<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?php
$scoresLocked = !empty($scoresLocked);
$lockAttr = $scoresLocked ? 'disabled' : '';
?>
<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;">Midterm Exam Scores</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/updateMidtermExamScores') ?>" method="post"
            onsubmit="return validateForm()">
            <?= csrf_field() ?>
            <input type="hidden" name="semester" value="<?= esc($semester) ?>">
            <input type="hidden" name="school_year" value="<?= esc($schoolYear) ?>">
            <table id="midtermTable" class="table table-bordered mt-4 w-100" data-no-mgmt-sticky>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>School ID</th>
                        <th>First Name</th>
                        <th>Last 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['school_id']) ?></td>
            <td>
                <a href="#" class="text-decoration-none" data-family-student-id="<?= (int)($student['student_id'] ?? 0) ?>">
                    <?= esc($student['firstname']) ?>
                </a>
            </td>
            <td>
                <a href="#" class="text-decoration-none" data-family-student-id="<?= (int)($student['student_id'] ?? 0) ?>">
                    <?= esc($student['lastname']) ?>
                </a>
            </td>
            <td>
                <input type="number" name="final_score[<?= esc($student['student_id']) ?>][score]"
                    value="<?= esc($student['score'] ?? '') ?>" class="form-control text-center" min="0" max="100" step="0.01"
                    placeholder="Enter score (optional)" <?= $lockAttr ?>>
            </td>
        </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>

        <br>
    </div>
    <?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
  (function ($) {
    // Numeric ordering plug-in reading from input values
    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 initMidtermTable() {
      if (!($ && $.fn && $.fn.DataTable)) return;

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

      // Sync data-order 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);
      });

      // Only one score column: index 4 (0-based)
      const scoreCols = [4];

      $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' },
          { 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(initMidtermTable);
  })(jQuery);
</script>
<?= $this->endSection() ?>
