<?php
require('connection.inc.php');

if (isset($_POST['role_id'])) {
    $roleId = $_POST['role_id'];

    // Fetch assigned permissions for the selected role
    $query = "
        SELECT p.permission_id, p.permission_name, 
               CASE WHEN rp.role_id IS NOT NULL THEN 1 ELSE 0 END AS is_assigned
        FROM permissions p
        LEFT JOIN role_permissions rp ON p.permission_id = rp.permission_id AND rp.role_id = ?
    ";  

    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $roleId);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $checked = $row['is_assigned'] ? 'checked' : '';
        echo "<div>
                <input type='checkbox' name='permissions[]' value='{$row['permission_id']}' $checked>
                <label>{$row['permission_name']}</label>
              </div>";
    }

    $stmt->close();
}
?>
