<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('roles.manage');
requirePermission('manage_roles');

require_once __DIR__ . '/../config/database.php';

if (!isset($_GET['id'])) {
    die("Role ID missing.");
}

$roleId = (int)$_GET['id'];

/* =============================
   FETCH ROLE
============================= */
$stmt = $pdo->prepare("SELECT * FROM roles WHERE id = ?");
$stmt->execute([$roleId]);
$role = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$role) {
    die("Role not found.");
}

/* =============================
   HANDLE SAVE
============================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $selected = $_POST['permissions'] ?? [];

    $pdo->beginTransaction();

    $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?")
        ->execute([$roleId]);

    if (!empty($selected)) {
        $insert = $pdo->prepare("
            INSERT INTO role_permissions (role_id, permission_id)
            VALUES (?, ?)
        ");

        foreach ($selected as $permissionId) {
            $insert->execute([$roleId, (int)$permissionId]);
        }
    }

    $pdo->commit();

    header("Location: roles.php");
    exit;
}

/* =============================
   FETCH ALL PERMISSIONS
============================= */
$permissions = $pdo->query("
    SELECT * FROM permissions
    ORDER BY group_name ASC, name ASC
")->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   GROUP PERMISSIONS
============================= */
$groupedPermissions = [];

foreach ($permissions as $perm) {
    $group = $perm['group_name'] ?: 'General';
    $groupedPermissions[$group][] = $perm;
}

/* =============================
   FETCH CURRENT ROLE PERMISSIONS
============================= */
$current = $pdo->prepare("
    SELECT permission_id
    FROM role_permissions
    WHERE role_id = ?
");
$current->execute([$roleId]);

$currentPermissions = array_column(
    $current->fetchAll(PDO::FETCH_ASSOC),
    'permission_id'
);

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<style>

/* SEARCH */
.permission-search {
    margin-bottom:20px;
}

.permission-search input {
    width:100%;
    padding:10px 12px;
    border-radius:6px;
    border:1px solid #ddd;
}

/* STICKY SAVE */
.sticky-save {
    position:fixed;
    bottom:0;
    left:0;
    width:100%;
    background:white;
    border-top:1px solid #e5e7eb;
    padding:15px 25px;
    display:flex;
    justify-content:flex-end;
    box-shadow:0 -4px 15px rgba(0,0,0,0.05);
    z-index:999;
}

/* GROUP */
.permission-section {
    margin-top:25px;
    border:1px solid #e5e7eb;
    border-radius:8px;
}

.permission-header {
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:12px 16px;
    background:#f9fafb;
    cursor:pointer;
}

.permission-header h3 {
    font-size:14px;
    margin:0;
    text-transform:uppercase;
    color:#6b7280;
}

.permission-count {
    font-size:12px;
    background:#f2531e;
    color:white;
    padding:2px 8px;
    border-radius:12px;
    margin-left:8px;
}

.permission-body {
    padding:15px 20px;
    display:block;
}

.permission-grid {
    display:grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap:8px 30px;
}

.permission-card {
    display:flex;
    align-items:center;
    gap:10px;
}

.permission-card input[type="checkbox"] {
    width:18px;
    height:18px;
    accent-color:#f2531e;
}

.permission-card label {
    font-size:14px;
    cursor:pointer;
}

.select-group-btn {
    font-size:12px;
    background:#f3f4f6;
    border:none;
    padding:6px 10px;
    cursor:pointer;
    border-radius:4px;
}

.select-group-btn:hover {
    background:#e5e7eb;
}

.collapsed .permission-body {
    display:none;
}

</style>

<div class="main-content">

    <div class="page-header">
        <h2>Manage Permissions</h2>
        <p class="page-subtitle">
            Role: <strong><?= htmlspecialchars($role['name']) ?></strong>
        </p>
    </div>

    <form method="POST" class="card-form">

        <!-- SEARCH -->
        <div class="permission-search">
            <input type="text" id="permissionSearch" placeholder="Search permissions...">
        </div>

        <?php foreach ($groupedPermissions as $group => $perms): ?>
            <div class="permission-section" data-group="<?= htmlspecialchars($group) ?>">

                <div class="permission-header">
                    <div>
                        <h3>
                            <?= htmlspecialchars($group) ?>
                            <span class="permission-count">
                                <?= count($perms) ?>
                            </span>
                        </h3>
                    </div>

                    <?php if ($roleId !== 1): ?>
                        <button type="button"
                                class="select-group-btn"
                                data-group="<?= htmlspecialchars($group) ?>">
                            Select All
                        </button>
                    <?php endif; ?>
                </div>

                <div class="permission-body">
                    <div class="permission-grid">
                        <?php foreach ($perms as $p): ?>
                            <div class="permission-card">
                                <input type="checkbox"
                                       class="group-checkbox permission-item"
                                       data-group="<?= htmlspecialchars($group) ?>"
                                       name="permissions[]"
                                       value="<?= (int)$p['id'] ?>"
                                       <?= in_array($p['id'], $currentPermissions) ? 'checked' : '' ?>
                                       <?= $roleId === 1 ? 'disabled' : '' ?>>
                                <label>
                                    <?= htmlspecialchars(
    $p['name'] ?: ucwords(str_replace('_',' ',$p['code']))
) ?>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

            </div>
        <?php endforeach; ?>

        <div class="sticky-save">
            <button type="submit" class="btn-primary">
                Save Permissions
            </button>
        </div>

    </form>

</div>

<script>

/* COLLAPSIBLE GROUPS */
document.querySelectorAll('.permission-header').forEach(header => {
    header.addEventListener('click', function(e) {
        if (!e.target.classList.contains('select-group-btn')) {
            this.parentElement.classList.toggle('collapsed');
        }
    });
});

/* SELECT ALL */
document.querySelectorAll('.select-group-btn').forEach(button => {
    button.addEventListener('click', function(e) {
        e.stopPropagation();
        const group = this.dataset.group;
        const checkboxes = document.querySelectorAll(
            '.group-checkbox[data-group="' + group + '"]'
        );
        let allChecked = true;
        checkboxes.forEach(cb => {
            if (!cb.checked) allChecked = false;
        });
        checkboxes.forEach(cb => {
            cb.checked = !allChecked;
        });
    });
});

/* SEARCH FILTER */
document.getElementById('permissionSearch').addEventListener('keyup', function() {
    const value = this.value.toLowerCase();
    document.querySelectorAll('.permission-card').forEach(card => {
        const text = card.innerText.toLowerCase();
        card.style.display = text.includes(value) ? 'flex' : 'none';
    });
});

</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>