<?php
/**
 * Liste des identifiants (email + mot de passe) par école et par classe
 */
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', 'school_admin']);

$schoolFilter = currentSchoolId();
$filterSchool = $_GET['filter_school'] ?? '';
$filterClass  = $_GET['filter_class'] ?? '';
$filterRole   = $_GET['filter_role'] ?? '';

// ── Regénérer un mot de passe ────────────────────────────────────────────────
if (isset($_GET['regenerate'], $_GET['uid'])) {
    verifyCsrf();
    $uid = (int)$_GET['uid'];
    $st = $pdo->prepare("SELECT id, name, role FROM users WHERE id=?");
    $st->execute([$uid]);
    $u = $st->fetch();
    if ($u) {
        $newPassword = bin2hex(random_bytes(4));
        $hash = password_hash($newPassword, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE users SET password=?, plain_password=? WHERE id=?")
            ->execute([$hash, $newPassword, $uid]);
        $phone = getUserPhone($pdo, $uid, $u['role']);
        if ($phone) {
            sendWhatsApp($phone, "Bonjour {$u['name']}, votre mot de passe Nukunu Mofiala a été réinitialisé. Nouveau mot de passe : $newPassword");
        }
        flashMessage('success', "Mot de passe régénéré pour {$u['name']} : <strong>$newPassword</strong>");
    }
    header('Location: credentials.php' . (!empty($filterSchool) ? "?filter_school=$filterSchool" : '?') . (!empty($filterClass) ? "&filter_class=$filterClass" : '') . (!empty($filterRole) ? "&filter_role=$filterRole" : ''));
    exit;
}

// ── Filtres ──────────────────────────────────────────────────────────────────
$where = "AND u.role != 'super_admin'";
$params = [];

if ($schoolFilter) {
    $where .= " AND u.school_id = " . (int)$schoolFilter;
} elseif ($filterSchool) {
    $where .= " AND u.school_id = ?";
    $params[] = (int)$filterSchool;
}

if ($filterClass) {
    $where .= " AND st.class_id = ?";
    $params[] = (int)$filterClass;
}

if ($filterRole && in_array($filterRole, ['school_admin','accountant','teacher','parent'], true)) {
    $where .= " AND u.role = ?";
    $params[] = $filterRole;
}

// ── Données ──────────────────────────────────────────────────────────────────
$effectiveSchool = $schoolFilter ?: ($filterSchool ?: null);

if ($effectiveSchool) {
    $stmtSch = $pdo->prepare("SELECT id, name, logo FROM schools WHERE id=?");
    $stmtSch->execute([$effectiveSchool]);
    $schools = $stmtSch->fetchAll(PDO::FETCH_ASSOC);
} else {
    $schools = $pdo->query("SELECT id, name, logo FROM schools ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
}

$classes = $pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare("
    SELECT u.id, u.name, u.email, u.role, u.plain_password,
           s.name AS school_name, s.logo AS school_logo,
           c.name AS class_name, c.id AS class_id
    FROM users u
    LEFT JOIN schools s ON u.school_id = s.id
    LEFT JOIN students st ON st.user_id = u.id
    LEFT JOIN classes c ON st.class_id = c.id
    WHERE 1=1 $where
    ORDER BY s.name, c.name, u.name
");
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Générer automatiquement un mot de passe pour les utilisateurs qui n'en ont pas
foreach ($users as &$u) {
    if (empty($u['plain_password'])) {
        $newPassword = bin2hex(random_bytes(4));
        $hash = password_hash($newPassword, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE users SET password=?, plain_password=? WHERE id=?")
            ->execute([$hash, $newPassword, $u['id']]);
        $u['plain_password'] = $newPassword;
    }
}
unset($u);
?><!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Identifiants - 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">
    <style>
        @media print { .no-print { display:none!important; } body { background:#fff; } .main-content { margin:0!important; } }
        .cred-group { margin-bottom:2rem; }
        .cred-group h3 { display:flex; align-items:center; gap:.6rem; margin-bottom:.5rem; font-size:1.1rem; }
        .cred-group h3 img { width:28px; height:28px; object-fit:contain; border-radius:4px; }
        .cred-table { width:100%; border-collapse:collapse; margin-bottom:1rem; }
        .cred-table th, .cred-table td { padding:.4rem .6rem; text-align:left; font-size:.85rem; }
        .cred-table th { background:#f5f7fa; border-bottom:2px solid #e2e8f0; font-weight:600; }
        .cred-table td { border-bottom:1px solid #edf2f7; }
        .cred-table .role-badge { display:inline-block; padding:.15rem .45rem; border-radius:4px; font-size:.75rem; font-weight:600; }
        .role-student { background:#e0f2fe; color:#0369a1; }
        .role-teacher { background:#fef3c7; color:#92400e; }
        .role-school_admin { background:#e0e7ff; color:#3730a3; }
        .role-accountant { background:#d1fae5; color:#065f46; }
        .role-parent { background:#fce7f3; color:#9d174d; }
        .btn-regen { font-size:.75rem; padding:.2rem .5rem; border-radius:4px; cursor:pointer; }
        .pwd-placeholder { color:#aaa; font-style:italic; }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-key"></i> Identifiants'; include '../includes/topbar.php'; ?>
        <div class="no-print" style="margin-bottom:1rem;">
            <a href="javascript:window.print()" class="btn-primary"><i class="fas fa-print"></i> Imprimer</a>
        </div>
        <?= showFlash() ?>

        <div class="filter-bar no-print" style="display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:1.5rem;align-items:center;">
            <?php if (!$schoolFilter): ?>
            <select name="filter_school" onchange="window.location='?filter_school='+this.value<?= json_encode($filterRole ? '&filter_role='.$filterRole : '') ?>+(document.getElementById('filterClass')?.'value'?'&filter_class='+document.getElementById('filterClass').value:'')">
                <option value="">— Toutes les écoles —</option>
                <?php foreach ($schools as $sc): ?>
                <option value="<?= $sc['id'] ?>" <?= $filterSchool == $sc['id'] ? 'selected' : '' ?>><?= e($sc['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
            <select id="filterClass" onchange="var s='<?= $filterSchool ?>';window.location='?filter_school='+s+(s?'&':'')+'filter_class='+this.value<?= json_encode($filterRole ? '&filter_role='.$filterRole : '') ?>">
                <option value="">— Toutes les classes —</option>
                <?php foreach ($classes as $cl): ?>
                <option value="<?= $cl['id'] ?>" <?= $filterClass == $cl['id'] ? 'selected' : '' ?>><?= e($cl['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <span style="color:#CBD5E0;">|</span>
            <a href="?<?= http_build_query(array_filter(['filter_school'=>$filterSchool,'filter_class'=>$filterClass])) ?>" class="filter-chip <?= !$filterRole ? 'active' : '' ?>" style="text-decoration:none;padding:.3rem .7rem;border-radius:20px;font-size:.8rem;font-weight:500;<?= !$filterRole ? 'background:var(--primary,#1F4E79);color:#fff;' : 'background:#E2E8F0;color:#475569;' ?>">Tous</a>
            <?php foreach ([
                'school_admin' => ['Directeurs','user-tie'],
                'accountant'   => ['Comptables','calculator'],
                'teacher'      => ['Enseignants','chalkboard-teacher'],
                'parent'       => ['Parents','user-friends'],
            ] as $r => [$label,$icon]): ?>
            <a href="?<?= http_build_query(array_filter(['filter_role'=>$r,'filter_school'=>$filterSchool,'filter_class'=>$filterClass])) ?>" class="filter-chip" style="text-decoration:none;padding:.3rem .7rem;border-radius:20px;font-size:.8rem;font-weight:500;<?= $filterRole===$r ? 'background:var(--primary,#1F4E79);color:#fff;' : 'background:#E2E8F0;color:#475569;' ?>"><i class="fas fa-<?=$icon?>"></i> <?=$label?></a>
            <?php endforeach; ?>
        </div>

        <?php
        // Regrouper par école puis classe
        $groups = [];
        foreach ($users as $u) {
            $sk = $u['school_name'] ?? 'Sans école';
            $ck = $u['class_name'] ?? 'Aucune classe';
            $groups[$sk][$ck][] = $u;
        }
        ?>

        <?php if (empty($groups)): ?>
        <p style="color:#999;text-align:center;padding:3rem 0;">Aucun utilisateur trouvé.</p>
        <?php else: ?>
        <?php foreach ($groups as $schoolName => $classGroups): ?>
            <?php foreach ($classGroups as $className => $usersInGroup): ?>
            <div class="cred-group">
                <h3>
                    <?php
                    $logo = '';
                    foreach ($usersInGroup as $u) {
                        if (!empty($u['school_logo'])) { $logo = $u['school_logo']; break; }
                    }
                    if ($logo): ?>
                    <img src="<?= e(logoUrl($logo)) ?>" alt="">
                    <?php endif; ?>
                    <?= e($schoolName) ?> — <?= e($className) ?>
                    <span style="font-weight:400;font-size:.8rem;color:#999;">(<?= count($usersInGroup) ?>)</span>
                </h3>
                <table class="cred-table">
                    <thead>
                        <tr>
                            <th>Nom</th>
                            <th>Email</th>
                            <th>Mot de passe</th>
                            <th>Rôle</th>
                            <th class="no-print">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($usersInGroup as $u): ?>
                        <tr>
                            <td><?= e($u['name']) ?></td>
                            <td><?= e($u['email']) ?></td>
                            <td><strong><?= e($u['plain_password']) ?></strong></td>
                            <td><span class="role-badge role-<?= $u['role'] ?>"><?= match($u['role']){
                                'school_admin' => 'Admin école',
                                'teacher'      => 'Enseignant',
                                'student'      => 'Élève',
                                'accountant'   => 'Comptable',
                                'parent'       => 'Parent',
                                default        => $u['role']
                            } ?></span></td>
                            <td class="no-print">
                                <form method="POST" action="?regenerate=1&uid=<?= $u['id'] ?><?= $filterSchool ? '&filter_school='.$filterSchool : '' ?><?= $filterClass ? '&filter_class='.$filterClass : '' ?>" style="display:inline" onsubmit="return confirm('Régénérer le mot de passe de <?= e($u['name']) ?> ?')">
                                    <?= csrfField() ?>
                                    <button type="submit" class="btn-regen" style="background:#e2e8f0;color:#475569;border:none;cursor:pointer;font-size:.75rem;padding:.2rem .5rem;border-radius:4px;">Régénérer</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endforeach; ?>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
<script src="../assets/js/main.js"></script>
</body>
</html>
