<?php
// application/models/Permission_model.php
class Permission_model extends CI_Model {

    // Check if a role has access to a specific section
    public function has_access($role_id, $section) {
        return $this->db->get_where('permissions', ['role_id' => $role_id, 'section' => $section])->row();
    }

    // Update permissions for a given role
    public function update_permissions($role_id, $sections) {
        // First, check if $sections is not empty or null
        if (empty($sections)) {
            return;  // No sections to update, so we simply return
        }

        // Delete existing permissions for the role
        $this->db->delete('permissions', ['role_id' => $role_id]);

        // Insert new permissions
        foreach ($sections as $section) {
            $this->db->insert('permissions', ['role_id' => $role_id, 'section' => $section]);
        }
    }

    // Get all permissions for a given role
    public function get_permissions_by_role($role_id) {
        // Select the 'section' field from the permissions table
        $this->db->select('section');
        $this->db->from('permissions');
        $this->db->where('role_id', $role_id);
        
        // Run the query
        $query = $this->db->get();
        
        // Return an array of sections for the given role, if any
        return $query->num_rows() > 0 ? array_column($query->result_array(), 'section') : [];
    }
}
