<?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']);

$schoolFilter = currentSchoolId();
$error = '';
$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);
$currentYear = $academicYears[0] ?? getDefaultAcademicYear($pdo, $schoolFilter);
$selectedYear = $_GET['academic_year'] ?? $currentYear;

// ── Sauvegarde montants ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_fees'])) {
    verifyCsrf();
    foreach ($_POST['amount'] ?? [] as $classId => $trimestres) {
        $classId = (int)$classId;
        foreach ($trimestres as $trim => $amount) {
            $trim = (int)$trim;
            $amt = str_replace([' ', ','], ['', '.'], $amount);
            $amt = max(0, (float)$amt);
            $pdo->prepare("INSERT INTO tuition_fees (school_id, class_id, academic_year, trimestre, amount)
                           VALUES (?,?,?,?,?)
                           ON DUPLICATE KEY UPDATE amount=?")
                ->execute([$schoolFilter ?? 0, $classId, $selectedYear, $trim, $amt, $amt]);
        }
    }
    $_SESSION['flash_toast'] = ['message'=>'Montants de scolarité enregistrés.', 'type'=>'success'];
    header('Location: fees.php?academic_year=' . urlencode($selectedYear));
    exit;
}

// ── Classes ────────────────────────────────────────────────────────────────────
$clStmt = $pdo->prepare("SELECT c.*
    FROM classes c
    WHERE 1=1 AND c.academic_year=?
    ORDER BY " . getClassSortSQL('c'));
$clStmt->execute([$selectedYear]);
$classes = $clStmt->fetchAll();

// ── Montants existants ─────────────────────────────────────────────────────────
$fees = [];
$classIds = array_column($classes, 'id');
if ($classIds) {
    $in = implode(',', array_fill(0, count($classIds), '?'));
    $fStmt = $pdo->prepare("SELECT class_id, trimestre, amount FROM tuition_fees WHERE academic_year=? AND class_id IN ($in)");
    $fStmt->execute(array_merge([$selectedYear], $classIds));
    foreach ($fStmt->fetchAll() as $f) {
        $fees[(int)$f['class_id']][(int)$f['trimestre']] = (float)$f['amount'];
    }
}
$__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>Scolarité - 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">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<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); }
.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; }
.empty-state { text-align:center; padding:3rem 1rem; color:#9CA3AF; }
.empty-state i { font-size:2.5rem; display:block; margin-bottom:.75rem; color:#CBD5E1; }
.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;} }
.fee-card { border:1px solid #E5E7EB; border-radius:10px; margin-bottom:1.5rem; background:#fff; overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,0.04); }
.fee-card-header { padding:.8rem 1.2rem; background:#F9FAFB; border-bottom:1px solid #E5E7EB; display:flex; justify-content:space-between; align-items:center; cursor:pointer; }
.fee-card-header h3 { margin:0; font-size:1rem; color:var(--primary); }
.fee-card-body { padding:1.2rem; display:none; }
.fee-card-body.open { display:block; }
.trimestre-grid { display:flex; gap:.8rem; flex-wrap:wrap; margin-bottom:1rem; }
.trimestre-box { flex:1; min-width:140px; }
.trimestre-box label { display:block; font-size:.85rem; font-weight:600; color:#4A5568; margin-bottom:4px; }
.trimestre-box input { width:100%; padding:.5rem .6rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.95rem; }
.trimestre-box input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(46,117,182,0.15); }
.balance-table { width:100%; border-collapse:collapse; font-size:.85rem; }
.balance-table th { background:var(--primary); color:white; padding:.5rem .7rem; text-align:left; font-weight:600; font-size:.74rem; text-transform:uppercase; letter-spacing:.4px; }
.balance-table td { padding:.5rem .7rem; border-bottom:1px solid #E5E7EB; }
.balance-table tbody tr:hover td { background:#F9FAFB; }
.solde { font-weight:700; }
.solde.pos { color:#276749; }
.solde.neg { color:#E53E3E; }
.solde.zero { color:#A0AEC0; }
.student-count { color:#718096; font-size:.85rem; }
@media (max-width:768px) {
  .prog-header { flex-direction:column; align-items:flex-start; }
  .filters-row { flex-direction:column; }
  .filter-group { min-width:100%; }
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-graduation-cap"></i> Gestion de la scolarité'; include '../includes/topbar.php'; ?>

        <?php if ($__flash): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?=json_encode($__flash['message'])?>,<?=json_encode($__flash['type'])?>);});</script>
        <?php endif; ?>
        <?php if ($error): ?><div class="error-message" style="margin-bottom:1rem;"><?= e($error) ?></div><?php endif; ?>

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1><i class="fas fa-graduation-cap" style="color:var(--primary);"></i> Gestion de la scolarité</h1>
                <p>Définissez les montants par trimestre et consultez les soldes élèves</p>
            </div>
        </div>

        <!-- ═══ Filtres ═══ -->
        <form method="GET" class="filters-card">
            <div class="filters-row">
                <div class="filter-group" style="flex:0 0 220px;">
                    <label><i class="fas fa-calendar-alt"></i> Année scolaire</label>
                    <select name="academic_year" onchange="this.form.submit()">
                        <?php foreach ($academicYears as $ay): ?>
                        <option value="<?= e($ay) ?>" <?= $ay === $selectedYear ? 'selected' : '' ?>><?= e($ay) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </form>

        <!-- ═══ Formulaires par classe ═══ -->
        <form method="POST">
            <?= csrfField() ?>
            <?php
                $chartIndex = 0;
                foreach ($classes as $cl):
                $clId = (int)$cl['id'];
                $t1 = $fees[$clId][1] ?? 0;
                $t2 = $fees[$clId][2] ?? 0;
                $t3 = $fees[$clId][3] ?? 0;
                $totalFee = $t1 + $t2 + $t3;
                $stuStmt = $pdo->prepare("
                    SELECT st.id, st.first_name, st.last_name, st.parent_name, st.parent_phone,
                        COALESCE(SUM(p.amount),0) AS total_paid
                    FROM students st
                    LEFT JOIN payments p ON p.student_id=st.id
                    WHERE st.class_id=?" . ($schoolFilter ? " AND st.school_id=?" : "") . "
                    GROUP BY st.id
                    ORDER BY st.last_name, st.first_name
                ");
                $params = [$clId];
                if ($schoolFilter) $params[] = $schoolFilter;
                $stuStmt->execute($params);
                $students = $stuStmt->fetchAll();
                $tPaid = [1=>0, 2=>0, 3=>0];
                if ($students) {
                    $ids = array_column($students, 'id');
                    $in = implode(',', array_fill(0, count($ids), '?'));
                    $tStmt = $pdo->prepare("SELECT student_id, trimestre FROM payments WHERE student_id IN ($in) AND academic_year=? GROUP BY student_id, trimestre");
                    $tStmt->execute(array_merge($ids, [$selectedYear]));
                    foreach ($tStmt->fetchAll() as $row) { $tPaid[(int)$row['trimestre']]++; }
                }
                $totalStudents = count($students);
                $chartId = 'chart_' . $clId;
            ?>
            <div class="fee-card">
                <div class="fee-card-header" onclick="this.nextElementSibling.classList.toggle('open')">
                    <div>
                        <h3><i class="fas fa-users" style="color:var(--accent);font-size:.85rem;"></i> <?= e($cl['name']) ?></h3>
                        <span class="student-count"><?= count($students) ?> élève(s) — Scolarité totale : <?= formatAmount($totalFee) ?></span>
                    </div>
                    <i class="fas fa-chevron-down" style="color:#A0AEC0;font-size:.85rem"></i>
                </div>
                <div class="fee-card-body open">
                    <div class="trimestre-grid">
                        <div class="trimestre-box">
                            <label><i class="fas fa-calendar-alt"></i> 1er Trimestre</label>
                            <input type="text" name="amount[<?= $clId ?>][1]" value="<?= e($t1 ?: '') ?>" placeholder="0">
                        </div>
                        <div class="trimestre-box">
                            <label><i class="fas fa-calendar-alt"></i> 2ème Trimestre</label>
                            <input type="text" name="amount[<?= $clId ?>][2]" value="<?= e($t2 ?: '') ?>" placeholder="0">
                        </div>
                        <div class="trimestre-box">
                            <label><i class="fas fa-calendar-alt"></i> 3ème Trimestre</label>
                            <input type="text" name="amount[<?= $clId ?>][3]" value="<?= e($t3 ?: '') ?>" placeholder="0">
                        </div>
                    </div>

                    <div style="display:flex;gap:1.5rem;align-items:center;margin-bottom:1rem;flex-wrap:wrap">
                        <div style="position:relative;width:120px;height:120px">
                            <canvas id="<?=$chartId?>"></canvas>
                        </div>
                        <div style="font-size:.85rem;color:#4A5568">
                            <div><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#48bb78;margin-right:6px"></span> Payé T1 : <?=$tPaid[1]?>/<?=$totalStudents?></div>
                            <div><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#ed8936;margin-right:6px"></span> Payé T2 : <?=$tPaid[2]?>/<?=$totalStudents?></div>
                            <div><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#667eea;margin-right:6px"></span> Payé T3 : <?=$tPaid[3]?>/<?=$totalStudents?></div>
                            <div><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#E5E7EB;margin-right:6px"></span> Aucun paiement : <?=$totalStudents - max($tPaid[1], $tPaid[2], $tPaid[3])?></div>
                        </div>
                    </div>

                    <script>
                    new Chart(document.getElementById('<?=$chartId?>'), {
                        type: 'doughnut',
                        data: {
                            labels: ['T1 payé','T2 payé','T3 payé','Aucun'],
                            datasets: [{
                                data: [<?=$tPaid[1]?>,<?=$tPaid[2]?>,<?=$tPaid[3]?>,<?=max(0,$totalStudents - max($tPaid[1],$tPaid[2],$tPaid[3]))?>],
                                backgroundColor: ['#48bb78','#ed8936','#667eea','#E5E7EB'],
                                borderWidth: 0
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: true,
                            cutout: '65%',
                            plugins: { legend: { display: false }, tooltip: { enabled: false } }
                        }
                    });
                    </script>

                    <?php if ($students): ?>
                    <div style="overflow-x:auto;">
                    <table class="balance-table">
                        <thead>
                            <tr>
                                <th>Élève</th>
                                <th>Parent</th>
                                <th style="text-align:right">Dû</th>
                                <th style="text-align:right">Payé</th>
                                <th style="text-align:right">Solde</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($students as $st):
                                $due = $totalFee;
                                $paid = (float)$st['total_paid'];
                                $balance = $paid - $due;
                                $balClass = $balance > 0 ? 'pos' : ($balance < 0 ? 'neg' : 'zero');
                            ?>
                            <tr>
                                <td><?= e($st['last_name'] . ' ' . $st['first_name']) ?></td>
                                <td style="color:#718096;font-size:.82rem"><?= e($st['parent_name'] ?? '') ?><?= $st['parent_phone'] ? ' ('.e($st['parent_phone']).')' : '' ?></td>
                                <td style="text-align:right"><?= formatAmount($due) ?></td>
                                <td style="text-align:right"><?= formatAmount($paid) ?></td>
                                <td style="text-align:right" class="solde <?= $balClass ?>">
                                    <?php if ($balance >= 0): ?>
                                        <?= formatAmount($balance) ?>
                                    <?php else: ?>
                                        -<?= formatAmount(abs($balance)) ?>
                                    <?php endif; ?>
                                </td>
                            </tr>
            <?php $chartIndex++; endforeach; ?>
                        </tbody>
                    </table>
                    </div>
                    <?php else: ?>
                    <div class="empty-state"><i class="fas fa-user-graduate"></i><p>Aucun élève dans cette classe</p></div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>

            <?php if ($classes): ?>
            <div style="display:flex;gap:.75rem;margin-top:.5rem;">
                <button type="submit" name="save_fees" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer les montants</button>
            </div>
            <?php endif; ?>
        </form>
    </div>
</div>

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

<script>
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>
