<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold font-outfit text-dark m-0">WASSCE Results Manager</h2>
            <p class="text-muted mb-0">Record your official WASSCE grades to compute your aggregate score and check university admission eligibility.</p>
        </div>
        <a href="<?= APP_URL ?>/profile" class="btn btn-outline-primary rounded-pill px-4"><i class="fa-solid fa-arrow-left me-2"></i>My Profile</a>
    </div>

    <!-- Info Card -->
    <div class="card border-0 shadow-sm mb-4 bg-light">
        <div class="card-body p-4 d-flex align-items-center">
            <i class="fa-solid fa-circle-info text-primary fs-3 me-3"></i>
            <div class="text-sm">
                <span class="fw-bold text-dark d-block">Aggregate Calculation Rule</span>
                <span class="text-muted">The university entry aggregate is computed as the sum of grades in the **3 Core Subjects** (English, Core Maths, Integrated Science/Social Studies) plus **3 Elective Subjects**, taking the best grades (where A1 = 1 point and F9 = 9 points; lower aggregate is better).</span>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <!-- Input Form -->
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm p-4">
                <form action="<?= APP_URL ?>/profile/wassce" method="POST">
                    <?= csrf_field() ?>

                    <div class="mb-3 row">
                        <div class="col-md-6">
                            <label for="year" class="form-label text-sm fw-medium">Examination Year</label>
                            <input type="number" class="form-control rounded-3" id="year" name="year" value="<?= htmlspecialchars(!empty($wassce) ? $wassce[0]['year'] : date('Y')) ?>" required>
                        </div>
                    </div>

                    <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">Core Subjects (Required)</h5>
                    
                    <?php
                    // Helper to prefill grades
                    $cores = [
                        'Core Mathematics'   => '',
                        'English Language'   => '',
                        'Integrated Science' => '',
                        'Social Studies'     => ''
                    ];
                    $electives = [];
                    foreach ($wassce as $res) {
                        if (array_key_exists($res['subject'], $cores)) {
                            $cores[$res['subject']] = $res['grade'];
                        } else {
                            $electives[] = [
                                'subject' => $res['subject'],
                                'grade'   => $res['grade']
                            ];
                        }
                    }
                    // Ensure at least 4 elective rows
                    while (count($electives) < 4) {
                        $electives[] = ['subject' => '', 'grade' => ''];
                    }
                    ?>

                    <?php foreach ($cores as $subj => $grd): ?>
                        <div class="row g-3 mb-3 align-items-center">
                            <div class="col-md-7">
                                <input type="text" class="form-control bg-light rounded-3 fw-medium text-dark" name="subjects[]" value="<?= $subj ?>" readonly>
                            </div>
                            <div class="col-md-5">
                                <select class="form-select rounded-3 wassce-grade-select" name="grades[]" required>
                                    <option value="">-- Grade --</option>
                                    <?php foreach ($grades as $g): ?>
                                        <option value="<?= $g ?>" <?= $grd === $g ? 'selected' : '' ?>><?= $g ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <h5 class="fw-bold font-outfit text-dark mt-4 mb-3 border-bottom pb-2">Elective Subjects</h5>
                    
                    <?php foreach ($electives as $i => $el): ?>
                        <div class="row g-3 mb-3 align-items-center">
                            <div class="col-md-7">
                                <input type="text" class="form-control rounded-3" name="subjects[]" value="<?= htmlspecialchars($el['subject']) ?>" placeholder="e.g. Elective Physics, Economics, Costing">
                            </div>
                            <div class="col-md-5">
                                <select class="form-select rounded-3 wassce-grade-select" name="grades[]">
                                    <option value="">-- Grade --</option>
                                    <?php foreach ($grades as $g): ?>
                                        <option value="<?= $g ?>" <?= $el['grade'] === $g ? 'selected' : '' ?>><?= $g ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <div class="mt-4 pt-3 border-top">
                        <button type="submit" class="btn btn-primary rounded-pill px-5 shadow-sm font-outfit fw-bold">Save My Grades</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Sidebar Aggregate Estimator -->
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm p-4 text-center sticky-top" style="top: 20px;">
                <div class="badge-icon-box bg-primary-subtle text-primary rounded-circle mx-auto mb-3"><i class="fa-solid fa-calculator fs-4"></i></div>
                <h5 class="fw-bold font-outfit text-dark mb-1">Calculated Aggregate</h5>
                <p class="text-xs text-muted mb-3">Best 6 subjects score (lower is better)</p>
                
                <div class="display-3 fw-extrabold font-outfit text-gradient mb-2" id="aggregate-display">--</div>
                
                <div class="mt-3 p-3 bg-light rounded text-start text-xs text-muted">
                    <span class="fw-bold text-dark d-block mb-1">WASSCE Grading Scale:</span>
                    <div class="d-flex justify-content-between">
                        <span>A1 (Excellent) = 1 pt</span>
                        <span>B2 (Very Good) = 2 pts</span>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span>B3 (Good) = 3 pts</span>
                        <span>C4 (Credit) = 4 pts</span>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span>C5 (Credit) = 5 pts</span>
                        <span>C6 (Credit) = 6 pts</span>
                    </div>
                    <div class="d-flex justify-content-between text-danger">
                        <span>D7/E8 (Pass) = 7/8 pts</span>
                        <span>F9 (Fail) = 9 pts</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const selects = document.querySelectorAll('.wassce-grade-select');
    const display = document.getElementById('aggregate-display');

    const gradePoints = {
        'A1': 1, 'B2': 2, 'B3': 3,
        'C4': 4, 'C5': 5, 'C6': 6,
        'D7': 7, 'E8': 8, 'F9': 9
    };

    function calculateAggregate() {
        let points = [];
        selects.forEach(select => {
            if (select.value) {
                points.push(gradePoints[select.value]);
            }
        });

        if (points.length < 6) {
            display.textContent = '--';
            return;
        }

        // Sort ascending and sum top 6
        points.sort((a, b) => a - b);
        const sum = points.slice(0, 6).reduce((a, b) => a + b, 0);
        display.textContent = sum;
    }

    selects.forEach(select => {
        select.addEventListener('change', calculateAggregate);
    });

    // Run initially
    calculateAggregate();
});
</script>
