<?php
/**
 * Reçus de paie — génération, export/import par classe et élève
 */
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', 'accountant']);
requirePermission('payments', 'view');

$action = $_GET['action'] ?? 'list';
$error  = '';
$schoolFilter = currentSchoolId();

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

// ── Ajout d'un paiement (Reçu) ─────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_receipt'])) {
    verifyCsrf();
    $studentId   = (int)$_POST['student_id'];
    $amount      = str_replace([' ', ','], ['', '.'], $_POST['amount'] ?? '0');
    $paymentDate = $_POST['payment_date'] ?? date('Y-m-d');
    $method      = $_POST['method'] ?? 'Espèces';
    $reference   = trim($_POST['reference_code'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $schoolId    = $schoolFilter ?: (int)($_POST['school_id'] ?? 0);

    $trimestre   = (int)($_POST['trimestre'] ?? getActivePeriod());
    $academicYear = $_POST['academic_year'] ?? getDefaultAcademicYear($pdo, $schoolFilter);

    if (!$studentId || (float)$amount <= 0) {
        $error = 'Veuillez sélectionner un élève et entrer un montant valide.';
    } elseif (!$schoolId) {
        $error = 'École invalide.';
    } else {
        $pdo->prepare("INSERT INTO payments (school_id, student_id, amount, payment_date, method, reference_code, description, trimestre, academic_year)
                        VALUES (?,?,?,?,?,?,?,?,?)")
            ->execute([$schoolId, $studentId, (float)$amount, $paymentDate, $method, $reference ?: null, $description ?: null, $trimestre, $academicYear]);
        $payId = $pdo->lastInsertId();
        $receiptNum = 'REC-' . str_pad($payId, 5, '0', STR_PAD_LEFT);
        $pdo->prepare("UPDATE payments SET receipt_number=? WHERE id=?")->execute([$receiptNum, $payId]);
        flashMessage('success', "Paiement enregistré — Reçu N° $receiptNum");
        header('Location: receipts.php?action=print&id=' . $payId);
        exit;
    }
}

// ── Export CSV ─────────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    $classId = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
    $studentId = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;
    $sql = "SELECT p.*, s.name AS school_name, st.first_name, st.last_name, st.parent_name, st.parent_phone, 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 ($classId) { $sql .= " AND st.class_id=?"; $params[] = $classId; }
    if ($studentId) { $sql .= " AND p.student_id=?"; $params[] = $studentId; }
    $sql .= " ORDER BY c.name, st.last_name, 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=recus_paiement.csv');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, ['N° Reçu', 'Classe', 'Prénom', 'Nom', 'Parent', 'Tel Parent', 'Montant', 'Date', 'Méthode', 'Référence', 'Description', 'École'], ';');
    foreach ($rows as $r) {
        fputcsv($out, [$r['receipt_number'] ?? '', $r['class_name'] ?? '', $r['first_name'] ?? '', $r['last_name'] ?? '', $r['parent_name'] ?? '', $r['parent_phone'] ?? '', $r['amount'], $r['payment_date'], $r['method'], $r['reference_code'] ?? '', $r['description'] ?? '', $r['school_name'] ?? ''], ';');
    }
    fclose($out);
    exit;
}

// ── Impression de reçus (2 par page A4) ───────────────────────────────────────
if ($action === 'print' && isset($_GET['id'])) {
    $ids = array_map('intval', explode(',', $_GET['id']));
    if (empty($ids)) { flashMessage('error', 'Aucun reçu sélectionné.'); header('Location: receipts.php'); exit; }
    $in = implode(',', array_fill(0, count($ids), '?'));
    $stmt = $pdo->prepare("SELECT p.*, s.name AS school_name, s.logo, s.address, s.phone AS school_phone, s.email AS school_email,
                                  st.first_name, st.last_name, st.parent_name, st.parent_phone, 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 p.id IN ($in) ORDER BY st.last_name, st.first_name");
    $stmt->execute($ids);
    $receipts = $stmt->fetchAll();
    if (empty($receipts)) { flashMessage('error', 'Paiements introuvables.'); header('Location: receipts.php'); exit; }
    // Marquer comme imprimés
    foreach ($receipts as &$rec) {
        if (!$rec['printed_at']) {
            $recNum = 'REC-' . str_pad($rec['id'], 5, '0', STR_PAD_LEFT);
            $pdo->prepare("UPDATE payments SET printed_at=NOW(), receipt_number=COALESCE(receipt_number,?) WHERE id=?")
                ->execute([$recNum, $rec['id']]);
            $rec['receipt_number'] = $recNum;
            $rec['printed_at'] = date('Y-m-d H:i:s');
        }
    }
    unset($rec);
    ?><!DOCTYPE html><html lang="fr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Reçus de paie</title>
    <style>
        *{box-sizing:border-box;margin:0;padding:0}
        body{font:20px/1.4 'Segoe UI',Calibri,sans-serif;color:#333;background:#fff;padding:0}

        .rec-page{page-break-after:always;break-after:page;width:297mm;height:210mm;display:flex;flex-direction:row;align-items:stretch;padding:4mm 5mm}
        .rec-copy{border:2px solid #2d3748;border-radius:3px;padding:2.5mm 3.5mm;width:50%;display:flex;flex-direction:column;background:#fff;position:relative;overflow:hidden}
        .rec-copy:first-child{margin-right:1.5mm}
        .rec-copy:last-child{margin-left:1.5mm}
        .rec-copy .watermark{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);opacity:.08;pointer-events:none;z-index:0;width:75%;height:auto}
        .rec-body{margin:auto;width:100%;position:relative;z-index:1}

        .rec-header{text-align:center;border-bottom:3px solid #667eea;padding-bottom:2mm;margin-bottom:2mm}
        .rec-header img{max-height:48px;margin-bottom:3px}
        .rec-header h1{margin:0;font-size:22px;color:#1a202c;font-weight:700;letter-spacing:.5px}
        .rec-header h2{margin:4px 0 2px;font-size:16px;color:#4a5568;font-weight:600;letter-spacing:3px}
        .rec-header .num{display:inline-block;background:#667eea;color:#fff;font-size:16px;font-weight:700;padding:3px 14px;border-radius:4px;margin-top:4px}

        table{width:100%;border-collapse:collapse;margin:2mm 0}
        table td{padding:4px 6px;border:1px solid #cbd5e0;font-size:18px}
        table td:first-child{font-weight:700;background:#edf2f7;width:120px;white-space:nowrap;color:#2d3748}

        .amt{font-size:24px;font-weight:800;color:#276749;text-align:center;padding:2mm;border:3px solid #276749;border-radius:5px;margin:2mm 0 0;background:#f0fff4}

        .footer{text-align:center;color:#718096;font-size:13px;border-top:1px solid #e2e8f0;padding-top:1.5mm;margin-top:2mm}

        .cut-line{width:5mm;position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;flex-shrink:0}
        .cut-line::before{content:'';position:absolute;left:50%;top:0;bottom:0;border-left:2px dashed #a0aec0}
        .cut-label{background:#fff;color:#a0aec0;font-size:10px;font-weight:600;letter-spacing:1px;padding:4mm 0;writing-mode:vertical-rl;text-orientation:mixed;z-index:1}

        .print-btn{text-align:center;margin:5mm 0}
        .print-btn button{padding:8px 28px;font-size:14px;cursor:pointer;background:#667eea;color:#fff;border:none;border-radius:6px}

        @media print{body{background:#fff}.print-btn,.no-print{display:none!important}.rec-copy{border-color:#2d3748!important;border-radius:0!important}.rec-copy:first-child{margin-right:1mm}.rec-copy:last-child{margin-left:1mm}}
        @page{size:A4 landscape;margin:0}
    </style></head><body>
    <div class="print-btn no-print" style="padding:10px;text-align:center;">
        <button onclick="window.print()"><i class="fas fa-print"></i> Imprimer (<?=count($receipts)?> reçu(s) × 2 exemplaires)</button>
        <br><br><a href="receipts.php" style="color:#667eea;">← Retour</a>
    </div>
    <?php foreach ($receipts as $rec):
        $logoUrl = $rec['logo'] ? BASE_URL . 'uploads/logos/' . rawurlencode($rec['logo']) : '';
        $watermark = $logoUrl ? '<img src="'.e($logoUrl).'" class="watermark" alt="">' : '';
        $copy = function() use ($rec, $logoUrl) { ?>
        <div class="rec-body">
        <div class="rec-header">
            <?php if ($logoUrl):?><img src="<?=e($logoUrl)?>" style="max-height:48px"><?php endif;?>
            <h1><?=e($rec['school_name'] ?? 'Nukunu Mofiala')?></h1>
            <h2>REÇU DE PAIEMENT</h2>
            <span class="num">N° <?=e($rec['receipt_number'])?></span>
        </div>
        <table>
            <tr><td>Élève</td><td><?=e($rec['last_name'].' '.$rec['first_name'])?></td></tr>
            <tr><td>Classe</td><td><?=e($rec['class_name'] ?? '—')?></td></tr>
            <?php if ($rec['parent_name']):?><tr><td>Parent</td><td><?=e($rec['parent_name'])?><?=$rec['parent_phone']?' ('.e($rec['parent_phone']).')':''?></td></tr><?php endif;?>
            <tr><td>Date</td><td><?=formatDate($rec['payment_date'])?></td></tr>
            <tr><td>Méthode</td><td><?=e($rec['method'])?></td></tr>
            <?php if ($rec['reference_code']):?><tr><td>Référence</td><td><?=e($rec['reference_code'])?></td></tr><?php endif;?>
            <?php if ($rec['description']):?><tr><td>Description</td><td><?=e($rec['description'])?></td></tr><?php endif;?>
        </table>
        <div class="amt"><?=formatAmount($rec['amount'])?></div>
        </div>
        <div class="footer"><?=e($rec['school_name'] ?? '')?> — Tél : <?=e($rec['school_phone'] ?? '')?> — <?=e($rec['school_email'] ?? '')?></div>
    <?php }; ?>
    <div class="rec-page">
        <div class="rec-copy"><?=$watermark?><?php $copy(); ?></div>
        <div class="cut-line"><span class="cut-label">EXEMPLAIRE À COUPER</span></div>
        <div class="rec-copy"><?=$watermark?><?php $copy(); ?></div>
    </div>
    <?php endforeach; ?>
    </body></html><?php
    exit;
}

// ── Imprimer un reçu depuis l'import (marquage) ───────────────────────────────
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.');
        header('Location: receipts.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 les colonnes.');
        header('Location: receipts.php'); exit;
    }
    // Map élève
    $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'];
        $key2 = strtolower(trim($st['first_name']) . '|' . trim($st['last_name']));
        if (!isset($studentMap[$key2])) $studentMap[$key2] = $st['id'];
    }
    $imported = 0; $errors = []; $rowNum = 0;
    while (($row = fgetcsv($handle, 0, ';')) !== false) {
        $rowNum++;
        $receiptNum  = trim($row[0] ?? '');
        $className   = trim($row[1] ?? '');
        $firstName   = trim($row[2] ?? '');
        $lastName    = trim($row[3] ?? '');
        $amount      = str_replace(',', '.', trim($row[4] ?? ''));
        $payDate     = trim($row[5] ?? '');
        if (empty($firstName) || empty($lastName) || empty($amount) || !is_numeric($amount)) continue;
        $key = strtolower($className . '|' . $firstName . '|' . $lastName);
        $studentId = $studentMap[$key] ?? ($studentMap[strtolower($firstName . '|' . $lastName)] ?? 0);
        if (!$studentId) {
            $errors[] = "Ligne $rowNum : élève '$lastName $firstName' introuvable"; continue;
        }
        // Chercher un paiement correspondant
        $find = $pdo->prepare("SELECT id FROM payments WHERE student_id=? AND amount=? AND payment_date=? ORDER BY created_at DESC LIMIT 1");
        $find->execute([$studentId, (float)$amount, $payDate ?: null]);
        $payRow = $find->fetch();
        if ($payRow) {
            $pdo->prepare("UPDATE payments SET receipt_number=?, imported_at=NOW() WHERE id=?")->execute([$receiptNum ?: null, $payRow['id']]);
            $imported++;
        } else {
            $errors[] = "Ligne $rowNum : aucun paiement trouvé pour '$lastName $firstName' - $amount FCFA le $payDate";
        }
    }
    fclose($handle);
    $msg = "$imported reçu(s) importé(s).";
    if (!empty($errors)) $msg .= ' ' . implode('. ', array_slice($errors, 0, 10));
    flashMessage('success', $msg);
    header('Location: receipts.php'); exit;
}

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

// ── AJAX : élèves par classe ──────────────────────────────────────────────────
if (isset($_GET['ajax_students'])) {
    $clId = (int)($_GET['class_id'] ?? 0);
    $sStmt = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $sStmt->execute([$clId]);
    header('Content-Type: application/json');
    echo json_encode($sStmt->fetchAll());
    exit;
}

// ── Chargement des listes ─────────────────────────────────────────────────────
$classes = $pdo->query("SELECT id, name, academic_year FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();

$academicYears = $pdo->query("SELECT DISTINCT academic_year FROM classes WHERE academic_year IS NOT NULL AND academic_year != '' ORDER BY academic_year DESC")->fetchAll(PDO::FETCH_COLUMN);
$selectedYear = $academicYears[0] ?? date('Y') . '-' . (date('Y')+1);

$classFilter = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$studentFilter = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;

$students = [];
if ($classFilter) {
    $sStmt = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $sStmt->execute([$classFilter]);
    $students = $sStmt->fetchAll();
}

// Liste des paiements
$where = []; $params = [];
if ($schoolFilter) { $where[] = "p.school_id=?"; $params[] = $schoolFilter; }
if ($classFilter) { $where[] = "st.class_id=?"; $params[] = $classFilter; }
if ($studentFilter) { $where[] = "p.student_id=?"; $params[] = $studentFilter; }
$whereSql = count($where) ? " WHERE " . implode(' AND ', $where) : "";

$payments = $pdo->prepare("
    SELECT p.*, s.name AS school_name, st.first_name, st.last_name, st.parent_name, st.parent_phone, 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
    $whereSql
    ORDER BY c.name, st.last_name, p.payment_date DESC
");
$payments->execute($params);
$payments = $payments->fetchAll();

// Stats
$totalAmount = array_sum(array_column($payments, 'amount'));
$totalCount = count($payments);
$printedCount = count(array_filter($payments, fn($p) => !empty($p['printed_at'])));

$__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>Reçus de paie - 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); }
.stat-row { display:flex; gap:1rem; margin-bottom:1.5rem; flex-wrap:wrap; }
.stat-box { flex:1; min-width:130px; background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1rem; text-align:center; }
.stat-box .stat-val { font-size:1.5rem; font-weight:800; color:var(--primary); }
.stat-box .stat-lbl { font-size:.78rem; color:#718096; margin-top:4px; }
.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;} }
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-receipt"></i> Reçus de paie'; 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-receipt" style="color:var(--primary);"></i> Reçus de paie</h1>
                <p>Enregistrez les paiements et imprimez les reçus</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <a href="?export=1<?=$classFilter?'&class_id='.$classFilter:''?><?=$studentFilter?'&student_id='.$studentFilter:''?>" class="btn btn-light"><i class="fas fa-download"></i> Export CSV</a>
                <a href="#" onclick="openImportModal();return false;" class="btn btn-light"><i class="fas fa-upload"></i> Importer</a>
                <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 ?')">
                    <?=csrfField()?>
                    <button type="submit" class="btn btn-danger"><i class="fas fa-trash"></i> Suppr. importations</button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- ═══ Filtres ═══ -->
        <form method="GET" class="filters-card" id="filterForm">
            <div class="filters-row">
                <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-user-graduate"></i> Élève</label>
                    <select name="student_id" onchange="this.form.submit()">
                        <option value="">-- Tous --</option>
                        <?php foreach ($students as $st): ?>
                        <option value="<?=$st['id']?>" <?=$studentFilter==$st['id']?'selected':''?>><?=e($st['last_name'].' '.$st['first_name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if ($classFilter || $studentFilter): ?>
                <div class="filter-group" style="justify-content:flex-end;">
                    <a href="receipts.php" class="btn btn-light" style="padding:.55rem .9rem;"><i class="fas fa-times"></i> Réinitialiser</a>
                </div>
                <?php endif; ?>
            </div>
        </form>

        <!-- ═══ Stats ═══ -->
        <div class="stat-row">
            <div class="stat-box"><div class="stat-val"><?=$totalCount?></div><div class="stat-lbl">Paiements</div></div>
            <div class="stat-box"><div class="stat-val"><?=formatAmount($totalAmount)?></div><div class="stat-lbl">Total</div></div>
            <div class="stat-box"><div class="stat-val"><?=$printedCount?></div><div class="stat-lbl">Reçus imprimés</div></div>
            <div class="stat-box"><div class="stat-val"><?=$totalCount-$printedCount?></div><div class="stat-lbl">En attente</div></div>
        </div>

        <!-- ═══ Formulaire nouveau paiement ═══ -->
        <div class="form-card" id="payForm">
            <h2><i class="fas fa-receipt"></i> Nouveau paiement</h2>
            <form method="POST">
                <?=csrfField()?>
                <div class="form-row">
                    <div class="form-group">
                        <label>Classe</label>
                        <select id="formClassSelect" onchange="loadFormStudents()" required>
                            <option value="">-- Choisir --</option>
                            <?php foreach ($classes as $cl): ?>
                            <option value="<?=$cl['id']?>"><?=e($cl['name'])?> <?=!empty($cl['academic_year'])?'('.e($cl['academic_year']).')':''?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Élève</label>
                        <select name="student_id" id="formStudentSelect" required>
                            <option value="">-- Choisir une classe d'abord --</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Période</label>
                        <select name="trimestre" required>
                            <option value="1">1er Trimestre</option>
                            <option value="2">2ème Trimestre</option>
                            <option value="3">3ème Trimestre</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Année scolaire</label>
                        <input type="text" name="academic_year" value="<?=e($selectedYear)?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Montant (<?=CURRENCY?>)</label>
                        <input type="number" name="amount" required min="1" step="1">
                    </div>
                    <div class="form-group">
                        <label>Date</label>
                        <input type="date" name="payment_date" value="<?=date('Y-m-d')?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Mode de paiement</label>
                        <select name="method">
                            <?php foreach (['Espèces','Virement','Mobile Money','Carte'] as $m): ?>
                            <option value="<?=$m?>"><?=$m?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Référence (optionnel)</label>
                        <input type="text" name="reference_code">
                    </div>
                </div>
                <div style="display:flex;gap:.75rem;">
                    <button type="submit" name="save_receipt" class="btn btn-success"><i class="fas fa-save"></i> Enregistrer & imprimer</button>
                    <a href="receipts.php" class="btn btn-light">Réinitialiser</a>
                </div>
            </form>
        </div>

        <!-- ═══ Modal Import CSV ═══ -->
        <div class="modal-overlay" id="importModal">
            <div class="modal-box">
                <h2><i class="fas fa-upload"></i> Importer des reçus</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> Associe des numéros de reçu aux paiements existants</strong><br>
                    <code style="font-size:.72rem;">N°Reçu;Classe;Prénom;Nom;Montant;Date</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>

        <!-- ═══ Tableau des reçus ═══ -->
        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-list"></i> Liste des reçus</div>
                <span style="color:#718096;font-size:.82rem;"><?=$totalCount?> reçu(s)</span>
            </div>
            <div style="overflow-x:auto;">
            <table class="prog-table">
                <thead>
                    <tr>
                        <th>N° Reçu</th>
                        <th>Classe</th>
                        <th>Élève</th>
                        <th>Montant</th>
                        <th>Date</th>
                        <th>Méthode</th>
                        <th>Référence</th>
                        <th>Imprimé</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($payments as $p): ?>
                    <tr>
                        <td><code style="font-size:.78rem;"><?=e($p['receipt_number'] ?? '—')?></code></td>
                        <td><span style="color:#718096;"><?=e($p['class_name'] ?? '—')?></span></td>
                        <td><?=e($p['last_name'].' '.$p['first_name'])?></td>
                        <td><strong><?=formatAmount($p['amount'])?></strong></td>
                        <td><?=formatDate($p['payment_date'])?></td>
                        <td><?=e($p['method'])?></td>
                        <td><?=e($p['reference_code'] ?? '-')?></td>
                        <td><?=$p['printed_at'] ? '<span style="color:#276749;"><i class="fas fa-check-circle"></i> '.formatDate($p['printed_at']).'</span>' : '<span style="color:#CBD5E1;">—</span>'?></td>
                        <td>
                            <a href="?action=print&id=<?=$p['id']?>" class="btn btn-light" style="padding:.35rem .55rem;font-size:.75rem;" title="Imprimer le reçu" target="_blank"><i class="fas fa-print"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($payments)): ?>
                    <tr><td colspan="9"><div class="empty-state"><i class="fas fa-receipt"></i><p>Aucun paiement trouvé</p></div></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>
    </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 loadFormStudents() {
    const cls = document.getElementById('formClassSelect').value;
    const sel = document.getElementById('formStudentSelect');
    sel.innerHTML = '<option value="">Chargement...</option>';
    if (!cls) { sel.innerHTML = '<option value="">-- Choisir une classe d\'abord --</option>'; return; }
    fetch('receipts.php?ajax_students=1&class_id=' + cls)
        .then(r => r.json())
        .then(data => {
            sel.innerHTML = '<option value="">-- Choisir un élève --</option>';
            data.forEach(s => { sel.innerHTML += '<option value="'+s.id+'">'+s.last_name+' '+s.first_name+'</option>'; });
        })
        .catch(() => { sel.innerHTML = '<option value="">Erreur de chargement</option>'; });
}
function filterChange() {
    const classId = document.getElementById('classSelect').value;
    const studentId = document.getElementById('studentSelect').value;
    let url = 'receipts.php';
    const params = [];
    if (classId) params.push('class_id=' + classId);
    if (studentId) params.push('student_id=' + studentId);
    if (params.length) url += '?' + params.join('&');
    window.location = url;
}
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>N°Reçu</th><th>Classe</th><th>Prénom</th><th>Nom</th><th>Montant</th><th>Date</th></tr>');
    w.document.write('<tr><td>REC-001</td><td>6ème A</td><td>Jean</td><td>Dupont</td><td>5000</td><td>15/09/2024</td></tr>');
    w.document.write('<tr><td>REC-002</td><td>5ème B</td><td>Marie</td><td>Martin</td><td>10000</td><td>20/09/2024</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>
