<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\Security;

Auth::requireRole(['admin']);
$pageTitle = 'Roles & Staff Permissions | Admin';

$modules = ph_admin_modules();
$extraModules = [
    ['key' => 'feature-map', 'title' => 'Feature Map', 'group' => 'Security & System', 'description' => 'View the platform feature map.'],
    ['key' => 'control-panel-check', 'title' => 'Control Panel Health Check', 'group' => 'Security & System', 'description' => 'View deployment and environment diagnostics.'],
];
$permissionModules = array_merge($modules, $extraModules);

foreach ($permissionModules as $module) {
    Database::safeExecute(
        'INSERT INTO permissions (module,action,description,created_at)
         SELECT ?,"access",?,NOW()
         WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE module=? AND action="access")',
        [(string)$module['key'], (string)($module['description'] ?? $module['title']), (string)$module['key']]
    );
}

$roles = Database::safeFetchAll('SELECT * FROM roles WHERE code IN ("admin","staff") ORDER BY id');
$selectedRoleId = max(0, (int)($_GET['role_id'] ?? $_POST['role_id'] ?? 0));
if (!$selectedRoleId) {
    $staffRole = Database::safeFetchOne('SELECT id FROM roles WHERE code="staff" LIMIT 1');
    $selectedRoleId = (int)($staffRole['id'] ?? 0);
}
$selectedRole = $selectedRoleId ? Database::safeFetchOne('SELECT * FROM roles WHERE id=?', [$selectedRoleId]) : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) {
        set_flash('error', 'Invalid security token.');
    } elseif (!$selectedRole || (string)$selectedRole['code'] === 'admin') {
        set_flash('error', 'The Super Admin role cannot be restricted from this screen.');
    } else {
        $permissionIds = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['permission_ids'] ?? [])))));
        Database::transaction(function () use ($selectedRoleId, $permissionIds): void {
            Database::execute('DELETE FROM role_permissions WHERE role_id=?', [$selectedRoleId]);
            foreach ($permissionIds as $permissionId) {
                Database::execute(
                    'INSERT INTO role_permissions (role_id,permission_id) SELECT ?,id FROM permissions WHERE id=? LIMIT 1',
                    [$selectedRoleId, $permissionId]
                );
            }
        });
        Security::logActivity(Auth::id(), 'role_permissions_updated', [
            'role_id' => $selectedRoleId,
            'permission_count' => count($permissionIds),
        ]);
        set_flash('success', 'Role permissions updated.');
    }
    redirect('admin/roles.php?role_id=' . $selectedRoleId);
}

$permissionRows = Database::safeFetchAll('SELECT * FROM permissions WHERE action="access" ORDER BY module');
$permissionByModule = [];
foreach ($permissionRows as $permission) {
    $permissionByModule[(string)$permission['module']] = $permission;
}
$assigned = [];
if ($selectedRoleId) {
    foreach (Database::safeFetchAll('SELECT permission_id FROM role_permissions WHERE role_id=?', [$selectedRoleId]) as $row) {
        $assigned[(int)$row['permission_id']] = true;
    }
}

$grouped = [];
foreach ($permissionModules as $module) {
    $grouped[(string)($module['group'] ?? 'Other')][] = $module;
}

require_once ROOT_PATH . '/app/Layouts/admin_header.php';
?>
<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div><h1 class="h3 mb-1">Roles & Staff Permissions</h1><p class="text-muted mb-0">Grant staff access only to the administration modules they need.</p></div>
</div>

<div class="row g-4">
    <div class="col-lg-3">
        <div class="card module-card"><div class="card-header bg-white"><strong>Roles</strong></div><div class="list-group list-group-flush">
            <?php foreach ($roles as $role): ?>
                <a class="list-group-item list-group-item-action <?= (int)$role['id'] === $selectedRoleId ? 'active' : '' ?>" href="?role_id=<?= (int)$role['id'] ?>">
                    <strong><?= e($role['name']) ?></strong><div class="small <?= (int)$role['id'] === $selectedRoleId ? 'text-white-50' : 'text-muted' ?>"><?= e($role['code']) ?></div>
                </a>
            <?php endforeach; ?>
        </div></div>
    </div>
    <div class="col-lg-9">
        <div class="card module-card"><div class="card-body">
            <?php if (!$selectedRole): ?>
                <div class="alert alert-warning">Select a role.</div>
            <?php elseif ((string)$selectedRole['code'] === 'admin'): ?>
                <div class="alert alert-info mb-0">Super Admin always has full access and cannot be restricted.</div>
            <?php else: ?>
                <form method="post"><?= csrf_field() ?><input type="hidden" name="role_id" value="<?= (int)$selectedRoleId ?>">
                    <div class="d-flex flex-wrap justify-content-between gap-2 align-items-center mb-3">
                        <div><h4 class="mb-1"><?= e($selectedRole['name']) ?></h4><p class="text-muted mb-0"><?= e($selectedRole['description'] ?? '') ?></p></div>
                        <div><button type="button" class="btn btn-sm btn-outline-secondary" id="selectAll">Select all</button> <button type="button" class="btn btn-sm btn-outline-secondary" id="clearAll">Clear</button></div>
                    </div>
                    <?php foreach ($grouped as $group => $items): ?>
                        <div class="border rounded p-3 mb-3"><h5 class="mb-3"><?= e($group) ?></h5><div class="row g-3">
                            <?php foreach ($items as $module): $permission = $permissionByModule[(string)$module['key']] ?? null; if (!$permission) continue; ?>
                                <div class="col-md-6"><label class="d-flex gap-2 border rounded p-3 h-100">
                                    <input class="form-check-input permission-check" type="checkbox" name="permission_ids[]" value="<?= (int)$permission['id'] ?>" <?= isset($assigned[(int)$permission['id']]) ? 'checked' : '' ?>>
                                    <span><strong><?= e($module['title']) ?></strong><span class="d-block small text-muted mt-1"><?= e($module['description'] ?? '') ?></span></span>
                                </label></div>
                            <?php endforeach; ?>
                        </div></div>
                    <?php endforeach; ?>
                    <button class="btn btn-primary">Save permissions</button>
                </form>
            <?php endif; ?>
        </div></div>
    </div>
</div>
<script>
document.getElementById('selectAll')?.addEventListener('click',()=>document.querySelectorAll('.permission-check').forEach(el=>el.checked=true));
document.getElementById('clearAll')?.addEventListener('click',()=>document.querySelectorAll('.permission-check').forEach(el=>el.checked=false));
</script>
<?php require_once ROOT_PATH . '/app/Layouts/admin_footer.php'; ?>
