<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class RoleMaster extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'role_master';
    protected $primaryKey = 'Role_Id';
    public $timestamps = true;

    protected $fillable = [
        'Role_Prefix',
        'Role_Name',
        'TwoFacAuth',
        'Is_Active'
    ];

    protected $casts = [
        'Is_Active'  => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /* =====================
       VALIDATION
    ===================== */

    public static function createRules()
    {
        return [
            'Role_Prefix' => 'nullable|string|max:5',
            'Role_Name'   => 'required|string|max:25|unique:role_master,Role_Name',
            'TwoFacAuth'  => 'nullable|in:Y,N',
            'Is_Active'   => 'nullable|boolean',
        ];
    }

    public static function updateRules($id)
    {
        return [
            'Role_Prefix' => 'nullable|string|max:5',
            'Role_Name'   => 'sometimes|required|string|max:25|unique:role_master,Role_Name,' . $id . ',Role_Id',
            'TwoFacAuth'  => 'nullable|in:Y,N',
            'Is_Active'   => 'nullable|boolean',
        ];
    }

    public static function validationMessages()
    {
        return [
            'Role_Name.required' => 'Role Name is required',
            'Role_Name.max'      => 'Role Name should not exceed 25 characters',
            'Role_Name.unique'   => 'Role Name already exists',
            'Role_Prefix.max'    => 'Role Prefix should not exceed 5 characters',
            'TwoFacAuth.in'      => 'Two Factor Authentication must be either Y or N',
        ];
    }

    /* =====================
       RELATIONSHIPS
    ===================== */

    public function users()
    {
        return $this->belongsToMany(
            GmcUser::class,
            'user_role_mapping',
            'Role_Id',
            'U_Id',
            'Role_Id',
            'U_Id'
        )->withPivot('Default_Rid', 'URoleMap', 'created_at', 'updated_at');
    }

    public function userMappings()
    {
        return $this->hasMany(UserRoleMapping::class, 'Role_Id', 'Role_Id');
    }

    /* =====================
       COUNTS
    ===================== */

    public function userCount()
    {
        return $this->users()->count();
    }

    public function defaultUserCount()
    {
        return $this->users()
            ->wherePivot('Default_Rid', 1)
            ->count();
    }

    /* =====================
       SCOPES
    ===================== */

    public function scopeActive($query)
    {
        return $query->where('Is_Active', 1);
    }

    public function scopeInactive($query)
    {
        return $query->where('Is_Active', 0);
    }

    public function scopeSearch($query, $search)
    {
        return $query->where(function ($q) use ($search) {
            $q->where('Role_Name', 'like', "%{$search}%")
              ->orWhere('Role_Prefix', 'like', "%{$search}%")
              ->orWhere('TwoFacAuth', 'like', "%{$search}%");
        });
    }

    public function scopeWithUserCount($query)
    {
        return $query->withCount('users');
    }

    public function scopeWithDefaultUserCount($query)
    {
        return $query->withCount([
            'users as default_users_count' => function ($q) {
                $q->where('Default_Rid', 1);
            }
        ]);
    }

    /* =====================
       ACCESSORS
    ===================== */

    public function getTwoFactorAuthTextAttribute()
    {
        return $this->TwoFacAuth === 'Y'
            ? 'Enabled'
            : ($this->TwoFacAuth === 'N' ? 'Disabled' : 'Not Set');
    }

    public function getStatusTextAttribute()
    {
        return $this->Is_Active ? 'Active' : 'Inactive';
    }

    public function getFullRoleAttribute()
    {
        return trim(($this->Role_Prefix ? $this->Role_Prefix . ' - ' : '') . $this->Role_Name);
    }

    /* =====================
       BUSINESS LOGIC
    ===================== */

    public function canBeDeleted()
    {
        return $this->users()->count() === 0;
    }

    public function deactivate()
    {
        $this->update(['Is_Active' => 0]);
        return $this;
    }

    public function activate()
    {
        $this->update(['Is_Active' => 1]);
        return $this;
    }

    public function enableTwoFactorAuth()
    {
        $this->update(['TwoFacAuth' => 'Y']);
        return $this;
    }

    public function disableTwoFactorAuth()
    {
        $this->update(['TwoFacAuth' => 'N']);
        return $this;
    }
}
