<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Role;

class UserAccess extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'access_type_id',
        'role_id',           
        'specific_user_id',  
    ];

    /**
     * Get the user that owns the access record.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the access type for this record.
     */
    public function accessType()
    {
        return $this->belongsTo(AccessType::class);
    }

    /**
     * Get the role for this access record.
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    /**
     * Get the specific user for this access record.
     */
    public function specificUser()
    {
        return $this->belongsTo(User::class, 'specific_user_id');
    }

    /**
     * Get all roles for a specific user across all their access records.
     * This is a helper method to get roles like the old JSON approach.
     */
    public static function getRolesForUser($userId)
    {
        return static::where('user_id', $userId)
            ->whereNotNull('role_id')
            ->with('role')
            ->get()
            ->pluck('role')
            ->filter();
    }

    /**
     * Get all specific users for a user across all their access records.
     * This is a helper method to get specific users like the old JSON approach.
     */
    public static function getSpecificUsersForUser($userId)
    {
        return static::where('user_id', $userId)
            ->whereNotNull('specific_user_id')
            ->with('specificUser')
            ->get()
            ->pluck('specificUser')
            ->filter();
    }

    /**
     * Check if a user has a specific role.
     */
    public static function userHasRole($userId, $roleId)
    {
        return static::where('user_id', $userId)
            ->where('role_id', $roleId)
            ->exists();
    }

    /**
     * Check if a user has access to a specific user.
     */
    public static function userHasAccessToUser($userId, $specificUserId)
    {
        return static::where('user_id', $userId)
            ->where('specific_user_id', $specificUserId)
            ->exists();
    }

    /**
     * Get all user access records with their relationships.
     * Useful for displaying user permissions.
     */
    public static function getCompleteAccessForUser($userId)
    {
        return static::where('user_id', $userId)
            ->with(['accessType', 'role', 'specificUser'])
            ->get();
    }
    
}