<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'first_name',
        'last_name',
        'email',
        'mobile',
        'employee_id',
        'department',
        'designation',
        'reporting_to',
        'branch_location',
        'access_scope',
        'avatar',
        'password',
        'role',
        'active',
        'is_locked',
        'two_factor_enabled',
        'joining_date',
        'last_login_at',
        'last_login_ip',
    ];

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

    protected $casts = [
        'active'             => 'boolean',
        'is_locked'          => 'boolean',
        'two_factor_enabled' => 'boolean',
        'password'           => 'hashed',
        'joining_date'       => 'date',
        'last_login_at'      => 'datetime',
    ];

    // Relationships
    public function leads(): HasMany
    {
        return $this->hasMany(Lead::class, 'assigned_to');
    }

    public function manager(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reporting_to');
    }

    public function directReports(): HasMany
    {
        return $this->hasMany(User::class, 'reporting_to');
    }

    public function roleModel(): BelongsTo
    {
        return $this->belongsTo(Role::class, 'role', 'slug');
    }

    public function permissionOverrides(): HasMany
    {
        return $this->hasMany(UserPermissionOverride::class, 'user_id');
    }

    public function auditLogs(): HasMany
    {
        return $this->hasMany(AuditLog::class, 'user_id');
    }

    public function loginHistories(): HasMany
    {
        return $this->hasMany(LoginHistory::class, 'user_id');
    }

    // RBAC & Permission Helper Methods
    public function isSuperAdmin(): bool
    {
        return $this->role === 'super-admin' || ($this->role === 'admin' && $this->id === 1);
    }

    public function isAdmin(): bool
    {
        return in_array($this->role, ['super-admin', 'admin']);
    }

    public function hasRole(string|array $roles): bool
    {
        if ($this->isSuperAdmin()) {
            return true;
        }

        if (is_array($roles)) {
            return in_array($this->role, $roles);
        }

        return $this->role === $roles;
    }

    public function hasPermission(string $permissionSlug): bool
    {
        // 1. Super Admin bypass
        if ($this->isSuperAdmin() || $this->isAdmin()) {
            return true;
        }

        // 2. Check User-specific Permission Overrides
        $override = $this->permissionOverrides()->where('permission_slug', $permissionSlug)->first();
        if ($override) {
            return (bool) $override->granted;
        }

        // 3. Fall back to Role Permissions
        $role = Role::where('slug', $this->role)->first();
        if ($role) {
            return $role->hasPermission($permissionSlug);
        }

        return false;
    }

    public function getEffectivePermissionScope(string $permissionSlug): string
    {
        if ($this->isSuperAdmin() || $this->isAdmin()) {
            return 'all';
        }

        // Check user override scope first
        $override = $this->permissionOverrides()->where('permission_slug', $permissionSlug)->first();
        if ($override && $override->granted) {
            return $override->access_scope ?? 'all';
        }

        // Check role permission scope
        $role = Role::where('slug', $this->role)->first();
        if ($role) {
            $rp = $role->rolePermissions()->where('permission_slug', $permissionSlug)->first();
            if ($rp) {
                return $rp->access_scope ?? 'all';
            }
        }

        return $this->access_scope ?? 'all';
    }

    public function canAccessLead(Lead $lead): bool
    {
        if (!$this->hasPermission('leads.view')) {
            return false;
        }

        $scope = $this->getEffectivePermissionScope('leads.view');

        return match($scope) {
            'all'        => true,
            'own'        => $lead->assigned_to === $this->id,
            'team'       => in_array($lead->assigned_to, array_merge([$this->id], $this->directReports()->pluck('id')->toArray())),
            'department' => in_array($lead->assigned_to, User::where('department', $this->department)->pluck('id')->toArray()),
            default      => true
        };
    }
}
