<?php

namespace Modules\Settings\Models;

use CodeIgniter\Model;

class UserPermissionsModel extends Model
{
    protected $table = 'user_permissions';
    protected $primaryKey = 'id';

    protected $allowedFields = ['user_id', 'permission_id', 'is_allowed'];

    protected $returnType     = 'array';
    protected $useTimestamps  = true;
    protected $useSoftDeletes = true;
    
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    public function getUserPermissions($userId)
    {
        return $this->select('permissions.module, user_permissions.is_allowed')
            ->join('permissions', 'permissions.id = user_permissions.permission_id')
            ->where('user_id', $userId)
            ->findAll();
    }

    // app/Models/AuthModel.php
    public function checkUserPermission($userId, $groupId, $permissionName)
    {
        // Check user-specific permissions first
        $userHasPermission = $this->db->table('user_permissions up')
            ->join('permissions p', 'up.permission_id = p.id')
            ->join('user_group_permissions ugp', 'upg.permission_id = p.id')
            ->where('up.user_id', $userId)
            ->where('ugp.group_id', $groupId)
            ->where('p.name', $permissionName)
            ->where('up.is_allowed', 1)
            ->countAllResults() > 0;
        
        if ($userHasPermission) return true;
        
        // Fallback to group permissions
        return $this->db->table('user_group_permissions ugp')
            ->join('permissions p', 'ugp.permission_id = p.id')
            ->where('ugp.group_id', $groupId)
            ->where('p.name', $permissionName)
            ->countAllResults() > 0;
    }

}