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

<?php
function format_score($val): string
{
    if ($val === null || $val === '') return 'N/A';
    if (is_numeric($val)) {
        $out = number_format((float)$val, 1, '.', '');
        if (substr($out, -2) === '.0') $out = substr($out, 0, -2);
        return $out;
    }
    return (string)$val;
}

function label_from_type(string $type): string
{
    $map = [
        'midterm' => 'Midterm',
        'final' => 'Final',
        'ptap' => 'PTAP',
        'attendance' => 'Attendance',
        'general' => 'General',
    ];
    $key = strtolower(trim($type));
    return $map[$key] ?? ucfirst($key);
}

$yearCounts = [];
if (!empty($rows)) {
    foreach ($rows as $r) {
        $yearKey = (string)($r['school_year'] ?? '');
        if (!isset($yearCounts[$yearKey])) $yearCounts[$yearKey] = 0;
        $yearCounts[$yearKey]++;
    }
}
$yearRendered = [];
?>

<div class="w-100 py-3 px-3">
    <style>
        .score-card-table { margin-top: 4px; }
        .score-card-table thead th { position: static; }
        .score-card-table tbody tr.score-year-alt-0 > * { background-color: #fff1e6 !important; }
        .score-card-table tbody tr.score-year-alt-1 > * { background-color: #e8f1ff !important; }
        .score-card-table th, .score-card-table td { white-space: nowrap; }
    </style>
    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <div>
            <h2 class="mb-0">Student Score Card</h2>
            <div class="text-muted small">
                <?= esc(($student['firstname'] ?? '') . ' ' . ($student['lastname'] ?? '')) ?>
                <?php if (!empty($student['school_id'])): ?>
                    - ID: <?= esc($student['school_id']) ?>
                <?php endif; ?>
            </div>
        </div>
        <a href="<?= site_url('student/score-card/list') ?>" class="btn btn-outline-secondary">Back</a>
    </div>

    <?php if (empty($rows)): ?>
        <div class="alert alert-warning">No semester scores found for this student.</div>
    <?php else: ?>
        <div class="card shadow-sm">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong>Scores By Year and Semester</strong>
            </div>
            <div class="card-body table-responsive pt-2">
                <table class="table table-striped table-hover align-middle score-card-table no-mgmt-sticky" data-no-mgmt-sticky="1">
                    <thead class="table-light">
                        <tr>
                            <th>School Year</th>
                            <th>Year Score</th>
                            <th>Grade</th>
                            <th>Semester</th>
                            <th>Homework Avg</th>
                            <th>Project Avg</th>
                            <th>Participation</th>
                            <th>Test/Quiz Avg</th>
                            <th>Attendance</th>
                            <th>PTAP</th>
                            <th>Midterm</th>
                            <th>Semester Score</th>
                            <th>Comments</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            $yearIndex = [];
                            $yearOrder = 0;
                        ?>
                        <?php foreach ($rows as $row): ?>
                            <?php
                                $sem = strtolower(trim((string)($row['semester'] ?? '')));
                                $semLabel = $sem !== '' ? ucfirst($sem) : 'N/A';
                                $semParam = $semLabel !== 'N/A' ? $semLabel : '';
                                $testQuiz = $row['quiz_avg'] ?? $row['test_avg'] ?? null;
                                $comments = $row['comments'] ?? [];
                                $yearKey = (string)($row['school_year'] ?? '');
                                if ($yearKey !== '' && !isset($yearIndex[$yearKey])) {
                                    $yearIndex[$yearKey] = $yearOrder % 2;
                                    $yearOrder++;
                                }
                                $rowAlt = $yearIndex[$yearKey] ?? 0;
                            ?>
                            <tr class="score-year-alt-<?= (int)$rowAlt ?>">
                                <?php if (empty($yearRendered[$yearKey])): ?>
                                    <?php $yearRendered[$yearKey] = true; ?>
                                    <td rowspan="<?= (int)($yearCounts[$yearKey] ?? 1) ?>">
                                        <?= esc($row['school_year'] ?? 'N/A') ?>
                                    </td>
                                    <td rowspan="<?= (int)($yearCounts[$yearKey] ?? 1) ?>">
                                        <?= esc(format_score($row['year_score'] ?? null)) ?>
                                    </td>
                                    <td rowspan="<?= (int)($yearCounts[$yearKey] ?? 1) ?>">
                                        <?= esc($row['class_section_name'] ?? '—') ?>
                                    </td>
                                <?php endif; ?>
                                <td>
                                    <?php if (!empty($semParam) && !empty($yearKey)): ?>
                                        <?php
                                            $reportUrl = site_url('report-card/student/' . (int)($student['id'] ?? 0))
                                                . '?school_year=' . urlencode($yearKey)
                                                . '&semester=' . urlencode($semParam)
                                                . '&download=1';
                                        ?>
                                        <a href="<?= esc($reportUrl) ?>" target="_blank" rel="noopener" class="d-inline-flex align-items-center gap-1">
                                            <i class="bi bi-file-earmark-pdf"></i>
                                            <span><?= esc($semLabel) ?></span>
                                        </a>
                                    <?php else: ?>
                                        <?= esc($semLabel) ?>
                                    <?php endif; ?>
                                </td>
                                <td><?= esc(format_score($row['homework_avg'] ?? null)) ?></td>
                                <td><?= esc(format_score($row['project_avg'] ?? null)) ?></td>
                                <td><?= esc(format_score($row['participation_score'] ?? null)) ?></td>
                                <td><?= esc(format_score($testQuiz)) ?></td>
                                <td><?= esc(format_score($row['attendance_score'] ?? null)) ?></td>
                                <td><?= esc(format_score($row['ptap_score'] ?? null)) ?></td>
                                <td><?= esc(format_score($row['midterm_exam_score'] ?? null)) ?></td>
                                <td><?= esc(format_score($row['semester_score'] ?? null)) ?></td>
                                <td style="min-width: 240px;">
                                    <?php if (empty($comments)): ?>
                                        <span class="text-muted">N/A</span>
                                    <?php else: ?>
                                        <?php foreach ($comments as $type => $comment): ?>
                                            <details class="mb-1">
                                                <summary class="small fw-semibold"><?= esc(label_from_type($type)) ?></summary>
                                                <div class="small text-muted mt-1"><?= esc($comment) ?></div>
                                            </details>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

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