<?php session_start(); ?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <title>Absences — École complète</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --navy:      #0f172a;
            --teal:      #0d9488;
            --teal-lt:   #ccfbf1;
            --teal-dark: #0b7c70;
            --indigo:    #4f46e5;
            --indigo-lt: #eef2ff;
            --amber:     #d97706;
            --amber-lt:  #fef3c7;
            --sky:       #e0f2fe;
            --sky-dark:  #0369a1;
            --slate:     #475569;
            --border:    #e2e8f0;
            --bg:        #f1f5f9;
            --white:     #ffffff;
            --shadow:    0 4px 24px rgba(15,23,42,.08);
        }

        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background: var(--bg);
            color: var(--navy);
            min-height: 100vh;
        }

        /* ── Top bar ── */
        .topbar {
            background: var(--navy);
            padding: 14px 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 2px 12px rgba(0,0,0,.3);
        }
        .topbar-icon {
            width: 38px; height: 38px;
            background: var(--teal);
            border-radius: 10px;
            display: grid; place-items: center;
            flex-shrink: 0;
        }
        .topbar-icon svg { width: 20px; height: 20px; stroke: #fff; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
        .topbar-text h1 { font-size: 1rem; font-weight: 800; color: #fff; }
        .topbar-text p  { font-size: .72rem; color: #94a3b8; }

        /* ── Card ── */
        .card {
            background: var(--white);
            border-radius: 16px;
            box-shadow: var(--shadow);
            padding: 20px;
            margin: 16px 14px;
        }
        .card-title {
            font-size: .72rem;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: .09em;
            color: var(--teal);
            margin-bottom: 16px;
        }

        /* ── Form ── */
        .form-row {
            display: grid;
            gap: 14px;
        }
        @media (min-width: 560px) {
            .form-row { grid-template-columns: 1fr 1fr auto; align-items: end; }
        }
        .field-label {
            display: block;
            font-size: .74rem;
            font-weight: 700;
            color: var(--slate);
            margin-bottom: 5px;
        }
        input[type="date"] {
            width: 100%;
            padding: 10px 13px;
            border: 1.5px solid var(--border);
            border-radius: 10px;
            font-family: inherit;
            font-size: .88rem;
            color: var(--navy);
            background: var(--white);
            outline: none;
            transition: border-color .2s, box-shadow .2s;
        }
        input[type="date"]:focus {
            border-color: var(--teal);
            box-shadow: 0 0 0 3px rgba(13,148,136,.13);
        }
        .btn-search {
            display: flex; align-items: center; justify-content: center; gap: 8px;
            background: var(--teal);
            color: #fff; border: none;
            border-radius: 10px;
            padding: 11px 24px;
            font-family: inherit; font-size: .88rem; font-weight: 700;
            cursor: pointer; width: 100%;
            transition: background .2s, transform .1s;
        }
        .btn-search:hover  { background: var(--teal-dark); }
        .btn-search:active { transform: scale(.97); }
        .btn-search svg { width: 16px; height: 16px; stroke: #fff; fill: none; stroke-width: 2.5; stroke-linecap: round; }
        @media (min-width: 560px) { .btn-search { width: auto; } }

        /* ── Summary strip ── */
        .summary-strip {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 12px;
            margin-bottom: 20px;
        }
        .stat-box {
            border-radius: 14px;
            padding: 14px 16px;
            display: flex; flex-direction: column; gap: 4px;
        }
        .stat-box.total  { background: linear-gradient(135deg, var(--teal) 0%, var(--teal-dark) 100%); }
        .stat-box.cycles { background: linear-gradient(135deg, var(--indigo) 0%, #3730a3 100%); }
        .stat-box.classes{ background: linear-gradient(135deg, var(--amber) 0%, #b45309 100%); }
        .stat-box .s-label { font-size: .68rem; font-weight: 700; text-transform: uppercase; letter-spacing: .07em; color: rgba(255,255,255,.75); }
        .stat-box .s-value { font-size: 1.7rem; font-weight: 800; color: #fff; line-height: 1.1; }
        .stat-box .s-sub   { font-size: .72rem; color: rgba(255,255,255,.7); }

        /* ── Cycle block ── */
        .cycle-block { margin-bottom: 28px; }

        .cycle-header {
            display: flex; align-items: center; gap: 10px;
            background: linear-gradient(90deg, var(--indigo) 0%, #3730a3 100%);
            border-radius: 12px;
            padding: 11px 16px;
            margin-bottom: 14px;
        }
        .cycle-header svg { width: 18px; height: 18px; stroke: rgba(255,255,255,.85); fill: none; stroke-width: 2; flex-shrink: 0; }
        .cycle-header .cname { font-size: .95rem; font-weight: 800; color: #fff; flex: 1; }
        .cycle-header .ctotal{
            background: rgba(255,255,255,.2);
            color: #fff; font-size: .75rem; font-weight: 700;
            padding: 3px 11px; border-radius: 20px;
        }

        /* ── Class block ── */
        .class-block { margin-bottom: 16px; }

        .class-header {
            display: flex; align-items: center; gap: 8px;
            padding: 8px 14px;
            background: var(--amber-lt);
            border-left: 4px solid var(--amber);
            border-radius: 0 8px 8px 0;
            margin-bottom: 10px;
        }
        .class-header svg { width: 15px; height: 15px; stroke: var(--amber); fill: none; stroke-width: 2.2; flex-shrink: 0; }
        .class-header .clname { font-size: .82rem; font-weight: 800; color: var(--navy); flex: 1; }
        .class-header .cltotal{
            background: var(--amber);
            color: #fff; font-size: .72rem; font-weight: 700;
            padding: 2px 10px; border-radius: 20px;
        }

        /* Desktop table */
        .abs-table { width: 100%; border-collapse: collapse; font-size: .84rem; }
        .abs-table thead th {
            background: #f8fafc;
            padding: 9px 13px; text-align: left;
            font-size: .69rem; font-weight: 800;
            text-transform: uppercase; letter-spacing: .07em;
            color: var(--slate); border-bottom: 2px solid var(--border);
        }
        .abs-table tbody tr { border-bottom: 1px solid var(--border); transition: background .15s; }
        .abs-table tbody tr:hover { background: #f8fafc; }
        .abs-table tbody td { padding: 11px 13px; vertical-align: middle; }
        .days-pill {
            display: inline-flex; align-items: center; gap: 4px;
            background: var(--sky); color: var(--sky-dark);
            font-weight: 700; font-size: .76rem;
            padding: 3px 11px; border-radius: 20px;
        }

        /* Mobile cards */
        .abs-list { display: none; }
        @media (max-width: 599px) {
            .abs-table { display: none; }
            .abs-list   { display: flex; flex-direction: column; gap: 9px; }
        }
        .abs-item {
            background: #f8fafc;
            border: 1px solid var(--border);
            border-radius: 11px;
            padding: 12px 14px;
            display: flex; align-items: center; justify-content: space-between; gap: 10px;
        }
        .abs-item .student-name { font-weight: 700; font-size: .88rem; }
        .abs-item .student-num  { font-size: .72rem; color: var(--slate); }

        /* Empty state */
        .empty { text-align: center; padding: 40px 20px; color: var(--slate); }
        .empty svg { width: 48px; height: 48px; stroke: #cbd5e1; fill: none; stroke-width: 1.4; margin-bottom: 12px; display: block; margin-inline: auto; }
        .empty p { font-size: .88rem; }

        @media print {
            .noprint { display: none; }
            body { background: #fff; }
            .card { box-shadow: none; margin: 0; padding: 10px; }
        }
    </style>
</head>
<body>

<?php
include '_serveur.php';
include 'header.php';
?>

<!-- Top bar -->
<div class="topbar noprint">
    <div class="topbar-icon">
        <svg viewBox="0 0 24 24"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
    </div>
    <div class="topbar-text">
        <h1>Absences — École complète</h1>
        <p>Toutes les classes · Tous les cycles</p>
    </div>
</div>

<!-- Search form -->
<div class="card noprint">
    <div class="card-title">🔍 Période de recherche</div>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">
        <div class="form-row">
            <div>
                <label class="field-label" for="date">Date début</label>
                <input type="date" id="date" name="date"
                       value="<?php echo isset($_POST['date']) ? htmlspecialchars($_POST['date']) : ''; ?>">
            </div>
            <div>
                <label class="field-label" for="date1">Date fin</label>
                <input type="date" id="date1" name="date1"
                       value="<?php echo isset($_POST['date1']) ? htmlspecialchars($_POST['date1']) : date('Y-m-d'); ?>">
            </div>
            <div>
                <button class="btn-search" name="envoyer" type="submit">
                    <svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    Chercher
                </button>
            </div>
        </div>
    </form>
</div>

<?php if (isset($_POST['envoyer'])):
    $date  = $link->real_escape_string($_POST['date']);
    $date1 = $link->real_escape_string($_POST['date1']);

    $sql = "SELECT
                absences.studentID,
                absences.message        AS studentName,
                classes.name            AS className,
                classes.id              AS classID,
                cycles.name             AS cycleName,
                cycles.id               AS cycleID
            FROM absences
            INNER JOIN classes ON absences.classID = classes.id
            INNER JOIN cycles  ON cycles.id = classes.cycleID
            WHERE absences.date BETWEEN '$date' AND '$date1'
            ORDER BY cycles.name, classes.name, absences.studentID";

    $req = mysqli_query($link, $sql);

    if (!$req) {
        echo '<div class="card" style="color:#dc2626">Erreur SQL : ' . htmlspecialchars(mysqli_error($link)) . '</div>';
    } else {

        /* ── Build nested structure: cycle → class → student → count ── */
        $data = [];
        while ($row = mysqli_fetch_assoc($req)) {
            $cid  = $row['cycleID'];
            $clid = $row['classID'];
            $sid  = $row['studentID'];

            if (!isset($data[$cid])) {
                $data[$cid] = ['name' => $row['cycleName'], 'classes' => []];
            }
            if (!isset($data[$cid]['classes'][$clid])) {
                $data[$cid]['classes'][$clid] = ['name' => $row['className'], 'students' => []];
            }
            if (!isset($data[$cid]['classes'][$clid]['students'][$sid])) {
                $data[$cid]['classes'][$clid]['students'][$sid] = ['name' => $row['studentName'], 'days' => 0];
            }
            $data[$cid]['classes'][$clid]['students'][$sid]['days']++;
        }

        /* ── Totals for summary strip ── */
        $grandTotal   = 0;
        $totalCycles  = count($data);
        $totalClasses = 0;
        foreach ($data as $cyc) {
            $totalClasses += count($cyc['classes']);
            foreach ($cyc['classes'] as $cl) {
                foreach ($cl['students'] as $st) { $grandTotal += $st['days']; }
            }
        }
?>

<div class="card">
    <div class="card-title">📊 Résultats</div>

    <!-- Summary strip -->
    <div class="summary-strip">
        <div class="stat-box total">
            <div class="s-label">Total absences</div>
            <div class="s-value"><?php echo $grandTotal; ?></div>
            <div class="s-sub">jours cumulés</div>
        </div>
        <div class="stat-box cycles">
            <div class="s-label">Cycles</div>
            <div class="s-value"><?php echo $totalCycles; ?></div>
            <div class="s-sub">concernés</div>
        </div>
        <div class="stat-box classes">
            <div class="s-label">Classes</div>
            <div class="s-value"><?php echo $totalClasses; ?></div>
            <div class="s-sub">concernées</div>
        </div>
    </div>

    <?php if (empty($data)): ?>
        <div class="empty">
            <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
            <p>Aucune absence enregistrée pour cette période.</p>
        </div>
    <?php else:
        foreach ($data as $cyc):
            /* cycle total */
            $cycTotal = 0;
            foreach ($cyc['classes'] as $cl)
                foreach ($cl['students'] as $st) $cycTotal += $st['days'];
    ?>

    <!-- CYCLE block -->
    <div class="cycle-block">
        <div class="cycle-header">
            <svg viewBox="0 0 24 24"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
            <span class="cname"><?php echo htmlspecialchars($cyc['name']); ?></span>
            <span class="ctotal"><?php echo $cycTotal; ?> jr</span>
        </div>

        <?php foreach ($cyc['classes'] as $cl):
            $clTotal = 0;
            foreach ($cl['students'] as $st) $clTotal += $st['days'];
        ?>

        <!-- CLASS block -->
        <div class="class-block">
            <div class="class-header">
                <svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87"/><path d="M16 3.13a4 4 0 010 7.75"/></svg>
                <span class="clname"><?php echo htmlspecialchars($cl['name']); ?></span>
                <span class="cltotal"><?php echo $clTotal; ?> jr</span>
            </div>

            <!-- Desktop table -->
            <table class="abs-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Élève</th>
                        <th>Jours d'absence</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $n = 1; foreach ($cl['students'] as $st): ?>
                    <tr>
                        <td style="color:var(--slate);font-size:.78rem"><?php echo $n++; ?></td>
                        <td><strong><?php echo htmlspecialchars($st['name']); ?></strong></td>
                        <td><span class="days-pill">📅 <?php echo $st['days']; ?> jour<?php echo $st['days'] > 1 ? 's' : ''; ?></span></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Mobile cards -->
            <div class="abs-list">
                <?php $n = 1; foreach ($cl['students'] as $st): ?>
                <div class="abs-item">
                    <div>
                        <div class="student-num"><?php echo $n++; ?></div>
                        <div class="student-name"><?php echo htmlspecialchars($st['name']); ?></div>
                    </div>
                    <span class="days-pill">📅 <?php echo $st['days']; ?> jr</span>
                </div>
                <?php endforeach; ?>
            </div>

        </div><!-- /class-block -->
        <?php endforeach; ?>

    </div><!-- /cycle-block -->
    <?php endforeach; ?>
    <?php endif; ?>

</div><!-- /card -->

<?php } endif; ?>

</body>
</html>
