<?php
/**
 * Gestion des paiements
 */
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']);
requirePermission('payments', 'view');

$action = $_GET['action'] ?? 'list';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : null;
$error  = '';

$schoolFilter = currentSchoolId();

// Colonne imported_at
try { $pdo->exec("ALTER TABLE payments ADD COLUMN imported_at DATETIME DEFAULT NULL"); } catch (PDOException $e) {}

// ── Export CSV ────────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    $classFilter = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
    $sql = "SELECT p.*, s.name AS school_name, st.first_name, st.last_name, c.name AS class_name
            FROM payments p
            LEFT JOIN schools s ON p.school_id=s.id
            LEFT JOIN students st ON p.student_id=st.id
            LEFT JOIN classes c ON st.class_id=c.id
            WHERE 1=1";
    $params = [];
    if ($schoolFilter) { $sql .= " AND p.school_id=?"; $params[] = $schoolFilter; }
    if ($classFilter) { $sql .= " AND st.class_id=?"; $params[] = $classFilter; }
    $sql .= " ORDER BY p.payment_date DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=paiements.csv');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, ['Classe', 'Prénom', 'Nom', 'Montant', 'Date', 'Méthode', 'Référence', 'Description', 'École'], ';');
    foreach ($rows as $r) {
        fputcsv($out, [$r['class_name'] ?? '', $r['first_name'] ?? '', $r['last_name'] ?? '', $r['amount'], $r['payment_date'], $r['method'], $r['reference_code'] ?? '', $r['description'] ?? '', $r['school_name'] ?? ''], ';');
    }
    fclose($out);
    exit;
}

// ── Suppression importations ──────────────────────────────────────────────────
if ($action === 'clear_imports') {
    verifyCsrf();
    checkDeleteAllowed();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: payments.php'); exit; }
    $pdo->exec("DELETE FROM payments WHERE imported_at IS NOT NULL");
    flashMessage('success','Importations supprimées.');
    header('Location: payments.php'); exit;
}

// ── Import CSV ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    verifyCsrf();
    if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        flashMessage('error', 'Erreur lors du téléchargement du fichier.');
        header('Location: payments.php'); exit;
    }
    $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
    $header = fgetcsv($handle, 0, ';');
    if (!$header || count($header) < 4) {
        fclose($handle);
        flashMessage('error', 'Format CSV invalide. Vérifiez le séparateur (;) et le nombre de colonnes.');
        header('Location: payments.php'); exit;
    }
    // Construire map (classe, prénom, nom) → student_id
    $studentMap = [];
    $stuStmt = $pdo->query("SELECT s.id, s.first_name, s.last_name, c.name AS class_name
                            FROM students s LEFT JOIN classes c ON s.class_id=c.id ORDER BY s.last_name, s.first_name");
    foreach ($stuStmt as $st) {
        $key = strtolower(trim($st['class_name'] ?? '') . '|' . trim($st['first_name']) . '|' . trim($st['last_name']));
        $studentMap[$key] = $st['id'];
        // fallback sans classe
        $key2 = strtolower(trim($st['first_name']) . '|' . trim($st['last_name']));
        if (!isset($studentMap[$key2])) $studentMap[$key2] = $st['id'];
    }
    $imported = 0; $errors = []; $rowNum = 0;
    $validMethods = ['Espèces', 'Virement', 'Mobile Money', 'Carte'];
    while (($row = fgetcsv($handle, 0, ';')) !== false) {
        $rowNum++;
        $className   = trim($row[0] ?? '');
        $firstName   = trim($row[1] ?? '');
        $lastName    = trim($row[2] ?? '');
        $amount      = str_replace(',', '.', trim($row[3] ?? ''));
        $payDate     = trim($row[4] ?? '');
        $method      = trim($row[5] ?? '');
        $reference   = trim($row[6] ?? '');
        $description = trim($row[7] ?? '');
        if (empty($firstName) || empty($lastName) || !is_numeric($amount) || (float)$amount <= 0) continue;
        if (!strtotime($payDate)) { $errors[] = "Ligne $rowNum : date '$payDate' invalide"; continue; }
        $method = in_array($method, $validMethods, true) ? $method : 'Espèces';
        $key = strtolower($className . '|' . $firstName . '|' . $lastName);
        $studentId = $studentMap[$key] ?? ($studentMap[strtolower($firstName . '|' . $lastName)] ?? 0);
        if (!$studentId) {
            $errors[] = "Ligne $rowNum : élève '$firstName $lastName' introuvable"; continue;
        }
        // Récupérer school_id de l'élève
        $sc = $pdo->prepare("SELECT school_id FROM students WHERE id=?");
        $sc->execute([$studentId]); $srow = $sc->fetch();
        $schoolId = $srow ? $srow['school_id'] : ($schoolFilter ?? 0);
        if (!$schoolId) { $errors[] = "Ligne $rowNum : école non déterminée pour '$firstName $lastName'"; continue; }
        $pdo->prepare("INSERT INTO payments (school_id, student_id, amount, payment_date, method, reference_code, description, imported_at) VALUES (?,?,?,?,?,?,?,NOW())")
            ->execute([$schoolId, $studentId, (float)$amount, $payDate, $method, $reference, $description]);
        $imported++;
    }
    fclose($handle);
    $msg = "$imported paiement(s) importé(s).";
    if (!empty($errors)) $msg .= ' ' . implode('. ', array_slice($errors, 0, 10));
    flashMessage('success', $msg);
    header('Location: payments.php'); exit;
}

// ── Suppression ───────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: payments.php'); exit; }
    checkDeleteAllowed();
    if ($schoolFilter) {
        $check = $pdo->prepare("SELECT id FROM payments WHERE id = ? AND school_id = ?");
        $check->execute([$id, $schoolFilter]);
        if (!$check->fetch()) { flashMessage('error', 'Action non autorisée.'); header('Location: payments.php'); exit; }
    }
    $pdo->prepare("DELETE FROM payments WHERE id = ?")->execute([$id]);
    flashMessage('success', 'Paiement supprimé.');
    header('Location: payments.php'); exit;
}

// ── Ajout / Modification ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_FILES['csv_file'])) {
    verifyCsrf();
    requirePermission('payments', $id ? 'edit' : 'create');
    $school_id      = $schoolFilter ?? (int)($_POST['school_id'] ?? 0);
    $student_id     = (int)($_POST['student_id'] ?? 0);
    $amount         = filter_var($_POST['amount'] ?? '', FILTER_VALIDATE_FLOAT);
    $payment_date   = trim($_POST['payment_date'] ?? '');
    $method         = $_POST['method'] ?? 'Espèces';
    $reference_code = trim($_POST['reference_code'] ?? '');
    $description    = trim($_POST['description'] ?? '');
    $validMethods   = ['Espèces', 'Virement', 'Mobile Money', 'Carte'];

    if ($school_id <= 0) $error = 'Veuillez sélectionner une école.';
    elseif ($student_id <= 0) $error = 'Veuillez sélectionner un élève.';
    elseif ($amount === false || $amount <= 0) $error = 'Le montant doit être un nombre positif.';
    elseif (empty($payment_date) || !strtotime($payment_date)) $error = 'Date de paiement invalide.';
    elseif (!in_array($method, $validMethods, true)) $error = 'Méthode de paiement invalide.';
    else {
        $sc = $pdo->prepare("SELECT id FROM students WHERE id = ? AND school_id = ?");
        $sc->execute([$student_id, $school_id]);
        if (!$sc->fetch()) $error = "Cet élève n'appartient pas à l'école sélectionnée.";
    }

    if (empty($error)) {
        $data = [$school_id, $student_id, $amount, $payment_date, $method, $reference_code, $description];
        if ($id) {
            if ($schoolFilter) {
                $check = $pdo->prepare("SELECT id FROM payments WHERE id = ? AND school_id = ?");
                $check->execute([$id, $schoolFilter]);
                if (!$check->fetch()) { flashMessage('error', 'Action non autorisée.'); header('Location: payments.php'); exit; }
            }
            $data[] = $id;
            $pdo->prepare("UPDATE payments SET school_id=?, student_id=?, amount=?, payment_date=?, method=?, reference_code=?, description=? WHERE id=?")->execute($data);
            flashMessage('success', 'Paiement mis à jour.');
        } else {
            $pdo->prepare("INSERT INTO payments (school_id, student_id, amount, payment_date, method, reference_code, description) VALUES (?,?,?,?,?,?,?)")->execute($data);
            flashMessage('success', 'Paiement enregistré.');
        }
        header('Location: payments.php'); exit;
    }
}

// ── Chargement pour édition ───────────────────────────────────────────────────
$payment = null;
if ($action === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM payments WHERE id = ?" . ($schoolFilter ? " AND school_id = ?" : ""));
    $stmt->execute($schoolFilter ? [$id, $schoolFilter] : [$id]);
    $payment = $stmt->fetch();
    if (!$payment) { flashMessage('error', 'Paiement introuvable.'); header('Location: payments.php'); exit; }
}

if ($schoolFilter) {
    $schoolsStmt = $pdo->prepare("SELECT id, name FROM schools WHERE id = ?");
    $schoolsStmt->execute([$schoolFilter]);
    $schools = $schoolsStmt->fetchAll();
    $studentsStmt = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE school_id = ? ORDER BY last_name, first_name");
    $studentsStmt->execute([$schoolFilter]);
    $students = $studentsStmt->fetchAll();
} else {
    $schools  = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();
    $students = $pdo->query("SELECT id, first_name, last_name FROM students ORDER BY last_name, first_name")->fetchAll();
}

// Filtre par classe
$classFilter = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$classes = $pdo->query("SELECT id, name, academic_year FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();

// ── Tri ───────────────────────────────────────────────────────────────────────
$sortAllowed = ['student_name', 'amount', 'payment_date', 'method', 'reference_code', 'school_name', 'created_at'];
$sort = resolveSort($sortAllowed, 'payment_date', 'desc');
$sortMap = [
    'student_name'   => 'st.last_name',
    'amount'         => 'p.amount',
    'payment_date'   => 'p.payment_date',
    'method'         => 'p.method',
    'reference_code' => 'p.reference_code',
    'school_name'    => 's.name',
    'created_at'     => 'p.created_at',
];
$orderExpr = ($sortMap[$sort['col']] ?? 'p.payment_date') . ' ' . $sort['dir'];

$listSql = "
    SELECT p.*, s.name AS school_name, st.first_name, st.last_name, c.name AS class_name
    FROM payments p
    LEFT JOIN schools s  ON p.school_id  = s.id
    LEFT JOIN students st ON p.student_id = st.id
    LEFT JOIN classes c ON st.class_id = c.id
";
$where = []; $params = [];
if ($schoolFilter) { $where[] = "p.school_id=?"; $params[] = $schoolFilter; }
if ($classFilter) { $where[] = "st.class_id=?"; $params[] = $classFilter; }
$sql = $listSql . (count($where) ? " WHERE " . implode(' AND ', $where) : "") . " ORDER BY $orderExpr";
$listStmt = $pdo->prepare($sql);
$listStmt->execute($params);
$payments = $listStmt->fetchAll();
$__flash = $_SESSION['flash_toast'] ?? null;
unset($_SESSION['flash_toast']);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Paiements - 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>
:root { --primary: #1F4E79; --accent: #2E75B6; --light: #D6E4F0; }
.prog-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:1.5rem; flex-wrap:wrap; gap:1rem; }
.prog-header h1 { font-family:Georgia,serif; color:var(--primary); font-size:1.6rem; }
.prog-header p { color:#666; font-size:.9rem; }
.filters-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1.25rem 1.5rem; margin-bottom:1.5rem; }
.filters-row { display:flex; gap:1.25rem; align-items:flex-end; flex-wrap:wrap; }
.filter-group { display:flex; flex-direction:column; gap:6px; flex:1; min-width:150px; }
.filter-group label { font-weight:600; color:var(--primary); font-size:.8rem; }
.filter-group select, .filter-group input { padding:.55rem .75rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.85rem; background:white; }
.filter-group select:focus, .filter-group input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(46,117,182,0.15); }
.table-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); overflow:hidden; margin-bottom:1.5rem; }
.table-card .tc-header { padding:1rem 1.5rem; border-bottom:1px solid #E5E7EB; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:.5rem; }
.table-card .tc-title { font-family:Georgia,serif; color:var(--primary); font-size:1.05rem; }
.prog-table { width:100%; border-collapse:collapse; }
.prog-table thead { background:var(--primary); color:white; }
.prog-table th { padding:.6rem .8rem; text-align:left; font-weight:600; font-size:.74rem; text-transform:uppercase; letter-spacing:.4px; white-space:nowrap; }
.prog-table td { padding:.55rem .8rem; border-bottom:1px solid #E5E7EB; font-size:.82rem; vertical-align:middle; }
.prog-table tbody tr:hover { background:#F9FAFB; }
.btn { display:inline-flex; align-items:center; gap:6px; padding:.5rem 1.1rem; border:none; border-radius:6px; font-size:.82rem; font-weight:600; cursor:pointer; transition:all .2s; text-decoration:none; }
.btn-primary { background:var(--primary); color:white; }
.btn-primary:hover { background:#163a5c; }
.btn-light { background:#E5E7EB; color:#374151; }
.btn-light:hover { background:#D1D5DB; }
.btn-success { background:#10B981; color:white; }
.btn-success:hover { background:#059669; }
.btn-warning { background:#F59E0B; color:white; }
.btn-danger { background:#E53E3E; color:white; }
.btn-danger:hover { background:#C53030; }
.empty-state { text-align:center; padding:3rem 1rem; color:#9CA3AF; }
.empty-state i { font-size:2.5rem; display:block; margin-bottom:.75rem; color:#CBD5E1; }
.modal-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.4); z-index:1500; align-items:center; justify-content:center; }
.modal-overlay.open { display:flex; }
.modal-box { background:white; border-radius:12px; padding:2rem; width:90%; max-width:480px; max-height:90vh; overflow-y:auto; box-shadow:0 10px 40px rgba(0,0,0,0.2); }
.modal-box h2 { font-family:Georgia,serif; color:var(--primary); font-size:1.15rem; margin-bottom:1.25rem; display:flex; align-items:center; gap:.5rem; }
.modal-box .modal-actions { display:flex; gap:.75rem; margin-top:1.25rem; justify-content:flex-end; }
.form-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1.5rem 2rem; margin-bottom:1.5rem; max-width:640px; }
.form-card h2 { font-family:Georgia,serif; color:var(--primary); font-size:1.15rem; margin-bottom:1.25rem; display:flex; align-items:center; gap:.5rem; }
.form-row { display:flex; gap:1.25rem; flex-wrap:wrap; margin-bottom:1rem; }
.form-row .form-group { flex:1; min-width:180px; }
.form-group { margin-bottom:1rem; }
.form-group label { display:block; font-weight:600; color:var(--primary); font-size:.8rem; margin-bottom:4px; }
.form-group select, .form-group input, .form-group textarea { width:100%; padding:.55rem .75rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.85rem; background:white; box-sizing:border-box; }
.form-group select:focus, .form-group input:focus, .form-group textarea:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(46,117,182,0.15); }
.toast-container { position:fixed; bottom:30px; right:30px; z-index:2000; display:flex; flex-direction:column; gap:10px; }
.toast { background:white; padding:12px 18px; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.15); display:flex; align-items:center; gap:10px; animation:slideIn .3s ease; border-left:4px solid var(--primary); font-size:.9rem; }
.toast-success { border-left-color:#10B981; }
.toast-error { border-left-color:#EF4444; }
@keyframes slideIn { from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;} }
@media (max-width:768px) {
  .prog-header { flex-direction:column; align-items:flex-start; }
  .filters-row { flex-direction:column; }
  .filter-group { min-width:100%; }
  .table-card .tc-header { flex-direction:column; align-items:flex-start; gap:.5rem; }
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-money-bill-wave"></i> Gestion des paiements'; include '../includes/topbar.php'; ?>

        <?php if ($__flash): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($__flash['message']) ?>,<?= json_encode($__flash['type']) ?>);});</script>
        <?php endif; ?>

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1><i class="fas fa-money-bill-wave" style="color:var(--primary);"></i> Gestion des paiements</h1>
                <p>Enregistrez, importez et suivez les paiements des élèves</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <?php if (hasPermission('payments','create')): ?>
                <a href="?action=add" class="btn btn-success"><i class="fas fa-plus"></i> Nouveau paiement</a>
                <?php endif; ?>
                <a href="?export=1<?= $classFilter ? '&class_id='.$classFilter : '' ?>" class="btn btn-light"><i class="fas fa-download"></i> Export CSV</a>
                <?php if (hasPermission('payments','create')): ?>
                <a href="#" onclick="openImportModal();return false;" class="btn btn-light"><i class="fas fa-upload"></i> Importer CSV</a>
                <?php endif; ?>
                <a href="#" onclick="return downloadTemplate()" class="btn btn-light"><i class="fas fa-file-export"></i> Modèle</a>
                <?php if (isSuperAdmin()): ?>
                <form method="POST" action="?action=clear_imports" style="display:inline" onsubmit="return confirm('Supprimer tous les paiements importés ? Cette action est irréversible.')">
                    <?= csrfField() ?>
                    <button type="submit" class="btn btn-danger"><i class="fas fa-trash"></i> Suppr. importations</button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($error): ?><div class="error-message" style="margin-bottom:1rem;"><?= e($error) ?></div><?php endif; ?>

        <!-- ═══ Filtres ═══ -->
        <form method="GET" class="filters-card" id="filterForm">
            <div class="filters-row">
                <?php if (!$schoolFilter): ?>
                <div class="filter-group">
                    <label><i class="fas fa-school"></i> École</label>
                    <select name="school_id" onchange="this.form.submit()">
                        <option value="">-- Toutes --</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= (int)($_GET['school_id']??0)===$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="filter-group">
                    <label><i class="fas fa-users"></i> Classe</label>
                    <select name="class_id" onchange="this.form.submit()">
                        <option value="">-- Toutes --</option>
                        <?php foreach ($classes as $cl): ?>
                        <option value="<?= $cl['id'] ?>" <?= $classFilter==$cl['id']?'selected':'' ?>><?= e($cl['name'])?><?= !empty($cl['academic_year']) ? ' ('.e($cl['academic_year']).')' : '' ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-search"></i> Recherche</label>
                    <input type="text" id="searchPay" placeholder="Rechercher un élève..." onkeyup="searchTable('searchPay','paymentsTable')">
                </div>
            </div>
        </form>

        <!-- ═══ Modal Import CSV ═══ -->
        <div class="modal-overlay" id="importModal">
            <div class="modal-box">
                <h2><i class="fas fa-upload"></i> Importer des paiements</h2>
                <div style="background:#EBF8FF;border:1px solid #BEE3F8;border-radius:8px;padding:1rem;margin-bottom:1.25rem;font-size:.8rem;">
                    <strong><i class="fas fa-info-circle"></i> Format CSV (séparateur <code>;</code>)</strong><br>
                    <code style="font-size:.72rem;">Classe;Prénom;Nom;Montant;Date;Méthode;Référence;Description</code><br>
                    <a href="#" onclick="return downloadTemplate()" style="display:inline-flex;align-items:center;gap:.35rem;margin-top:.3rem;color:#2563EB;font-size:.78rem;"><i class="fas fa-download"></i> Télécharger le modèle</a>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <?= csrfField() ?>
                    <div class="form-group">
                        <label>Fichier CSV <span style="color:red;">*</span></label>
                        <input type="file" name="csv_file" accept=".csv,.txt" required>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn btn-light" onclick="closeImportModal()">Annuler</button>
                        <button type="submit" class="btn btn-primary"><i class="fas fa-upload"></i> Importer</button>
                    </div>
                </form>
            </div>
        </div>

        <?php if (in_array($action, ['add','edit']) && ($action==='add' ? hasPermission('payments','create') : hasPermission('payments','edit'))): ?>
        <!-- ═══ Formulaire ═══ -->
        <div class="form-card">
            <h2><i class="fas fa-<?= $payment ? 'edit' : 'plus-circle' ?>"></i> <?= $payment ? 'Modifier' : 'Enregistrer' ?> un paiement</h2>
            <form method="POST">
                <?= csrfField() ?>
                <div class="form-row">
                    <div class="form-group">
                        <label>École</label>
                        <select name="school_id" required <?= $schoolFilter ? 'disabled' : '' ?>>
                            <option value="">Choisir...</option>
                            <?php foreach ($schools as $sc): ?>
                            <option value="<?= $sc['id'] ?>" <?= ($payment['school_id'] ?? '') == $sc['id'] ? 'selected' : '' ?>><?= e($sc['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <?php if ($schoolFilter): ?><input type="hidden" name="school_id" value="<?= $schoolFilter ?>"><?php endif; ?>
                    </div>
                    <div class="form-group">
                        <label>Élève</label>
                        <select name="student_id" required>
                            <option value="">Choisir...</option>
                            <?php foreach ($students as $st): ?>
                            <option value="<?= $st['id'] ?>" <?= ($payment['student_id'] ?? '') == $st['id'] ? 'selected' : '' ?>><?= e($st['last_name'] . ' ' . $st['first_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Montant (FCFA)</label>
                        <input type="number" name="amount" required min="1" step="1" value="<?= e($payment['amount'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Date</label>
                        <input type="date" name="payment_date" required value="<?= e($payment['payment_date'] ?? date('Y-m-d')) ?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Méthode</label>
                        <select name="method">
                            <?php foreach (['Espèces', 'Virement', 'Mobile Money', 'Carte'] as $m): ?>
                            <option value="<?= $m ?>" <?= ($payment['method'] ?? 'Espèces') === $m ? 'selected' : '' ?>><?= $m ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Référence</label>
                        <input type="text" name="reference_code" value="<?= e($payment['reference_code'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" rows="3"><?= e($payment['description'] ?? '') ?></textarea>
                </div>
                <div style="display:flex;gap:.75rem;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
                    <a href="payments.php" class="btn btn-light">Annuler</a>
                </div>
            </form>
        </div>

        <?php else: ?>
        <!-- ═══ Tableau des paiements ═══ -->
        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-list"></i> Liste des paiements</div>
                <span style="color:#718096;font-size:.82rem;"><?= count($payments) ?> paiement(s)</span>
            </div>
            <div style="overflow-x:auto;">
            <table class="prog-table" id="paymentsTable">
                <thead>
                    <tr>
                        <th><?= sortTh('student_name',   'Élève',     $sort) ?></th>
                        <th>Classe</th>
                        <th><?= sortTh('amount',         'Montant',   $sort) ?></th>
                        <th><?= sortTh('payment_date',   'Date',      $sort) ?></th>
                        <th><?= sortTh('method',         'Méthode',   $sort) ?></th>
                        <th><?= sortTh('reference_code', 'Référence', $sort) ?></th>
                        <th>N° Reçu</th>
                        <?php if (!$schoolFilter): ?>
                        <th><?= sortTh('school_name', 'École', $sort) ?></th>
                        <?php endif; ?>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($payments as $p): ?>
                    <tr>
                        <td><?= e($p['last_name'] . ' ' . $p['first_name']) ?></td>
                        <td><span style="color:#718096;"><?= e($p['class_name'] ?? '—') ?></span></td>
                        <td><?= formatAmount($p['amount']) ?></td>
                        <td><?= formatDate($p['payment_date']) ?></td>
                        <td><?= e($p['method']) ?></td>
                        <td><?= e($p['reference_code'] ?? '-') ?></td>
                        <td><code style="font-size:.78rem;"><?= e($p['receipt_number'] ?? '—') ?></code></td>
                        <?php if (!$schoolFilter): ?><td><?= e($p['school_name'] ?? '-') ?></td><?php endif; ?>
                        <td>
                            <div style="display:flex;gap:.3rem;">
                            <?php if (hasPermission('payments','edit')): ?>
                            <a href="?action=edit&id=<?= $p['id'] ?>" class="btn btn-light btn-sm" style="padding:.35rem .55rem;font-size:.75rem;" title="Modifier"><i class="fas fa-edit"></i></a>
                            <?php endif; ?>
                            <a href="<?=BASE_URL?>admin/receipts.php?action=print&id=<?=$p['id']?>" class="btn btn-light btn-sm" style="padding:.35rem .55rem;font-size:.75rem;" title="Imprimer le reçu" target="_blank"><i class="fas fa-print"></i></a>
                            <?php if (isSuperAdmin()): ?>
                            <form method="POST" action="?action=delete&id=<?= $p['id'] ?>" style="display:inline" onsubmit="return confirm('Supprimer ce paiement ?')">
                                <?= csrfField() ?>
                                <button type="submit" class="btn btn-danger btn-sm" style="padding:.35rem .55rem;font-size:.75rem;" title="Supprimer"><i class="fas fa-trash"></i></button>
                            </form>
                            <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($payments)): ?>
                    <tr><td colspan="<?= $schoolFilter ? 8 : 9 ?>" style="text-align:center;padding:2rem;color:#9CA3AF;">Aucun paiement enregistré</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══ Toast Container ═══ -->
<div class="toast-container" id="toastContainer"></div>

<script>
function openImportModal(){document.getElementById('importModal').classList.add('open');}
function closeImportModal(){document.getElementById('importModal').classList.remove('open');}
document.getElementById('importModal')?.addEventListener('click',function(e){if(e.target===this)closeImportModal();});
function downloadTemplate() {
    const w = window.open('', '_blank');
    w.document.write('<html><head><meta charset="UTF-8"><style>td,th{border:1px solid #ccc;padding:4px 8px;font:11px Calibri,sans-serif}th{background:#4472c4;color:#fff;font-weight:700}</style></head><body><table>');
    w.document.write('<tr><th>Classe</th><th>Prénom</th><th>Nom</th><th>Montant</th><th>Date</th><th>Méthode</th><th>Référence</th><th>Description</th></tr>');
    w.document.write('<tr><td>6ème A</td><td>Jean</td><td>Dupont</td><td>5000</td><td>15/09/2024</td><td>Espèces</td><td>REC-001</td><td>Frais inscription</td></tr>');
    w.document.write('<tr><td>5ème B</td><td>Marie</td><td>Martin</td><td>10000</td><td>20/09/2024</td><td>Mobile Money</td><td>TNX-1234</td><td></td></tr>');
    w.document.write('</table></body></html>');
    w.document.close();
    w.focus();
    w.print();
    return false;
}
function showToast(msg,type){var c=document.getElementById('toastContainer');var t=document.createElement('div');t.className='toast toast-'+(type==='success'?'success':'error');t.innerHTML='<span>'+(type==='success'?'&#x2705;':'&#x274C;')+'</span><span>'+msg+'</span>';c.appendChild(t);setTimeout(function(){t.remove();},4000);}
</script>
<script src="../assets/js/main.js"></script>
</body>
</html>
