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

<div class="container-fluid">
    <div class="wrapper below-sixty-wrapper">
        <h2 class="text-center mt-4 mb-4 below-sixty-title">Below 60 Summary</h2>

        <?= $this->include('partials/academic_filter') ?>

        <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
            <div class="text-muted">
                <?= esc(ucfirst($semester ?? '')) ?> • <?= esc($schoolYear ?? '') ?>
            </div>
            <?php if (!empty($canViewGrading)): ?>
                <a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
                    Back to Grading
                </a>
            <?php else: ?>
                <span class="text-muted small">You do not have access to the Grading page.</span>
            <?php endif; ?>
        </div>

        <?php
        $displayScore = function ($value) {
            if ($value === null || $value === '') {
                return '—';
            }
            if (is_numeric($value)) {
                return esc(number_format((float)$value, 2, '.', ''));
            }
            return esc($value);
        };
        ?>

        <?php if (empty($rows)): ?>
            <div class="alert alert-success text-center d-inline-block">
                No students below 60 for this selection.
            </div>
        <?php else: ?>
            <div class="table-responsive below-sixty-table">
                <table class="table table-bordered table-striped align-middle w-100 no-mgmt-sticky below-sixty-dt" data-no-mgmt-sticky data-no-dt-fixedheader>
                    <thead class="table-light">
                        <tr>
                            <th>Student Name</th>
                            <th>Section</th>
                            <th>Hwk Avg</th>
                            <th>Project Avg</th>
                            <th>Participation</th>
                            <th>Test Avg</th>
                            <th>PTAP Score</th>
                            <th>Attendance</th>
                            <th>Midterm Score</th>
                            <th><?= strcasecmp($semester ?? '', 'fall') === 0 ? '1st Semester Score' : 'Semester Score' ?></th>
                            <th>Status</th>
                            <th>Email Parent</th>
                            <th>Schedule Meeting</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rows as $row): ?>
                            <?php
                            $scoreRaw = $row['semester_score'] ?? null;
                            $scoreVal = is_numeric($scoreRaw) ? (float)$scoreRaw : null;
                            $scoreClass = '';
                            if ($scoreVal !== null) {
                                if ($scoreVal < 50) {
                                    $scoreClass = 'grade-red';
                                } elseif ($scoreVal < 60) {
                                    $scoreClass = 'grade-orange';
                                }
                            }
                            $studentName = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
                            ?>
                            <?php $isClosed = ($row['status'] ?? 'Open') === 'Closed'; ?>
                            <tr class="<?= esc($scoreClass) ?>">
                                <td><?= esc($studentName !== '' ? $studentName : 'N/A') ?></td>
                                <td><?= esc($row['class_section_name'] ?? '—') ?></td>
                                <td class="text-center"><?= $displayScore($row['homework_avg'] ?? null) ?></td>
                                <td class="text-center"><?= $displayScore($row['project_avg'] ?? null) ?></td>
                                <td class="text-center"><?= $displayScore($row['participation_score'] ?? null) ?></td>
                                <td class="text-center"><?= $displayScore($row['test_avg'] ?? null) ?></td>
                                <td class="text-center"><?= $displayScore($row['ptap_score'] ?? null) ?></td>
                                <td class="text-center"><?= $displayScore($row['attendance_score'] ?? null) ?></td>
                                <td class="text-center"><?= $displayScore($row['midterm_exam_score'] ?? null) ?></td>
                                <td class="text-center"><?= $displayScore($row['semester_score'] ?? null) ?></td>
                                <td class="text-center">
                                    <form method="post" action="<?= site_url('grading/below-60/status') ?>" class="d-flex align-items-center gap-2 justify-content-center">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="student_id" value="<?= esc((string)($row['student_id'] ?? '')) ?>">
                                        <input type="hidden" name="semester" value="<?= esc((string)($semester ?? '')) ?>">
                                        <input type="hidden" name="school_year" value="<?= esc((string)($schoolYear ?? '')) ?>">
                                        <select name="status" class="form-select form-select-sm" style="width: 110px;">
                                            <option value="Open" <?= ($row['status'] ?? 'Open') === 'Open' ? 'selected' : '' ?>>Open</option>
                                            <option value="Closed" <?= ($row['status'] ?? '') === 'Closed' ? 'selected' : '' ?>>Closed</option>
                                        </select>
                                        <input type="text" name="note" class="form-control form-control-sm" style="width: 140px;" placeholder="Note (optional)" value="<?= esc((string)($row['note'] ?? '')) ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-secondary">Update</button>
                                    </form>
                                </td>
                                <td class="text-center">
                                    <?php if ($isClosed): ?>
                                        <button type="button" class="btn btn-sm btn-secondary" disabled>Send Email</button>
                                    <?php else: ?>
                                        <a class="btn btn-sm btn-outline-primary"
                                           href="<?= site_url('grading/below-60/email/edit?student_id=' . (int)($row['student_id'] ?? 0) . '&semester=' . rawurlencode((string)($semester ?? '')) . '&school_year=' . rawurlencode((string)($schoolYear ?? ''))) ?>">
                                            Send Email
                                        </a>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <?php if ($isClosed): ?>
                                        <button class="btn btn-sm btn-secondary" disabled>Schedule</button>
                                    <?php else: ?>
                                        <a class="btn btn-sm btn-outline-secondary"
                                           href="<?= site_url('grading/below-60/schedule?student_id=' . (int)($row['student_id'] ?? 0) . '&semester=' . rawurlencode((string)($semester ?? '')) . '&school_year=' . rawurlencode((string)($schoolYear ?? ''))) ?>">
                                            Schedule
                                        </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<style>
    .grade-orange td { background: #fff3cd !important; color: #8a5d00; font-weight: 600; }
    .grade-red td { background: #f8d7da !important; color: #842029; font-weight: 600; }
    .below-sixty-wrapper { padding-top: 0.75rem; }
    .below-sixty-title { position: relative; z-index: 1; margin-bottom: 1.25rem; }
    .below-sixty-table { margin-top: 0.75rem; }
</style>
<script>
    (function() {
        if (!window.$ || !$.fn || !$.fn.DataTable) return;
        $(function() {
            const table = $('.below-sixty-dt');
            if (!table.length) return;
            try {
                table.DataTable({
                    order: [[8, 'asc']],
                    pageLength: 100,
                    lengthMenu: [10, 25, 50, 100, 200]
                });
            } catch (_) {}
        });
    })();
</script>
<?= $this->endSection() ?>
