<?php
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('payment_history', 'view');

$schoolFilter = currentSchoolId();
$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();

// Élèves avec récapitulatif
$stuWhere = $schoolFilter ? "st.school_id=?" : "1=1";
$stuParams = $schoolFilter ? [$schoolFilter] : [];
if ($classFilter) { $stuWhere .= " AND st.class_id=?"; $stuParams[] = $classFilter; }

$students = $pdo->prepare("
    SELECT st.id, st.first_name, st.last_name, st.parent_name, st.parent_phone, c.name AS class_name,
        COALESCE(SUM(p.amount),0) AS total_paid,
        COUNT(p.id) AS payment_count,
        MAX(p.payment_date) AS last_payment
    FROM students st
    LEFT JOIN classes c ON st.class_id=c.id
    LEFT JOIN payments p ON p.student_id=st.id
    WHERE $stuWhere
    GROUP BY st.id
    ORDER BY c.name, st.last_name, st.first_name
");
$students->execute($stuParams);
$students = $students->fetchAll();

// Paiements détaillés par élève
$studentIds = array_column($students, 'id');
$paymentsByStudent = [];
if ($studentIds) {
    $in = implode(',', array_fill(0, count($studentIds), '?'));
    $pStmt = $pdo->prepare("
        SELECT p.*, s.name AS school_name
        FROM payments p
        LEFT JOIN schools s ON p.school_id=s.id
        WHERE p.student_id IN ($in)
        ORDER BY p.payment_date DESC, p.created_at DESC
    ");
    $pStmt->execute($studentIds);
    foreach ($pStmt->fetchAll() as $pay) {
        $sid = (int)$pay['student_id'];
        $paymentsByStudent[$sid][] = $pay;
    }
}
$__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>Historique des 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-light { background:#E5E7EB; color:#374151; }
.btn-light:hover { background:#D1D5DB; }
.empty-state { text-align:center; padding:3rem 1rem; color:#9CA3AF; }
.empty-state i { font-size:2.5rem; display:block; margin-bottom:.75rem; color:#CBD5E1; }
.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; }
.hist-table .student-row td { background:#fff; font-weight:600; border-bottom:2px solid #E5E7EB; }
.hist-table .student-row .toggle-details { cursor:pointer; color:var(--accent); }
.hist-table .pay-details { display:none; }
.hist-table .pay-details.open { display:table-row; }
.hist-table .pay-details td { padding:.4rem .7rem .4rem 2.5rem; background:#F9FAFB; }
.hist-table .pay-item { display:flex; justify-content:space-between; padding:3px 0; border-bottom:1px dashed #E5E7EB; }
.hist-table .pay-item:last-child { border:none; }
.hist-table .pay-item .date { color:#718096; font-size:.82rem; }
.hist-table .pay-item .amt { font-weight:700; }
.hist-table .badge-cat { display:inline-block; background:#EBF4FF; color:#2B6CB0; font-size:.72rem; padding:1px 7px; border-radius:8px; font-weight:600; }
.hist-table .month-group { margin-bottom:.8rem; }
.hist-table .month-group h4 { font-size:.82rem; color:#4A5568; margin:0 0 4px; border-bottom:1px solid #E5E7EB; padding-bottom: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;} }
@media (max-width:768px) {
  .prog-header { flex-direction:column; align-items:flex-start; }
  .table-card .tc-header { flex-direction:column; align-items:flex-start; gap:.5rem; }
  .hist-table { font-size:.82rem; }
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-history"></i> Historique 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-history" style="color:var(--primary);"></i> Historique des paiements</h1>
                <p>Consultez l'historique détaillé des paiements par élève</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;align-items:center;">
                <span style="font-size:.9rem;color:#718096;"><?=count($students)?> élève(s)</span>
            </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 les classes —</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>
                <?php if ($classFilter): ?>
                <div class="filter-group" style="justify-content:flex-end;">
                    <a href="payment_history.php" class="btn btn-light" style="padding:.55rem .9rem;"><i class="fas fa-times"></i> Réinitialiser</a>
                </div>
                <?php endif; ?>
            </div>
        </form>

        <!-- ═══ Stats ═══ -->
        <?php
        $totalPaiements = array_sum(array_column($students, 'payment_count'));
        $totalMontant = array_sum(array_column($students, 'total_paid'));
        ?>
        <div class="stat-row">
            <div class="stat-box"><div class="stat-val"><?=count($students)?></div><div class="stat-lbl">Élèves</div></div>
            <div class="stat-box"><div class="stat-val"><?=$totalPaiements?></div><div class="stat-lbl">Paiements</div></div>
            <div class="stat-box"><div class="stat-val"><?=formatAmount($totalMontant)?></div><div class="stat-lbl">Total perçu</div></div>
        </div>

        <!-- ═══ Tableau ═══ -->
        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-list"></i> Détail des paiements par élève</div>
            </div>
            <div style="overflow-x:auto;">
            <table class="prog-table hist-table">
                <thead>
                    <tr>
                        <th>Élève</th>
                        <th>Classe</th>
                        <th>Parent</th>
                        <th style="text-align:center">Paiements</th>
                        <th style="text-align:right">Total payé</th>
                        <th>Dernier paiement</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students as $st):
                        $sid = (int)$st['id'];
                        $pays = $paymentsByStudent[$sid] ?? [];
                        $totalPaid = (float)$st['total_paid'];
                        $payCount = (int)$st['payment_count'];
                    ?>
                    <tr class="student-row">
                        <td><a href="javascript:void(0)" class="toggle-details" onclick="togglePay(<?=$sid?>)"><i class="fas fa-chevron-right" id="icon_<?=$sid?>" style="font-size:.7rem;"></i> <?=e($st['last_name'].' '.$st['first_name'])?></a></td>
                        <td><span class="badge-cat"><?=e($st['class_name'] ?? '—')?></span></td>
                        <td style="font-size:.82rem;color:#718096;"><?=e($st['parent_name'] ?? '')?><?=$st['parent_phone']?' ('.e($st['parent_phone']).')':''?></td>
                        <td style="text-align:center"><?=$payCount?></td>
                        <td style="text-align:right;font-weight:700"><?=formatAmount($totalPaid)?></td>
                        <td style="font-size:.82rem;color:#718096;"><?=$st['last_payment']?formatDate($st['last_payment']):'—'?></td>
                    </tr>
                    <tr class="pay-details" id="pay_<?=$sid?>">
                        <td colspan="6">
                            <?php if ($pays): ?>
                                <?php
                                $groups = [];
                                foreach ($pays as $p) {
                                    $m = substr($p['payment_date'], 0, 7);
                                    $groups[$m][] = $p;
                                }
                                ?>
                                <?php foreach ($groups as $month => $ms): ?>
                                <div class="month-group">
                                    <h4><?=strftime('%B %Y', strtotime($month.'-01'))?></h4>
                                    <?php foreach ($ms as $p): ?>
                                    <div class="pay-item">
                                        <span>
                                            <span class="date"><?=formatDate($p['payment_date'])?></span>
                                            — <?=e($p['method'])?>
                                            <?php if ($p['receipt_number']): ?> <code style="font-size:.75rem;">N°<?=e($p['receipt_number'])?></code><?php endif; ?>
                                            <?php if ($p['trimestre']): ?><span style="color:#718096;font-size:.78rem;">(T<?=(int)$p['trimestre']?>)</span><?php endif; ?>
                                        </span>
                                        <span class="amt"><?=formatAmount($p['amount'])?></span>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <span style="color:#a0aec0;">Aucun paiement</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($students)): ?>
                    <tr><td colspan="6"><div class="empty-state"><i class="fas fa-users"></i><p>Aucun élève trouvé</p></div></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
function togglePay(id) {
    const row = document.getElementById('pay_' + id);
    const icon = document.getElementById('icon_' + id);
    row.classList.toggle('open');
    icon.classList.toggle('fa-chevron-right');
    icon.classList.toggle('fa-chevron-down');
}
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>
