<?php
$moduleIcons = [
    'order'    => ['icon' => 'bag-check',      'color' => '#f97316'],
    'menu'     => ['icon' => 'menu-button-wide','color' => '#16a34a'],
    'user'     => ['icon' => 'people-fill',     'color' => '#2563eb'],
    'voucher'  => ['icon' => 'ticket-perforated','color'=> '#7c3aed'],
    'deal'     => ['icon' => 'tag-fill',        'color' => '#db2777'],
    'report'   => ['icon' => 'bar-chart-fill',  'color' => '#0891b2'],
    'settings' => ['icon' => 'gear-fill',       'color' => '#64748b'],
    'category' => ['icon' => 'grid-fill',       'color' => '#d97706'],
];
$totalInRole = count($assignedSet);
$totalAll    = array_sum(array_map('count', $grouped));
?>

<div class="page-header">
    <div>
        <a href="<?= url('roles') ?>" class="btn btn-outline-secondary btn-sm mb-2">
            <i class="bi bi-arrow-left me-1"></i>All Roles
        </a>
        <h1><i class="bi bi-shield-lock me-2"></i><?= e($role['label']) ?> — Permissions</h1>
        <p>Toggle which permissions this role has. Changes take effect immediately on save.</p>
    </div>
    <div class="text-end">
        <div class="fw-700 fs-4 text-accent" id="countDisplay"><?= $totalInRole ?></div>
        <div class="text-secondary" style="font-size:.75rem;">of <?= $totalAll ?> permissions</div>
    </div>
</div>

<?= flash_alert() ?>

<form method="POST" action="<?= url('roles/'.$role['id'].'/update') ?>">
<?= csrf_field() ?>

<!-- Quick actions -->
<div class="d-flex gap-2 mb-3 flex-wrap">
    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleAll(true)">
        <i class="bi bi-check-all me-1"></i>Select All
    </button>
    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleAll(false)">
        <i class="bi bi-x-lg me-1"></i>Clear All
    </button>
    <button type="submit" class="btn btn-accent btn-sm ms-auto px-4">
        <i class="bi bi-check-lg me-1"></i>Save Permissions
    </button>
</div>

<!-- Permission matrix grouped by module -->
<?php foreach ($grouped as $module => $perms): ?>
<?php $cfg = $moduleIcons[$module] ?? ['icon' => 'circle', 'color' => '#64748b']; ?>
<div class="card mb-3 p-0 overflow-hidden">
    <div class="card-header d-flex align-items-center gap-2"
         style="background:<?= $cfg['color'] ?>12;border-bottom:1px solid <?= $cfg['color'] ?>22;">
        <div style="width:28px;height:28px;border-radius:8px;background:<?= $cfg['color'] ?>22;
                    display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-<?= $cfg['icon'] ?>" style="color:<?= $cfg['color'] ?>;font-size:.9rem;"></i>
        </div>
        <h6 class="card-title mb-0" style="text-transform:capitalize;"><?= e($module) ?></h6>
        <span class="ms-auto text-secondary module-count" style="font-size:.75rem;"
              data-module="<?= e($module) ?>">
            <?= count(array_filter($perms, fn($p) => isset($assignedSet[$p['id']]))) ?>
            / <?= count($perms) ?>
        </span>
        <!-- Module-level toggle -->
        <button type="button" class="btn btn-link btn-sm p-0 ms-1 text-secondary"
                onclick="toggleModule('<?= e($module) ?>', this)" title="Toggle all in module">
            <i class="bi bi-toggle2-on"></i>
        </button>
    </div>
    <div class="card-body py-2 px-3">
        <div class="row g-0">
        <?php foreach ($perms as $p): ?>
        <?php $checked = isset($assignedSet[$p['id']]); ?>
        <div class="col-12 col-sm-6 col-lg-4">
            <label class="perm-label d-flex align-items-center gap-2 py-2 px-1 rounded"
                   style="cursor:pointer;font-size:.85rem;"
                   data-module="<?= e($module) ?>">
                <input type="checkbox" name="permissions[]"
                       value="<?= $p['id'] ?>"
                       class="form-check-input perm-cb flex-shrink-0"
                       <?= $checked ? 'checked' : '' ?>
                       onchange="updateCount()"
                       style="width:18px;height:18px;">
                <span>
                    <span class="fw-600"><?= e($p['label']) ?></span>
                    <span class="d-block text-secondary" style="font-size:.7rem;"><?= e($p['name']) ?></span>
                </span>
            </label>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endforeach; ?>

<div class="d-flex justify-content-between align-items-center mt-3">
    <a href="<?= url('roles') ?>" class="btn btn-outline-secondary">Cancel</a>
    <button type="submit" class="btn btn-accent px-5">
        <i class="bi bi-check-lg me-1"></i>Save Permissions
    </button>
</div>

</form>

<style>
.perm-label:hover { background: #f8fafc; }
.perm-label:has(input:checked) { background: #fff7ed; }
</style>

<script>
const totalAll = <?= $totalAll ?>;

function updateCount() {
    const total = document.querySelectorAll('.perm-cb:checked').length;
    document.getElementById('countDisplay').textContent = total;

    // Update per-module counts
    document.querySelectorAll('[data-module]').forEach(el => {
        if (!el.classList.contains('module-count')) return;
        const mod     = el.dataset.module;
        const all     = document.querySelectorAll(`.perm-label[data-module="${mod}"] .perm-cb`).length;
        const checked = document.querySelectorAll(`.perm-label[data-module="${mod}"] .perm-cb:checked`).length;
        el.textContent = checked + ' / ' + all;
    });
}

function toggleAll(state) {
    document.querySelectorAll('.perm-cb').forEach(cb => cb.checked = state);
    updateCount();
}

function toggleModule(mod, btn) {
    const boxes   = document.querySelectorAll(`.perm-label[data-module="${mod}"] .perm-cb`);
    const allOn   = [...boxes].every(cb => cb.checked);
    boxes.forEach(cb => cb.checked = !allOn);
    updateCount();
}
</script>
