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

<?php
$title = 'Update Quiz Scores';
$type  = 'quiz';
$scoresLocked = !empty($scoresLocked);
$lockAttr = $scoresLocked ? 'disabled' : '';
?>

<div class="container-xxl py-5">
    <div class="container">
        <div class="text-center mx-auto mb-4 mt-3" style="max-width: 600px;">
            <h2 class="text-dark" style="font-family: Arial, sans-serif;"><?= esc($title) ?></h2>
        </div>

        <?php if (session()->get('status')): ?>
            <div class="alert alert-success">
                <?= session()->get('status') ?>
            </div>
        <?php endif; ?>
        <?php if ($scoresLocked): ?>
            <div class="alert alert-warning">
                Scores are locked for this class. Unlock to edit.
            </div>
        <?php endif; ?>
<div class="d-flex justify-content-between mt-4 flex-wrap gap-2">
                <button type="submit" class="btn btn-success" <?= $lockAttr ?>>
                    <i class="bi bi-save"></i> Save Changes
                </button>
                <a href="<?= base_url('/grading') ?>" class="btn btn-secondary">
                    <i class="bi bi-x-circle"></i> Back to Scores
                </a>
            </div>
        <form action="<?= base_url('/grading/updateQuiz') ?>" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="semester" value="<?= esc($semester) ?>">
            <input type="hidden" name="school_year" value="<?= esc($schoolYear) ?>">

            <table id="quizTable" class="table table-bordered mt-4 w-100" data-no-mgmt-sticky>

                <thead class="table-light">
                    <tr>
                        <th>#</th>
                        <th>School ID</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <?php foreach ($quizHeaders as $index): ?>
                            <th class="text-center"><?= esc("Quiz " . $index) ?></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php $row = 1; ?>
                    <?php foreach ($students as $student): ?>
                        <?php
                        $studentId = $student['id'];
                        $scores = $quizScores[$studentId]['scores'] ?? [];
                        ?>
                        <tr>
                            <td><?= $row++ ?></td>
                            <td><?= esc($student['school_id']) ?></td>
                            <td>
                                <a href="#" class="text-decoration-none" data-family-student-id="<?= (int)$studentId ?>">
                                    <?= esc($student['firstname']) ?>
                                </a>
                            </td>
                            <td>
                                <a href="#" class="text-decoration-none" data-family-student-id="<?= (int)$studentId ?>">
                                    <?= esc($student['lastname']) ?>
                                </a>
                            </td>
                            <input type="hidden" name="student_ids[]" value="<?= esc($studentId) ?>">

                            <?php foreach ($quizHeaders as $index): ?>
                                <?php $scoreValue = $scores[$index] ?? ''; ?>
                                <td class="<?= $scoreValue === '' ? 'bg-warning-subtle' : '' ?>">
                                    <input type="number"
                                        name="scores[<?= $studentId ?>][<?= $index ?>]"
                                        value="<?= esc(is_array($scoreValue) ? '' : $scoreValue) ?>"
                                        class="form-control text-center"
                                        min="0" max="100" step="0.01" <?= $lockAttr ?>>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>

            </table>

            <div class="d-flex justify-content-between mt-4 flex-wrap gap-2">
                <button type="submit" class="btn btn-success" <?= $lockAttr ?>>
                    <i class="bi bi-save"></i> Save Changes
                </button>
                <a href="<?= base_url('/grading') ?>" class="btn btn-secondary">
                    <i class="bi bi-x-circle"></i> Back to Scores
                </a>
            </div>
        </form>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
  (function ($) {
    // Custom ordering plug-in: read numeric value from an input inside the cell
    if ($ && $.fn && $.fn.dataTable && !$.fn.dataTable.ext.order['dom-num-input']) {
      $.fn.dataTable.ext.order['dom-num-input'] = function (settings, col) {
        return this.api()
          .column(col, { order: 'index' })
          .nodes()
          .map(function (td) {
            const val = $('input', td).val();
            const num = parseFloat(val);
            return Number.isFinite(num) ? num : -Infinity;
          });
      };
    }

    function initQuizTable() {
      if (!($ && $.fn && $.fn.DataTable)) return;

      const $table = $('#quizTable');
      if (!$table.length) return;

      // Keep data-order in sync with live input values
      $table.on('input', 'input[type="number"]', function () {
        const num = parseFloat(this.value);
        this.closest('td')?.setAttribute('data-order', Number.isFinite(num) ? num : -Infinity);
      });

      // Score columns start after Last Name (index 0-based)
      const totalCols = $table.find('thead th').length;
      const scoreCols = [];
      for (let i = 4; i < totalCols; i++) scoreCols.push(i);

      $table.DataTable({
        paging: false,
        info: false,
        searching: false,
        autoWidth: false,
        order: [[2, 'asc'], [3, 'asc']],
        columnDefs: [
          { targets: 0, orderable: false, searchable: false },
          { targets: 1, className: 'text-nowrap' },
          ...(scoreCols.length ? [{ targets: scoreCols, orderDataType: 'dom-num-input', orderSequence: ['desc', 'asc'], type: 'num' }] : []),
        ],
        fixedHeader: {
          header: true,
          headerOffset: typeof getFixedHeaderOffset === 'function' ? getFixedHeaderOffset() : 0,
        },
        drawCallback: function () {
          const api = this.api();
          api.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
            cell.textContent = i + 1;
          });
        },
      });
    }

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