<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'is_system_admin',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'is_system_admin' => 'boolean',
    ];

    public function isSuperAdmin()
    {
        return (bool) $this->is_system_admin || $this->role === 'superadmin';
    }

    public function getRoleLabel()
    {
        $roles = Permission::getRoles();
        return $roles[$this->role]['label'] ?? $this->role;
    }

    public function getRoleColor()
    {
        $roles = Permission::getRoles();
        return $roles[$this->role]['color'] ?? 'secondary';
    }

    public function getPermissions()
    {
        if ($this->isSuperAdmin()) {
            return Permission::pluck('slug')->toArray();
        }

        return Cache::remember('user_permissions_' . $this->id . '_' . $this->role, 3600, function () {
            return \DB::table('role_permissions')
                ->join('permissions', 'role_permissions.permission_id', '=', 'permissions.id')
                ->where('role_permissions.role', $this->role)
                ->pluck('permissions.slug')
                ->toArray();
        });
    }

    public function hasPermission($permissionSlug)
    {
        if ($this->isSuperAdmin()) {
            return true;
        }

        $permissions = $this->getPermissions();
        return in_array($permissionSlug, $permissions);
    }

    public function hasModuleAccess($module)
    {
        if ($this->isSuperAdmin()) {
            return true;
        }

        $permissions = $this->getPermissions();
        $modulePermissions = Permission::where('module', $module)->pluck('slug')->toArray();

        foreach ($modulePermissions as $mp) {
            if (in_array($mp, $permissions)) {
                return true;
            }
        }
        return false;
    }

    public static function clearPermissionsCache()
    {
        $users = self::all();
        foreach ($users as $user) {
            Cache::forget('user_permissions_' . $user->id . '_' . $user->role);
        }
    }
}
