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

<div class="container-fluid py-4">
    <style>
        .admin-score-table { margin-top: 4px; }
        .admin-score-table thead th { position: static; }
    </style>
    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <div>
            <h2 class="mb-0">Student Score Card (Admin)</h2>
            <div class="text-muted small">Search for a student, then open their score card.</div>
        </div>
    </div>

    <div class="card shadow-sm mb-3">
        <div class="card-body">
            <form id="studentSearchForm" method="get" action="<?= site_url('administrator/student-score-card') ?>">
                <div class="row g-2 justify-content-center">
                    <div class="col-12 col-md-8 col-lg-6">
                        <div class="input-group">
                            <span class="input-group-text">Search Student</span>
                            <input id="globalStudentSearch"
                                   class="form-control"
                                   type="text"
                                   name="q"
                                   placeholder="Type School ID or Student Name"
                                   list="studentSuggestions"
                                   autocomplete="off"
                                   value="<?= esc($query ?? '') ?>" />
                            <button id="globalStudentSearchClear" class="btn btn-outline-secondary" type="button" title="Clear search">Clear</button>
                        </div>
                        <small class="text-muted">Searches all grades.</small>
                    </div>
                </div>
                <button type="submit" class="d-none">Search</button>
            </form>
        </div>
    </div>

    <datalist id="studentSuggestions">
        <?php
            $seen = [];
            foreach (($suggestions ?? []) as $stu):
                $sid = (int)($stu['id'] ?? 0);
                if ($sid <= 0) continue;
                $schoolId = trim((string)($stu['school_id'] ?? ''));
                $label = trim(($stu['firstname'] ?? '') . ' ' . ($stu['lastname'] ?? ''));
                $value = trim(($schoolId !== '' ? $schoolId . ' - ' : '') . $label);
                if ($value === '' || isset($seen[$value])) continue;
                $seen[$value] = true;
        ?>
            <option value="<?= esc($value) ?>"></option>
        <?php endforeach; ?>
    </datalist>

    <?php if (!empty($query) && empty($students)): ?>
        <div class="alert alert-warning">No students found.</div>
    <?php endif; ?>

    <?php if (!empty($students)): ?>
        <div class="card shadow-sm">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong>Results</strong>
                <span class="text-muted small">Showing up to 50</span>
            </div>
            <div class="card-body table-responsive pt-2">
                <table class="table table-striped table-hover align-middle admin-score-table no-mgmt-sticky" data-no-mgmt-sticky="1">
                    <thead class="table-light">
                        <tr>
                            <th>School ID</th>
                            <th>Student</th>
                            <th>Status</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($students as $s): ?>
                            <tr>
                                <td><?= esc($s['school_id'] ?? '') ?></td>
                                <td><?= esc(($s['firstname'] ?? '') . ' ' . ($s['lastname'] ?? '')) ?></td>
                                <td>
                                    <?php if ((int)($s['is_active'] ?? 0) === 1): ?>
                                        <span class="badge text-bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge text-bg-secondary">Inactive</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end">
                                    <form method="post" action="<?= site_url('student/score-card') ?>" class="d-inline">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="student_id" value="<?= (int)($s['id'] ?? 0) ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-primary">Open Score Card</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
  (function () {
    const form = document.getElementById('studentSearchForm');
    const input = document.getElementById('globalStudentSearch');
    const clr = document.getElementById('globalStudentSearchClear');
    const dlist = document.getElementById('studentSuggestions');
    const suggestionSet = new Set(Array.from(dlist?.options || []).map(o => (o.value || '').trim()));
    let lastAutoQuery = '';

    function submitSearch() {
      if (!form) return;
      form.submit();
    }

    input?.addEventListener('keydown', e => {
      if (e.key === 'Enter') { e.preventDefault(); submitSearch(); }
    });

    clr?.addEventListener('click', () => {
      if (input) input.value = '';
      input?.focus();
    });

    function tryAutoRun() {
      const val = (input?.value || '').trim();
      if (!val) return;
      if (suggestionSet.has(val) && val !== lastAutoQuery) {
        lastAutoQuery = val;
        submitSearch();
      }
    }

    input?.addEventListener('change', tryAutoRun);
    input?.addEventListener('input', () => {
      clearTimeout(input.__autoTimer);
      input.__autoTimer = setTimeout(tryAutoRun, 50);
    });
  })();
</script>

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