<?php

namespace App\Models;

use CodeIgniter\Model;

class RolePermissionModel extends Model
{
    protected $table = 'role_permissions'; // Define the table associated with this model
    protected $primaryKey = 'id'; // Define the primary key of the table
    protected $allowedFields = [
        'role_id', 
        'permission_id', 
        'can_create', 
        'can_read', 
        'can_update', 
        'can_delete',
        'can_manage',
        'created_at',
        'updated_at'
    ]; // Define the fields that can be set using insert/update methods
    
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    
   
    /**
     * Fetch all role permissions with optional limit and offset
     * 
     * @param int $limit Number of records to return
     * @param int $offset Number of records to skip
     * @return array List of role permissions
     * @throws \Exception If there is an error during the fetch
     */
    /**
     * Fetch permissions assigned to a specific role
     * 
     * @param int $role_id The ID of the role
     * @return array List of permissions associated with the role
     * @throws \Exception If there is an error during the fetch
     */
    public function getRolePermissions($role_id)
    {
        try {
            // Query to get role permissions based on role ID
            return $this->where('role_id', $role_id)->findAll();
        } catch (\Exception $e) {
            // Log the error message if the query fails
            log_message('error', 'Error fetching role permissions for role ID: ' . $role_id . ': ' . $e->getMessage());
            // Rethrow the exception to be handled by the caller
            throw $e;
        }
    }

    public function getPermissionsByRole($roleId)
    {
        return $this->where('role_id', $roleId)->findAll();
    }

    public function deleteByRole($roleId)
    {
        return $this->where('role_id', $roleId)->delete();
    }
}
