<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>

<div class="container-fluid">
    <div class="wrapper">
        <h2 class="text-center mt-4 mb-4">Student Decisions — All Students</h2>

        <!-- School Year filter only -->
        <form method="get" class="row g-2 align-items-center justify-content-center mb-3 no-print">
            <div class="col-auto"><label class="form-label mb-0">School year</label></div>
            <div class="col-auto">
                <select name="school_year" class="form-select form-select-sm" style="min-width: 180px;">
                    <?php $years = isset($schoolYears) && is_array($schoolYears) ? $schoolYears : []; ?>
                    <?php foreach ($years as $y):
                        $val = is_array($y) && isset($y['school_year']) ? (string)$y['school_year'] : (string)$y; ?>
                        <option value="<?= esc($val) ?>" <?= ($schoolYear === $val ? 'selected' : '') ?>><?= esc($val) ?></option>
                    <?php endforeach; ?>
                    <?php if (empty($years) && $schoolYear !== ''): ?>
                        <option value="<?= esc($schoolYear) ?>" selected><?= esc($schoolYear) ?></option>
                    <?php endif; ?>
                </select>
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-secondary btn-sm">Apply</button>
                <a class="btn btn-outline-secondary btn-sm" href="?">Reset</a>
            </div>
        </form>

        <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
            <div class="text-muted">
                <?= esc($schoolYear ?? '') ?>
                <?php if ($generated): ?>
                    <span class="badge bg-success ms-2">Saved</span>
                <?php else: ?>
                    <span class="badge bg-warning text-dark ms-2">Not yet generated</span>
                <?php endif; ?>
            </div>
            <div class="d-flex gap-2 flex-wrap no-print">
                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="window.print()">
                    Print Stats
                </button>
                <a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
                    Grading
                </a>
            </div>
        </div>

        <?php if (!empty(session()->getFlashdata('status'))): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?= esc(session()->getFlashdata('status')) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        <?php if (!empty(session()->getFlashdata('error'))): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <?= esc(session()->getFlashdata('error')) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Generate / Regenerate button -->
        <form method="post" action="<?= site_url('grading/decisions/generate') ?>" class="mb-3 no-print">
            <?= csrf_field() ?>
            <input type="hidden" name="school_year" value="<?= esc($schoolYear ?? '') ?>">
            <button type="submit" class="btn btn-primary">
                <?= $generated ? 'Regenerate Decisions' : 'Generate Decisions' ?>
            </button>
            <span class="text-muted small ms-2">
                Year score ≥ 60 → <strong>Pass</strong> (auto) &nbsp;|&nbsp;
                Year score &lt; 60 → pulled from below-60 decisions
            </span>
        </form>

        <?php if (empty($rows)): ?>
            <div class="alert alert-info">No semester scores found for this school year.</div>
        <?php else: ?>

        <?php
        $decisionBadge = [
            'Pass'                 => 'success',
            'Repeat Class'         => 'danger',
            'Make-up exam in fall' => 'info',
            'Deferred decision'    => 'info',
            'Expel'                => 'danger',
            'Withdrawn'            => 'secondary',
        ];
        $sourceBadge = [
            'auto'    => ['bg-success-subtle text-success-emphasis', 'Auto'],
            'manual'  => ['bg-primary-subtle text-primary-emphasis', 'Manual'],
            'pending' => ['bg-warning-subtle text-warning-emphasis', 'Pending'],
        ];

        $stats = ['Pass' => 0, 'Other' => 0, 'Pending' => 0];
        foreach ($rows as $r) {
            if ($r['decision'] === 'Pass') $stats['Pass']++;
            elseif ($r['decision'] === '' || $r['source'] === 'pending') $stats['Pending']++;
            else $stats['Other']++;
        }

        $pct = static function (int $count, int $total): string {
            return $total > 0 ? number_format(($count / $total) * 100, 1) . '%' : '0.0%';
        };

        $genderKey = static function (?string $gender): string {
            $value = strtolower(trim((string)$gender));

            return match (true) {
                in_array($value, ['male', 'm', 'boy', 'boys'], true) => 'boys',
                in_array($value, ['female', 'f', 'girl', 'girls'], true) => 'girls',
                default => 'other',
            };
        };

        $genderStats = static function (array $items) use ($genderKey): array {
            $stats = ['boys' => 0, 'girls' => 0, 'other' => 0];

            foreach ($items as $item) {
                $stats[$genderKey($item['gender'] ?? '')]++;
            }

            return $stats;
        };

        $totalStudents = count($rows);
        $passRows = array_values(array_filter($rows, static fn (array $row): bool => (string)($row['decision'] ?? '') === 'Pass'));
        $trophyRows = array_values(array_filter($rows, static fn (array $row): bool => !empty($row['is_trophy'])));

        $allGenderStats = $genderStats($rows);
        $passGenderStats = $genderStats($passRows);
        $trophyGenderStats = $genderStats($trophyRows);
        ?>

        <!-- Summary cards -->
        <div class="d-flex gap-3 mb-3 flex-wrap no-print">
            <div class="card text-center px-4 py-2 border-success">
                <div class="fs-4 fw-bold text-success"><?= $stats['Pass'] ?></div>
                <div class="text-muted small">Pass</div>
            </div>
            <div class="card text-center px-4 py-2 border-primary">
                <div class="fs-4 fw-bold text-primary"><?= $stats['Other'] ?></div>
                <div class="text-muted small">Other decision</div>
            </div>
            <div class="card text-center px-4 py-2 border-warning">
                <div class="fs-4 fw-bold text-warning"><?= $stats['Pending'] ?></div>
                <div class="text-muted small">Pending</div>
            </div>
            <div class="card text-center px-4 py-2">
                <div class="fs-4 fw-bold"><?= count($rows) ?></div>
                <div class="text-muted small">Total</div>
            </div>
        </div>

        <div class="print-only" style="margin-bottom:14px;">
            <div style="text-align:center;margin-bottom:10px;border-bottom:2px solid #333;padding-bottom:6px;">
                <h2 style="margin:0;">Student Decisions Summary — <?= esc($schoolYear ?? '') ?></h2>
                <p style="margin:3px 0 0;font-size:10px;color:#555;">
                    Trophy counts use the same year-score rule as the trophy final page.
                </p>
            </div>

            <h3 style="margin-bottom:6px;">Print Stats</h3>
            <table data-no-mgmt-sticky style="margin-bottom:12px;">
                <thead>
                    <tr>
                        <th>Metric</th>
                        <th style="text-align:center;">Count</th>
                        <th style="text-align:center;">Percent</th>
                        <th style="text-align:center;">Boys</th>
                        <th style="text-align:center;">Boys %</th>
                        <th style="text-align:center;">Girls</th>
                        <th style="text-align:center;">Girls %</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Total Students</td>
                        <td style="text-align:center;"><?= $totalStudents ?></td>
                        <td style="text-align:center;">100.0%</td>
                        <td style="text-align:center;"><?= $allGenderStats['boys'] ?></td>
                        <td style="text-align:center;"><?= $pct($allGenderStats['boys'], $totalStudents) ?></td>
                        <td style="text-align:center;"><?= $allGenderStats['girls'] ?></td>
                        <td style="text-align:center;"><?= $pct($allGenderStats['girls'], $totalStudents) ?></td>
                    </tr>
                    <tr>
                        <td>Pass</td>
                        <td style="text-align:center;"><?= count($passRows) ?></td>
                        <td style="text-align:center;"><?= $pct(count($passRows), $totalStudents) ?></td>
                        <td style="text-align:center;"><?= $passGenderStats['boys'] ?></td>
                        <td style="text-align:center;"><?= $pct($passGenderStats['boys'], count($passRows)) ?></td>
                        <td style="text-align:center;"><?= $passGenderStats['girls'] ?></td>
                        <td style="text-align:center;"><?= $pct($passGenderStats['girls'], count($passRows)) ?></td>
                    </tr>
                    <tr>
                        <td>Trophies</td>
                        <td style="text-align:center;"><?= count($trophyRows) ?></td>
                        <td style="text-align:center;"><?= $pct(count($trophyRows), $totalStudents) ?></td>
                        <td style="text-align:center;"><?= $trophyGenderStats['boys'] ?></td>
                        <td style="text-align:center;"><?= $pct($trophyGenderStats['boys'], count($trophyRows)) ?></td>
                        <td style="text-align:center;"><?= $trophyGenderStats['girls'] ?></td>
                        <td style="text-align:center;"><?= $pct($trophyGenderStats['girls'], count($trophyRows)) ?></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="table-responsive no-print">
            <table class="table table-bordered table-striped align-middle w-100 all-decisions-dt"
                   data-no-mgmt-sticky data-no-dt-fixedheader>
                <thead class="table-light">
                    <tr>
                        <th>Student Name</th>
                        <th>Section</th>
                        <th class="text-center">Fall Score</th>
                        <th class="text-center">Spring Score</th>
                        <th class="text-center">Year Score</th>
                        <th class="text-center">Decision</th>
                        <th class="text-center">Source</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $row): ?>
                        <?php
                        $yearScore  = $row['year_score'];
                        $decision   = (string)($row['decision'] ?? '');
                        $source     = (string)($row['source'] ?? 'pending');
                        $yearVal    = is_numeric($yearScore) ? (float)$yearScore : null;
                        $rowClass   = '';
                        if ($yearVal !== null && $yearVal < 60) {
                            $rowClass = $yearVal < 50 ? 'grade-red' : 'grade-orange';
                        }
                        $badge       = $decisionBadge[$decision] ?? null;
                        [$srcCls, $srcLabel] = $sourceBadge[$source] ?? ['bg-light text-muted', $source];
                        $studentName = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
                        $fmt = fn($v) => is_numeric($v) ? number_format((float)$v, 2) : '—';
                        ?>
                        <tr class="<?= esc($rowClass) ?>">
                            <td><?= esc($studentName ?: 'N/A') ?></td>
                            <td><?= esc($row['class_section_name'] ?? '—') ?></td>
                            <td class="text-center"><?= esc($fmt($row['fall_score'] ?? null)) ?></td>
                            <td class="text-center"><?= esc($fmt($row['spring_score'] ?? null)) ?></td>
                            <td class="text-center fw-semibold">
                                <?= esc($fmt($yearVal)) ?>
                            </td>
                            <td class="text-center">
                                <?php if ($decision !== '' && $badge): ?>
                                    <span class="badge bg-<?= esc($badge) ?>"><?= esc($decision) ?></span>
                                <?php elseif ($decision !== ''): ?>
                                    <span class="badge bg-secondary"><?= esc($decision) ?></span>
                                <?php else: ?>
                                    <span class="text-muted small">—</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <span class="badge <?= esc($srcCls) ?>"><?= esc($srcLabel) ?></span>
                            </td>
                            <td class="text-muted small"><?= nl2br(esc((string)($row['notes'] ?? ''))) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Legend -->
        <div class="mt-2 mb-4 d-flex gap-2 flex-wrap align-items-center no-print">
            <?php foreach ($decisionBadge as $label => $color): ?>
                <span class="badge bg-<?= esc($color) ?> px-2 py-1"><?= esc($label) ?></span>
            <?php endforeach; ?>
            <span class="text-muted small ms-2">— decision colour key</span>
        </div>

        <?php endif; ?>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<style>
    .print-only { display: none !important; }
    .grade-orange td { background: #fff3cd !important; color: #8a5d00; }
    .grade-red td    { background: #f8d7da !important; color: #842029; }

    @media print {
        .no-print { display: none !important; }
        .print-only { display: block !important; }
        body { font-size: 11px; }
        .container-fluid { padding: 0 !important; }
        table { width: 100%; border-collapse: collapse; font-size: 10px; }
        table th, table td { border: 1px solid #bbb; padding: 3px 5px; }
        table thead {
            background: #333 !important;
            color: #fff !important;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        table thead th {
            position: static !important;
            top: auto !important;
            box-shadow: none !important;
        }
    }
</style>
<script>
(function () {
    if (!window.$ || !$.fn || !$.fn.DataTable) return;
    $(function () {
        const tbl = $('.all-decisions-dt');
        if (!tbl.length) return;
        try {
            tbl.DataTable({
                order: [[1, 'asc'], [0, 'asc']],
                pageLength: 100,
                lengthMenu: [25, 50, 100, 200],
                columnDefs: [{ orderable: false, targets: [7] }]
            });
        } catch (_) {}
    });
})();
</script>
<?= $this->endSection() ?>
