<?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;

    protected $fillable = [
        'name',
        'email',
        'password',
        'role_id',
        'department_id',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function roleRecord()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }

    public function department()
    {
        return $this->belongsTo(Department::class);
    }

    public function moduleOverrides()
    {
        return $this->hasMany(UserModuleOverride::class);
    }

    public function leadViews()
    {
        return $this->hasMany(LeadView::class);
    }

    public function leadRemarks()
    {
        return $this->hasMany(LeadRemark::class);
    }

    public function isPlatformAdmin(): bool
    {
        return $this->roleRecord && $this->roleRecord->is_platform_admin;
    }

    public function assignedLeads()
    {
        return $this->hasMany(Lead::class, 'assigned_to_user_id');
    }

    public function isMarketingTeam(): bool
    {
        return $this->department && $this->department->slug === 'marketing';
    }

    public static function marketingTeamMembers()
    {
        return static::with('department')
            ->whereHas('department', function ($q) {
                $q->where('slug', 'marketing')->where('is_active', true);
            })
            ->whereHas('roleRecord', function ($q) {
                $q->where('is_platform_admin', false);
            })
            ->orderBy('name')
            ->get();
    }

    public function isDesignTeam(): bool
    {
        return $this->department
            && in_array($this->department->slug, config('departments.design_team_slugs', []), true);
    }

    public static function designTeamMembers()
    {
        $slugs = config('departments.design_team_slugs', []);

        return static::with('department')
            ->whereHas('department', function ($q) use ($slugs) {
                $q->whereIn('slug', $slugs)->where('is_active', true);
            })
            ->whereHas('roleRecord', function ($q) {
                $q->where('is_platform_admin', false);
            })
            ->orderBy('name')
            ->get();
    }
}
