<?php

namespace App\Models;

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',
        'mobile',
        'password',
        'role_id',
        'region',
    ];

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

    protected $casts = [
        'password' => 'hashed',
    ];

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    // Hierarchy: User as Head has many members
    public function members()
    {
        return $this->belongsToMany(User::class, 'team_members', 'head_id', 'member_id');
    }

    // Hierarchy: User as Member has one Head
    public function head()
    {
        return $this->belongsToMany(User::class, 'team_members', 'member_id', 'head_id');
    }

    // Assignments
    public function assignedLeads()
    {
        return $this->belongsToMany(Lead::class, 'lead_assignments')
            ->withPivot('accepted_at', 'rejected_at')
            ->withTimestamps();
    }

    public function assignedBusinesses()
    {
        return $this->belongsToMany(Business::class, 'business_assignments')->withTimestamps();
    }

    public function assignedProjects()
    {
        return $this->belongsToMany(Project::class, 'project_assignments')->withTimestamps();
    }

    public function createdBusinesses()
    {
        return $this->hasMany(Business::class, 'created_by');
    }

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

    public function createdProjects()
    {
        return $this->hasMany(Project::class, 'created_by');
    }

    public function assignedTasks()
    {
        return $this->hasMany(Task::class, 'assigned_to');
    }

    public function isAdmin()
    {
        return $this->role->name === 'admin';
    }

    public function isHead()
    {
        return $this->role->name === 'head';
    }

    public function isTeamMember()
    {
        return $this->role->name === 'team';
    }

    public function hasModuleAccess($module)
    {
        // Admin has access to all modules
        if ($this->isAdmin()) {
            return true;
        }

        // Check if the user's role has this module in permissions
        $permissions = $this->role->permissions ?? [];
        return in_array($module, $permissions);
    }

    public function getPermissionsAttribute()
    {
        // Permissions are now role-based or derived from assignments
        return $this->role->permissions ?? [];
    }

    public function messages()
    {
        return $this->hasMany(Message::class);
    }
}
