<?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();

$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 = $_GET['academic_year'] ?? ($academicYears[0] ?? getDefaultAcademicYear($pdo, $schoolFilter));
$trimestre = isset($_GET['trimestre']) ? (int)$_GET['trimestre'] : getActivePeriod();

// Stats globales
$w = "1=1"; $p = [];
if ($schoolFilter) { $w .= " AND school_id=?"; $p[] = $schoolFilter; }
$w .= " AND academic_year=?"; $p[] = $selectedYear;
if ($trimestre) { $w .= " AND trimestre=?"; $p[] = $trimestre; }

$totalRevenue = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM payments WHERE $w");
$totalRevenue->execute($p);
$totalRevenue = (float)$totalRevenue->fetchColumn();

$totalCount = $pdo->prepare("SELECT COUNT(*) FROM payments WHERE $w");
$totalCount->execute($p);
$totalCount = (int)$totalCount->fetchColumn();

// Par trimestre
$byTrim = $pdo->prepare("SELECT trimestre, COUNT(*) AS cnt, SUM(amount) AS total FROM payments WHERE school_id=? AND academic_year=? GROUP BY trimestre ORDER BY trimestre");
$byTrim->execute([$schoolFilter ?: 0, $selectedYear]);
$byTrim = $byTrim->fetchAll();

// Par classe
$byClass = $pdo->prepare("
    SELECT c.name AS class_name, COUNT(p.id) AS cnt, COALESCE(SUM(p.amount),0) AS total
    FROM payments p
    LEFT JOIN students st ON p.student_id=st.id
    LEFT JOIN classes c ON st.class_id=c.id
    WHERE p.school_id=? AND p.academic_year=?
    GROUP BY c.id, c.name
    ORDER BY " . getClassSortSQL('c') . "
");
$byClass->execute([$schoolFilter ?: 0, $selectedYear]);
$byClass = $byClass->fetchAll();

// Par méthode
$byMethod = $pdo->prepare("SELECT method, COUNT(*) AS cnt, SUM(amount) AS total FROM payments WHERE school_id=? AND academic_year=? GROUP BY method ORDER BY total DESC");
$byMethod->execute([$schoolFilter ?: 0, $selectedYear]);
$byMethod = $byMethod->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Recettes - 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>
        .stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:1rem;margin-bottom:1.5rem}
        .stat-card{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:1.2rem;text-align:center}
        .stat-card .val{font-size:1.5rem;font-weight:800;color:#2d3748}
        .stat-card .lbl{font-size:.85rem;color:#718096;margin-top:4px}
        .stat-card .sub{font-size:.75rem;color:#a0aec0;margin-top:2px}
        .table-mini{width:100%;border-collapse:collapse;font-size:.9rem}
        .table-mini th{background:#f7fafc;padding:.6rem .8rem;text-align:left;font-weight:600;color:#4a5568;border-bottom:2px solid #e2e8f0}
        .table-mini td{padding:.6rem .8rem;border-bottom:1px solid #f0f4f8}
        .table-mini tr:hover td{background:#f7fafc}
        .grid-2{display:grid;grid-template-columns:1fr 1fr;gap:1.5rem}
        @media(max-width:768px){.grid-2{grid-template-columns:1fr}}
        .period-tabs{display:flex;gap:.5rem;margin-bottom:1.5rem;flex-wrap:wrap}
        .period-tabs a{padding:.5rem 1.2rem;border-radius:8px;background:#fff;border:1px solid #e2e8f0;color:#4a5568;text-decoration:none;font-size:.9rem;font-weight:600;transition:all .2s}
        .period-tabs a:hover{border-color:#667eea;color:#667eea}
        .period-tabs a.active{background:#667eea;color:#fff;border-color:#667eea}
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-chart-line"></i> Recettes Générales de l\'école'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <div class="period-tabs">
            <a href="recettes.php?academic_year=<?=urlencode($selectedYear)?>" class="<?=!$trimestre?'active':''?>">Tous</a>
            <a href="recettes.php?academic_year=<?=urlencode($selectedYear)?>&trimestre=1" class="<?=$trimestre==1?'active':''?>">1er Trimestre</a>
            <a href="recettes.php?academic_year=<?=urlencode($selectedYear)?>&trimestre=2" class="<?=$trimestre==2?'active':''?>">2ème Trimestre</a>
            <a href="recettes.php?academic_year=<?=urlencode($selectedYear)?>&trimestre=3" class="<?=$trimestre==3?'active':''?>">3ème Trimestre</a>
            <select onchange="window.location='?academic_year='+this.value<?=$trimestre?'+\'&trimestre='.$trimestre.'\'':''?>" style="padding:.4rem .7rem;border:1px solid #e2e8f0;border-radius:6px;margin-left:auto;">
                <?php foreach ($academicYears as $ay): ?>
                <option value="<?=e($ay)?>" <?=$ay===$selectedYear?'selected':''?>><?=e($ay)?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="stat-grid">
            <div class="stat-card">
                <div class="val"><?=formatAmount($totalRevenue)?></div>
                <div class="lbl">Total des recettes</div>
                <div class="sub"><?=$totalCount?> paiement(s)</div>
            </div>
            <?php foreach ($byTrim as $t): ?>
            <div class="stat-card">
                <div class="val"><?=formatAmount($t['total'])?></div>
                <div class="lbl">Trimestre <?=(int)$t['trimestre']?></div>
                <div class="sub"><?=(int)$t['cnt']?> paiement(s)</div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="grid-2">
            <div class="card">
                <div class="card-header"><span class="card-title"><i class="fas fa-users"></i> Par classe</span></div>
                <div class="data-table-wrapper">
                    <table class="table-mini">
                        <thead><tr><th>Classe</th><th style="text-align:right">Paiements</th><th style="text-align:right">Total</th></tr></thead>
                        <tbody>
                            <?php foreach ($byClass as $c): ?>
                            <tr>
                                <td><?=e($c['class_name'] ?? 'Sans classe')?></td>
                                <td style="text-align:right"><?=(int)$c['cnt']?></td>
                                <td style="text-align:right;font-weight:700"><?=formatAmount($c['total'])?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($byClass)): ?>
                            <tr><td colspan="3" style="text-align:center;color:#999;">Aucune donnée</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="card">
                <div class="card-header"><span class="card-title"><i class="fas fa-credit-card"></i> Par méthode</span></div>
                <div class="data-table-wrapper">
                    <table class="table-mini">
                        <thead><tr><th>Méthode</th><th style="text-align:right">Paiements</th><th style="text-align:right">Total</th></tr></thead>
                        <tbody>
                            <?php foreach ($byMethod as $m): ?>
                            <tr>
                                <td><?=e($m['method'])?></td>
                                <td style="text-align:right"><?=(int)$m['cnt']?></td>
                                <td style="text-align:right;font-weight:700"><?=formatAmount($m['total'])?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($byMethod)): ?>
                            <tr><td colspan="3" style="text-align:center;color:#999;">Aucune donnée</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="../assets/js/main.js"></script>
</body>
</html>
