<?php

if (isset($_POST['assign_permission_btn'])) {
    $permission_id = $_POST['permission_id'];
    $selected_roles = isset($_POST['roles']) ? $_POST['roles'] : [];

    // Delete existing roles for this permission
    $delete_stmt = $connection->prepare("DELETE FROM role_permissions WHERE permission_id = ?");
    $delete_stmt->bind_param("i", $permission_id);
    $delete_stmt->execute();
    $delete_stmt->close();

    // Insert new ones
    if (!empty($selected_roles)) {
        $insert_stmt = $connection->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
        foreach ($selected_roles as $role_id) {
            $insert_stmt->bind_param("ii", $role_id, $permission_id);
            $insert_stmt->execute();
        }
        $insert_stmt->close();
    }

    $_SESSION['msg'] = "Permissions updated successfully.";
    $_SESSION['type'] = "success";
    header("Location: permissions");
    exit();
}
?>

<?php
if (isset($_POST['add_permission_btn'])) {
    $permission_name = trim($_POST['permission_name']);

    if (empty($permission_name)) {
        $_SESSION['msg'] = "Page name cannot be empty.";
        $_SESSION['type'] = "error";
    } else {
        // Prevent duplicate
        $check = $connection->prepare("SELECT id FROM permissions WHERE permission_name = ?");
        $check->bind_param("s", $permission_name);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {
            $_SESSION['msg'] = "This page already exists in permissions.";
            $_SESSION['type'] = "warning";
        } else {
            $stmt = $connection->prepare("INSERT INTO permissions (permission_name) VALUES (?)");
            $stmt->bind_param("s", $permission_name);

            if ($stmt->execute()) {
                $_SESSION['msg'] = "Page added to permissions successfully.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Failed to add page.";
                $_SESSION['type'] = "error";
            }
            $stmt->close();
        }

        $check->close();
    }

    header("Location: permissions"); // Redirect back to your permissions management page
    exit();
}
?>

<div class="page-title">
  <div>
    <h1><i class="fa fa-key"></i>Permissions</h1>
    <p>Assign Permission to Role</p>
  </div>
  
</div>
<div class="card">
    <div class="table-scrol">
        <div class='panel panel-primary ch'>
            <div class='panel-heading'>
                <h4 align="center">Assign Permissions to Role</h4>
            </div>
            <div class='panel-body'>
            <div class='mb-3 text-right'>
                        <button class="btn btn-success" data-toggle="modal" data-target="#addPermissionModal">➕ Add Permission</button>
                    </div>
                    <br />
<!-- Assign Permissions UI -->
    <?php
// Fetch all pages (permissions)
$permissions_query = "SELECT * FROM permissions ORDER BY id DESC";
$permissions_result = mysqli_query($connection, $permissions_query);

// Fetch all roles once
$roles_result = mysqli_query($connection, "SELECT * FROM role");
$roles = [];
while ($r = mysqli_fetch_assoc($roles_result)) {
    $roles[$r['id']] = $r['role_name'];
}
?>

<div class="table-responsive">
    <table class="table table-bordered table-hover" id ="myTable">
        <thead class="thead-dark">
            <tr>
                <th>#</th>
                <th>Page Name</th>
                <th>Assigned Roles</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $sn = 1;
        while ($perm = mysqli_fetch_assoc($permissions_result)) {
            $permission_id = $perm['id'];
            $permission_name = $perm['permission_name'];

            // Get roles assigned to this permission
            $role_stmt = $connection->prepare("
                SELECT role.role_name FROM role_permissions
                JOIN role ON role.id = role_permissions.role_id
                WHERE role_permissions.permission_id = ?
            ");
            $role_stmt->bind_param("i", $permission_id);
            $role_stmt->execute();
            $role_result = $role_stmt->get_result();

            $assigned_roles = [];
            while ($role_row = $role_result->fetch_assoc()) {
                $assigned_roles[] = $role_row['role_name'];
            }
            $role_stmt->close();

            echo "
                <tr>
                    <td>{$sn}</td>
                    <td><b>{$permission_name}</b></td>
                    <td>" . (empty($assigned_roles) ? "<i class='text-muted'>None</i>" : implode(', ', $assigned_roles)) . "</td>
                    <td>
                        <button class='btn btn-sm btn-primary' data-toggle='modal' data-target='#assignRoleModal{$permission_id}'>Assign Roles</button>
                    </td>
                </tr>
            ";

            // 🔽 Build the modal for assigning roles
            echo "
                <div class='modal fade' id='assignRoleModal{$permission_id}' tabindex='-1' role='dialog'>
                    <div class='modal-dialog' role='document'>
                        <form method='POST' action=''>
                            <div class='modal-content'>
                                <div class='modal-header bg-info text-white'>
                                    <h5 class='modal-title'>Assign Roles to <b>{$permission_name}</b></h5>
                                    <button type='button' class='close' data-dismiss='modal'>&times;</button>
                                </div>
                                <div class='modal-body'>
                                    <input type='hidden' name='permission_id' value='{$permission_id}'>
            ";

            foreach ($roles as $role_id => $role_name) {
                // Check if assigned
                $checked = in_array($role_name, $assigned_roles) ? "checked" : "";
                echo "
                    <div class='form-check'>
                        <input class='form-check-input' type='checkbox' name='roles[]' value='{$role_id}' id='role{$role_id}_{$permission_id}' {$checked}>
                        <label class='form-check-label' for='role{$role_id}_{$permission_id}'>{$role_name}</label>
                    </div>
                ";
            }

            echo "
                                </div>
                                <div class='modal-footer'>
                                    <button type='submit' name='assign_permission_btn' class='btn btn-success'>Save Changes</button>
                                    <button type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            ";

            $sn++;
        }
        ?>
        </tbody>
    </table>
</div>


<!-- Add Permission Modal -->
<div class="modal fade" id="addPermissionModal" tabindex="-1" role="dialog" aria-labelledby="addPermissionModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <form method="POST" action="">
      <div class="modal-content">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title" id="addPermissionModalLabel">Add New Page Permission</h5>
          <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
            <span>&times;</span>
          </button>
        </div>

        <div class="modal-body">
          <div class="form-group">
            <label for="permission_name">Page Name</label>
            <input type="text" name="permission_name" id="permission_name" class="form-control" placeholder="e.g., class, dashboard, settings" required>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" name="add_permission_btn" class="btn btn-success">Add Page</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </form>
  </div>
</div>

