<?php

class Role extends Model {
    
    // Get all roles
    public function getAll() {
        $this->db->query("SELECT * FROM roles ORDER BY name ASC");
        return $this->db->resultSet();
    }

    // Get role by ID
    public function getById($id) {
        $this->db->query("SELECT * FROM roles WHERE id = :id");
        $this->db->bind(':id', $id);
        return $this->db->single();
    }

    // Create a new role
    public function create($data) {
        $this->db->query("INSERT INTO roles (name, description) VALUES (:name, :description)");
        $this->db->bind(':name', $data['name']);
        $this->db->bind(':description', $data['description']);
        return $this->db->execute();
    }

    // Update a role
    public function update($id, $data) {
        $this->db->query("UPDATE roles SET name = :name, description = :description WHERE id = :id");
        $this->db->bind(':name', $data['name']);
        $this->db->bind(':description', $data['description']);
        $this->db->bind(':id', $id);
        return $this->db->execute();
    }

    // Delete a role
    public function delete($id) {
        $this->db->query("DELETE FROM roles WHERE id = :id");
        $this->db->bind(':id', $id);
        return $this->db->execute();
    }

    // Get permissions assigned to a role
    public function getPermissions($role_id) {
        $this->db->query("SELECT p.* FROM permissions p 
                          JOIN role_permissions rp ON p.id = rp.permission_id 
                          WHERE rp.role_id = :role_id");
        $this->db->bind(':role_id', $role_id);
        return $this->db->resultSet();
    }

    // Assign permissions to a role (sync)
    public function syncPermissions($role_id, $permission_ids) {
        // First, remove all existing permissions
        $this->db->query("DELETE FROM role_permissions WHERE role_id = :role_id");
        $this->db->bind(':role_id', $role_id);
        $this->db->execute();

        // Then add the new ones
        if (!empty($permission_ids)) {
            foreach ($permission_ids as $perm_id) {
                $this->db->query("INSERT INTO role_permissions (role_id, permission_id) VALUES (:role_id, :permission_id)");
                $this->db->bind(':role_id', $role_id);
                $this->db->bind(':permission_id', $perm_id);
                $this->db->execute();
            }
        }
        return true;
    }
}