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

<div class="container mt-4">
  <div class="d-flex justify-content-between align-items-center mb-2">
    <h3 class="mb-0">Enter Scores</h3>
    <a class="btn btn-outline-secondary" href="/admin/competition-winners">Back</a>
  </div>

  <?php $isLocked = !empty($competition['is_locked']); ?>
  <?php $lockedAttr = $isLocked ? 'disabled' : ''; ?>

  <?php if ($isLocked): ?>
    <div class="alert alert-warning">This competition is locked. Unlock it to update scores.</div>
  <?php endif; ?>

  <div class="mb-3">
    <div><strong>Competition:</strong> <?= esc($competition['title']) ?></div>
    <?php if (!empty($classSectionName)): ?>
      <div><strong>Class Section:</strong> <?= esc($classSectionName) ?></div>
      <div>
        <strong>Students:</strong> <?= esc($classStudentCount ?? 0) ?> |
        <strong>Auto Winners:</strong> <?= esc($classAutoWinners ?? 0) ?> |
        <strong>Override:</strong> <?= esc($classOverrideWinners ?? '-') ?> |
        <strong>Final Winners:</strong> <?= esc($classFinalWinners ?? 0) ?> |
        <strong>Questions:</strong> <?= esc($classQuestionCount ?? '-') ?>
      </div>
    <?php endif; ?>
  </div>

  <?php if (!$classSelectionLocked): ?>
    <form method="get" class="row g-2 align-items-end mb-3">
      <div class="col-md-6">
        <label class="form-label">Select Class Section</label>
        <select class="form-select" name="class_section_id" onchange="this.form.submit()" <?= $lockedAttr ?>>
          <option value="">Choose a class</option>
          <?php foreach ($classSections as $section): ?>
            <?php
              $value = (string) ($section['class_section_id'] ?? '');
              $label = $section['class_section_name'] ?? $value;
              $selected = $value !== '' && (int) $value === (int) $activeClassSectionId ? 'selected' : '';
            ?>
            <option value="<?= esc($value) ?>" <?= $selected ?>><?= esc($label) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-6">
        <div class="form-text">Pick a class to load its students for score entry.</div>
      </div>
    </form>
  <?php endif; ?>

  <?php if (session('success')): ?>
    <div class="alert alert-success"><?= esc(session('success')) ?></div>
  <?php endif; ?>

  <form method="post" action="/admin/competition-winners/<?= $competition['id'] ?>/scores">
    <?= csrf_field() ?>
    <input type="hidden" name="class_section_id" value="<?= esc($activeClassSectionId ?? '') ?>">

    <?php if (empty($activeClassSectionId)): ?>
      <div class="alert alert-warning">Select a class section to load students.</div>
    <?php else: ?>
      <link rel="stylesheet" href="https://cdn.datatables.net/v/bs5/dt-2.1.8/r-3.0.3/datatables.min.css">
      <?php $scoreMax = ($classQuestionCount !== null && (int) $classQuestionCount > 0) ? (int) $classQuestionCount : null; ?>
      <table class="table table-bordered table-sm" data-no-mgmt-sticky id="scoresTable">
        <thead class="table-light">
          <tr>
            <th style="width:140px;">School ID</th>
            <th>Student</th>
            <th style="width:180px;">
              Score<?= $scoreMax !== null ? ' (max ' . esc($scoreMax) . ')' : '' ?>
            </th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($students as $s):
          $name = trim(($s['firstname'] ?? '') . ' ' . ($s['lastname'] ?? ''));
          $studentId = $s['id'] ?? $s['student_id'] ?? null;
          $schoolId = $s['school_id'] ?? null;
          $val  = $studentId !== null ? ($scoreMap[$studentId] ?? '') : '';
        ?>
          <tr>
            <td><?= esc($schoolId ?: $studentId) ?></td>
            <td><?= esc($name !== '' ? $name : ('Student #' . $studentId)) ?></td>
            <td data-order="<?= esc($val) ?>">
              <input class="form-control form-control-sm"
                     name="scores[<?= esc($studentId) ?>]"
                     type="number" step="0.01" min="0"
                     value="<?= esc($val) ?>"
                     <?= $scoreMax !== null ? 'max="' . esc($scoreMax) . '"' : '' ?>
                     <?= $lockedAttr ?>>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>

    <div class="d-flex gap-2">
      <button class="btn btn-primary" <?= $lockedAttr ?>>Save Scores</button>
      <a class="btn btn-outline-secondary" href="/admin/competition-winners/<?= $competition['id'] ?>/preview">Preview Winners</a>
    </div>
  </form>
</div>

<script src="https://cdn.datatables.net/v/bs5/dt-2.1.8/r-3.0.3/datatables.min.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    const tableEl = document.getElementById('scoresTable');
    if (!tableEl) {
      return;
    }

    new DataTable(tableEl, {
      responsive: true,
      paging: false,
      searching: false,
      info: false,
      order: [[1, 'asc']],
    });

    tableEl.addEventListener('input', function (event) {
      const target = event.target;
      if (target && target.matches('input')) {
        const cell = target.closest('td');
        if (cell) {
          cell.setAttribute('data-order', target.value.trim());
        }
      }
    });
  });
</script>

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