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

namespace App\Models;

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

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

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

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // Relationships
    public function createdClients()
    {
        return $this->hasMany(Client::class, 'created_by');
    }

    public function approvedClients()
    {
        return $this->hasMany(Client::class, 'approved_by');
    }

    /**
     * Get user permissions
     */
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'permission_user')
            ->withPivot('actions')
            ->withTimestamps();
    }

    /**
     * Check if user has permission with specific action
     */
    public function hasPermission($slug, $action = null): bool
    {
        $permission = $this->permissions->firstWhere('slug', $slug);

        if (!$permission) {
            return false;
        }

        if ($action === null) {
            return true;
        }

        $userPermission = $this->permissions->find($permission->id);
        $actions = $userPermission->pivot->actions ? json_decode($userPermission->pivot->actions, true) : [];

        return in_array($action, $actions);
    }

    /**
     * Check if user has any of the given permissions
     */
    public function hasAnyPermission(array $permissions): bool
    {
        foreach ($permissions as $permission) {
            if ($this->hasPermission($permission)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if user has all of the given permissions
     */
    public function hasAllPermissions(array $permissions): bool
    {
        foreach ($permissions as $permission) {
            if (!$this->hasPermission($permission)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Get user's permissions grouped by module
     */
    public function getPermissionsByModule()
    {
        return $this->permissions->groupBy('module');
    }

    /**
     * Dashboard Access Permission Methods
     */
    public function canAccessDashboard(): bool
    {
        return $this->hasPermission('dashboard.view');
    }

    public function canAccessClients(): bool
    {
        return $this->hasAnyPermission(['clients.view', 'clients.create', 'clients.edit', 'clients.delete']);
    }

    public function canAccessLoans(): bool
    {
        return $this->hasAnyPermission(['loans.view', 'loans.create', 'loans.edit', 'loans.delete', 'loans.approve']);
    }

    public function canAccessSavings(): bool
    {
        return $this->hasAnyPermission(['savings.accounts.view', 'savings.accounts.create', 'savings.deposit', 'savings.withdraw']);
    }

    public function canAccessAccounting(): bool
    {
        return $this->hasAnyPermission([
            'accounting.ledger', 'accounting.journals', 'accounting.cashbook',
            'accounting.invoices', 'accounting.receipts'
        ]);
    }

    public function canAccessReports(): bool
    {
        return $this->hasAnyPermission(['reports.financial', 'reports.loans', 'reports.savings', 'reports.audit', 'reports.compliance']);
    }

    public function canAccessProcessing(): bool
    {
        return $this->hasAnyPermission(['processing.invoicing', 'processing.receipts', 'processing.payments']);
    }

    public function canAccessAdministration(): bool
    {
        return $this->hasAnyPermission([
            'administration.settings', 'administration.backup', 'administration.roles',
            'users.view', 'permissions.manage', 'company-settings.view'
        ]);
    }

    public function canAccessUserManagement(): bool
    {
        return $this->hasAnyPermission(['users.view', 'users.create', 'users.edit', 'users.delete']);
    }

    public function canAccessProfile(): bool
    {
        return $this->hasPermission('profile.view');
    }

    /**
     * Get permission count for display
     */
    public function getPermissionCountAttribute()
    {
        return $this->permissions->count();
    }

    /**
     * Get all permission slugs for this user
     */
    public function getAllPermissionSlugs()
    {
        return $this->permissions->pluck('slug')->toArray();
    }

    // Simple role check methods (for reference only)
    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }

    public function isLoanOfficer(): bool
    {
        return $this->role === 'loan_officer';
    }

    public function isTeller(): bool
    {
        return $this->role === 'teller';
    }

    public function isAuditor(): bool
    {
        return $this->role === 'auditor';
    }

    public function isCustomer(): bool
    {
        return $this->role === 'customer';
    }
}
