<?php
// C:\xampp\htdocs\odza\credora\app\Models\Permission.php

namespace App\Models;

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

class Permission extends Model
{
    use HasFactory;

    protected $fillable = [
        'module',
        'feature',
        'slug',
        'actions',
        'description',
    ];

    protected $casts = [
        'actions' => 'array',
    ];

    /**
     * Users who have this permission
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'permission_user')
            ->withPivot('actions')
            ->withTimestamps();
    }

    /**
     * Get formatted module name
     */
    public function getModuleNameAttribute(): string
    {
        return ucfirst(str_replace('_', ' ', $this->module));
    }

    /**
     * Get available actions as comma-separated list
     */
    public function getActionsListAttribute(): string
    {
        return $this->actions ? implode(', ', $this->actions) : 'None';
    }

    /**
     * Check if permission has specific action
     */
    public function hasAction($action): bool
    {
        return in_array($action, $this->actions ?? []);
    }

    /**
     * Get color based on module
     */
    public function getModuleColorAttribute()
    {
        $colors = [
            'dashboard' => 'primary',
            'clients' => 'success',
            'loans' => 'warning',
            'savings' => 'info',
            'accounting' => 'secondary',
            'reports' => 'dark',
            'processing' => 'primary',
            'administration' => 'danger',
            'user_management' => 'success',
            'profile' => 'info',
            'company_settings' => 'secondary',
        ];

        return $colors[$this->module] ?? 'secondary';
    }
}
