<?php
/**
 * Gestion des droits par rôle — Matrice de permissions
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin']);

// Pages gérées avec leurs libellés
$pages = [
    // Admin
    'schools'      => ['label' => 'Écoles',        'group' => 'Administration'],
    'classes'      => ['label' => 'Classes',        'group' => 'Administration'],
    'students'     => ['label' => 'Élèves',         'group' => 'Administration'],
    'teachers'     => ['label' => 'Enseignants',    'group' => 'Administration'],
    'attestation'  => ['label' => 'Attestation scolaire', 'group' => 'Administration'],
    'grades'       => ['label' => 'Notes / Saisie',  'group' => 'Administration'],
    'subjects'     => ['label' => 'Matières',       'group' => 'Administration'],
    'payments'     => ['label' => 'Paiements',      'group' => 'Administration'],
    'payment_history' => ['label' => 'Historique paiements', 'group' => 'Administration'],
    'users'        => ['label' => 'Utilisateurs',   'group' => 'Administration'],
    'permissions'  => ['label' => 'Droits/Rôles',  'group' => 'Administration'],
    // Portail
    'portal_dashboard' => ['label' => 'Tableau de bord',    'group' => 'Portail'],
    'portal_grades'    => ['label' => 'Notes / Bulletins',  'group' => 'Portail'],
    'portal_payments'  => ['label' => 'Paiements',          'group' => 'Portail'],
    'portal_profile'   => ['label' => 'Profil',             'group' => 'Portail'],
    'portal_children'  => ['label' => 'Mes enfants',        'group' => 'Portail'],
];

// Rôles modifiables (super_admin a toujours tous les droits, non éditable)
$editableRoles = [
    'school_admin' => 'Directeur',
    'teacher'      => 'Professeur',
    'accountant'   => 'Comptable',
    'student'      => 'Élève',
    'parent'       => 'Parent',
];

$actions = ['can_view' => 'Voir', 'can_create' => 'Créer', 'can_edit' => 'Modifier', 'can_delete' => 'Supprimer'];

// ── Sauvegarde ────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    checkRole(['super_admin']);

    $upsert = $pdo->prepare(
        "INSERT INTO role_permissions (role, page, can_view, can_create, can_edit, can_delete)
         VALUES (?, ?, ?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE
           can_view   = VALUES(can_view),
           can_create = VALUES(can_create),
           can_edit   = VALUES(can_edit),
           can_delete = VALUES(can_delete)"
    );

    foreach ($editableRoles as $role => $label) {
        foreach (array_keys($pages) as $page) {
            $view   = isset($_POST['perm'][$role][$page]['can_view'])   ? 1 : 0;
            $create = isset($_POST['perm'][$role][$page]['can_create']) ? 1 : 0;
            $edit   = isset($_POST['perm'][$role][$page]['can_edit'])   ? 1 : 0;
            $delete = isset($_POST['perm'][$role][$page]['can_delete']) ? 1 : 0;
            $upsert->execute([$role, $page, $view, $create, $edit, $delete]);
        }
    }

    // Invalider le cache des permissions pour tous les rôles
    clearPermissionCache();
    flashMessage('success', 'Permissions mises à jour avec succès.');
    header('Location: permissions.php'); exit;
}

// ── Chargement des permissions actuelles ──────────────────────────────────────
$currentPerms = [];
$rows = $pdo->query("SELECT role, page, can_view, can_create, can_edit, can_delete FROM role_permissions ORDER BY role, page")->fetchAll();
foreach ($rows as $row) {
    $currentPerms[$row['role']][$row['page']] = $row;
}

// Grouper les pages
$groups = [];
foreach ($pages as $pageKey => $pageMeta) {
    $groups[$pageMeta['group']][$pageKey] = $pageMeta['label'];
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Droits & Permissions - Nukunu Mofiala</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-shield-alt"></i> Droits &amp; Permissions par rôle'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <div class="card">
            <p style="color:#718096; margin-bottom:1.5rem;">
                <i class="fas fa-info-circle"></i>
                Le <strong>Super Admin</strong> a tous les droits et ne peut pas être modifié.
                Cochez les cases pour accorder l'accès à chaque rôle.
            </p>

            <form method="POST">
                <?= csrfField() ?>

                <?php foreach ($groups as $groupName => $groupPages): ?>
                <div class="perm-group">
                    <div class="perm-group-title">
                        <i class="fas fa-<?= $groupName === 'Portail' ? 'user-circle' : 'cogs' ?>"></i>
                        <?= e($groupName) ?>
                    </div>

                    <div class="perm-matrix-wrap">
                        <table class="perm-matrix">
                            <thead>
                                <tr>
                                    <th class="perm-page-col">Page / Module</th>
                                    <?php foreach ($editableRoles as $role => $label): ?>
                                    <th class="perm-role-col" colspan="4">
                                        <span class="badge <?= getRoleBadgeClass($role) ?>"><?= e($label) ?></span>
                                    </th>
                                    <?php endforeach; ?>
                                </tr>
                                <tr>
                                    <th></th>
                                    <?php foreach ($editableRoles as $role => $label): ?>
                                    <?php foreach ($actions as $actKey => $actLabel): ?>
                                    <th class="perm-action-col"><?= e($actLabel) ?></th>
                                    <?php endforeach; ?>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($groupPages as $pageKey => $pageLabel): ?>
                                <tr class="perm-row">
                                    <td class="perm-page-label">
                                        <i class="fas fa-file-alt"></i> <?= e($pageLabel) ?>
                                    </td>
                                    <?php foreach ($editableRoles as $role => $label): ?>
                                    <?php foreach (array_keys($actions) as $actKey): ?>
                                    <td class="perm-cell">
                                        <?php
                                        $checked = ($currentPerms[$role][$pageKey][$actKey] ?? 0) ? 'checked' : '';
                                        // Désactiver "créer/modifier/supprimer" si "voir" n'est pas coché (logique UI)
                                        $isView = $actKey === 'can_view';
                                        ?>
                                        <input type="checkbox"
                                               class="perm-check"
                                               name="perm[<?= $role ?>][<?= $pageKey ?>][<?= $actKey ?>]"
                                               value="1"
                                               <?= $checked ?>
                                               data-role="<?= $role ?>"
                                               data-page="<?= $pageKey ?>"
                                               data-action="<?= $actKey ?>">
                                    </td>
                                    <?php endforeach; ?>
                                    <?php endforeach; ?>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endforeach; ?>

                <div style="margin-top:1.5rem; display:flex; gap:1rem; align-items:center;">
                    <button type="submit" class="btn-submit" style="width:auto; padding:.75rem 2rem;">
                        <i class="fas fa-save"></i> Enregistrer les permissions
                    </button>
                    <button type="button" id="btnSelectAll" class="btn-action btn-view">
                        <i class="fas fa-check-double"></i> Tout sélectionner
                    </button>
                    <button type="button" id="btnClearAll" class="btn-action btn-delete">
                        <i class="fas fa-times"></i> Tout désélectionner
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Tout cocher / décocher
document.getElementById('btnSelectAll').addEventListener('click', () => {
    document.querySelectorAll('.perm-check').forEach(cb => cb.checked = true);
});
document.getElementById('btnClearAll').addEventListener('click', () => {
    document.querySelectorAll('.perm-check').forEach(cb => cb.checked = false);
});

// Logique : si "Voir" est décoché, décocher les autres actions
document.querySelectorAll('.perm-check[data-action="can_view"]').forEach(viewCb => {
    viewCb.addEventListener('change', function() {
        if (!this.checked) {
            const role = this.dataset.role;
            const page = this.dataset.page;
            document.querySelectorAll(
                `.perm-check[data-role="${role}"][data-page="${page}"]`
            ).forEach(cb => cb.checked = false);
        }
    });
});

// Si on coche créer/modifier/supprimer, cocher aussi "voir"
document.querySelectorAll('.perm-check:not([data-action="can_view"])').forEach(cb => {
    cb.addEventListener('change', function() {
        if (this.checked) {
            const role = this.dataset.role;
            const page = this.dataset.page;
            const viewCb = document.querySelector(
                `.perm-check[data-role="${role}"][data-page="${page}"][data-action="can_view"]`
            );
            if (viewCb) viewCb.checked = true;
        }
    });
});
</script>
</body>
</html>
