<?php

class Permission extends Model {

    // Get all permissions
    public function getAll() {
        $this->db->query("SELECT * FROM permissions ORDER BY module ASC, name ASC");
        return $this->db->resultSet();
    }

    // Get all permissions grouped by module (useful for the edit role UI)
    public function getAllGrouped() {
        $permissions = $this->getAll();
        $grouped = [];
        foreach ($permissions as $p) {
            $grouped[$p->module][] = $p;
        }
        return $grouped;
    }
    
    // Check if a user has a specific permission (Helper for Auth)
    public function userHasPermission($user_id, $permission_name) {
        // Get user role first
        $this->db->query("SELECT role FROM users WHERE id = :user_id");
        $this->db->bind(':user_id', $user_id);
        $user = $this->db->single();
        
        if (!$user) return false;
        
        // Super admin bypass
        if ($user->role === 'super_admin') return true;

        // Check permission via role
        $this->db->query("SELECT COUNT(*) as count 
                          FROM role_permissions rp
                          JOIN roles r ON rp.role_id = r.id
                          JOIN permissions p ON rp.permission_id = p.id
                          WHERE r.name = :role_name AND p.name = :perm_name");
        $this->db->bind(':role_name', $user->role);
        $this->db->bind(':perm_name', $permission_name);
        
        return $this->db->single()->count > 0;
    }

    // Get all permissions for a specific user (for session caching)
    public function getUserPermissions($user_id) {
        // Get user role first
        $this->db->query("SELECT role FROM users WHERE id = :user_id");
        $this->db->bind(':user_id', $user_id);
        $user = $this->db->single();
        
        if (!$user) return [];
        
        $this->db->query("SELECT p.name 
                          FROM role_permissions rp
                          JOIN roles r ON rp.role_id = r.id
                          JOIN permissions p ON rp.permission_id = p.id
                          WHERE r.name = :role_name");
        $this->db->bind(':role_name', $user->role);
        
        $results = $this->db->resultSet();
        return array_map(function($row) { return $row->name; }, $results);
    }
}