<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'phone',
        'company_id',
        'project_id',
        'position',
        'is_active',
        'invitation_token',
        'invitation_accepted_at',
        'activation_token',
        'activation_token_sent_at',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'is_active' => 'boolean',
        'invitation_accepted_at' => 'datetime',
        'activation_token_sent_at' => 'datetime',
    ];

    /**
     * User roles constants
     */
    const ROLE_SOLICITANTE = 'solicitante';      // Cliente
    const ROLE_RESPONSABLE = 'responsable';      // Técnico N1
    const ROLE_INGENIERO = 'ingeniero';          // Ingeniero N2
    const ROLE_SUPERVISOR = 'supervisor';        // Supervisor N3
    const ROLE_ADMINISTRADOR = 'administrador';  // Administrador

    /**
     * Get all available roles
     */
    public static function getRoles()
    {
        return [
            self::ROLE_SOLICITANTE => 'Cliente',
            self::ROLE_RESPONSABLE => 'Técnico N1',
            self::ROLE_INGENIERO => 'Ingeniero N2',
            self::ROLE_SUPERVISOR => 'Supervisor N3',
            self::ROLE_ADMINISTRADOR => 'Administrador',
        ];
    }

    /**
     * Check if user has specific role(s)
     */
    public function hasRole($roles)
    {
        if (is_array($roles)) {
            return in_array($this->role, $roles);
        }
        return $this->role === $roles;
    }

    /**
     * Check if user can create tickets
     */
    public function canCreateTickets()
    {
        return in_array($this->role, [
            self::ROLE_SOLICITANTE,
            self::ROLE_RESPONSABLE,
            self::ROLE_INGENIERO,
            self::ROLE_SUPERVISOR,
            self::ROLE_ADMINISTRADOR
        ]);
    }

    /**
     * Check if user can assign tickets
     */
    public function canAssignTickets()
    {
        return in_array($this->role, [
            self::ROLE_INGENIERO,
            self::ROLE_SUPERVISOR,
            self::ROLE_ADMINISTRADOR
        ]);
    }

    /**
     * Check if user is admin
     */
    public function isAdmin()
    {
        return $this->role === self::ROLE_ADMINISTRADOR;
    }

    /**
     * Get tickets created by this user
     */
    public function createdTickets()
    {
        return $this->hasMany(Ticket::class, 'requester_id');
    }

    /**
     * Get tickets assigned to this user
     */
    public function assignedTickets()
    {
        return $this->hasMany(Ticket::class, 'assigned_to');
    }

    /**
     * Get comments by this user
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    /**
     * Proyectos asignados al usuario (many-to-many)
     */
    public function projects()
    {
        return $this->belongsToMany(Project::class, 'project_user')->withTimestamps();
    }

    /**
     * Verificar si el usuario tiene un proyecto asignado
     */
    public function hasProject($projectId)
    {
        return $this->projects()->where('project_id', $projectId)->exists();
    }

    /**
     * Obtener IDs de proyectos asignados
     */
    public function getAssignedProjectIds()
    {
        return $this->projects()->pluck('projects.id')->toArray();
    }

    /**
     * Get projects managed by this user
     */
    public function managedProjects()
    {
        return $this->hasMany(Project::class, 'manager_id');
    }

    /**
     * Get the company this user belongs to
     */
    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Get the project this user is assigned to
     */
    public function project()
    {
        return $this->belongsTo(Project::class);
    }
}