<?= $this->extend('layout/main_layout') ?>
<?= $this->section('content') ?>
<div class="container-xxl py-5">
    <div class="container">
        <div class="text-center mx-auto mb-5 wow fadeInUp" data-wow-delay="0.1s" style="max-width: 600px;">
            <br>
            <h2 class="text-dark" style="font-family: Arial, sans-serif;">Add Midterm Exam Scores</h2>
        </div>

        <?php if (session()->get('status')): ?>
            <div class="alert alert-success">
                <?= session()->get('status') ?>
            </div>
        <?php endif; ?>
        <?php
        $formatScore = static function ($value) {
            return ($value === null || $value === '') ? '' : esc($value);
        };
        $missingOkMap = $missingOkMap ?? [];
        ?>

        <form action="<?= base_url('/teacher/updateMidtermExamScores') ?>" method="post"
            onsubmit="return validateForm()">
            <?= csrf_field() ?>

            <table class="table table-bordered mt-4" id="midtermExamTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Student Name</th>
                        <th class="text-center">Midterm Exam Score</th>

                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students as $index => $student): ?>
                        <tr>
                            <td><?= $index + 1 ?></td>
                            <td><?= esc($student['firstname']) ?> <?= esc($student['lastname']) ?></td>
                            <td>
                                <?php
                                $rawScore = $student['score'] ?? null;
                                $isEmptyScore = ($rawScore === null || $rawScore === '');
                                $studentId = (int) ($student['student_id'] ?? 0);
                                $isMissingOk = !empty($missingOkMap[$studentId][0]);
                                ?>
                                <input type="number" name="final_score[<?= esc($student['student_id']) ?>][score]"
                                    value="<?= $formatScore($rawScore) ?>" class="form-control text-center <?= $isEmptyScore ? 'score-empty' : '' ?>" min="0" max="100" step="0.01"
                                    placeholder="Enter score">
                                <label class="missing-check mt-1 <?= $isEmptyScore ? '' : 'd-none' ?>">
                                    <input type="checkbox"
                                        name="missing_ok[<?= esc($student['student_id']) ?>][midterm]"
                                        value="1"
                                        class="missing-score-checkbox"
                                        data-field-label="Midterm Exam" <?= $isMissingOk ? 'checked' : '' ?>>
                                    Missing ok
                                </label>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <button type="submit" class="btn btn-success">Save Changes</button>
            <a href="<?= base_url('/teacher/scores'); ?>" class="btn btn-info">
                <i class="bi bi-arrow-left-circle"></i> Back to Scores
            </a>
        </form>
        <br>
    </div>
    <style>
        .score-empty {
            background-color: #fff3cd;
        }
        .missing-check {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-size: 0.75rem;
            color: #6c757d;
        }
    </style>
    <?= $this->endSection() ?>

    <?= $this->section('scripts') ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.10/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.10/css/dataTables.bootstrap5.min.css">
    <script src="https://cdn.datatables.net/1.13.10/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.10/js/dataTables.bootstrap5.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const toggleEmptyClass = (input) => {
                if (input.value === '' || input.value === null) {
                    input.classList.add('score-empty');
                } else {
                    input.classList.remove('score-empty');
                }
            };
            const toggleMissingCheck = (input) => {
                const label = input.parentElement ? input.parentElement.querySelector('.missing-check') : null;
                if (!label) return;
                const empty = input.value === '' || input.value === null;
                label.classList.toggle('d-none', !empty);
                if (!empty) {
                    const checkbox = label.querySelector('input[type="checkbox"]');
                    if (checkbox) checkbox.checked = false;
                }
            };

            document.querySelectorAll('input[type="number"]').forEach((input) => {
                toggleEmptyClass(input);
                toggleMissingCheck(input);
                input.addEventListener('input', () => {
                    toggleEmptyClass(input);
                    toggleMissingCheck(input);
                });
            });
        });
    </script>
    <script>
        (function($) {
            function initMidtermExamTable() {
                if (!($ && $.fn && $.fn.DataTable)) return;
                const $table = $('#midtermExamTable');
                if (!$table.length) return;

                $table.DataTable({
                    paging: false,
                    info: false,
                    searching: false,
                    autoWidth: false,
                    order: [[1, 'asc']],
                    columnDefs: [
                        { targets: 0, orderable: false, searchable: false },
                        { targets: 2, orderable: false, searchable: false },
                    ],
                    drawCallback: function() {
                        const api = this.api();
                        api.column(0, { search: 'applied', order: 'applied' }).nodes().each(function(cell, i) {
                            cell.textContent = i + 1;
                        });
                    },
                });
            }

            $(document).ready(initMidtermExamTable);
        })(jQuery);
    </script>
    <?= $this->endSection() ?>
