@extends('layouts.app')

@section('title','Students')

@section('content')
<div class="card">
  <div class="card-header" style="display:flex; align-items:center; justify-content:space-between;">
    <div>Students</div>
    <div style="display:flex; gap:8px;">
      <a class="btn" href="{{ route('students.qr') }}">Print QRs</a>
      <a class="btn" href="{{ route('students.create') }}">Add Student</a>
    </div>
  </div>
  <div class="card-body" style="overflow-x:auto;">
    <form method="GET" action="{{ route('students.index') }}" style="display:flex; gap:10px; align-items:end; margin-bottom:12px; flex-wrap:wrap;">
      <div>
        <label>Search</label>
        <input type="text" name="q" value="{{ $q ?? '' }}" placeholder="Name or QR UID" style="padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
      </div>
      <div>
        <label>Grade</label>
        <select name="grade_id" style="padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
          <option value="">All</option>
          @foreach(($grades ?? []) as $g)
            <option value="{{ $g->id }}" {{ (string)($selectedGradeId ?? '') === (string)$g->id ? 'selected' : '' }}>{{ $g->name }}</option>
          @endforeach
        </select>
      </div>
      <div>
        <label>Per Page</label>
        <select name="per_page" style="padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
          @foreach([10,20,50,100] as $n)
            <option value="{{ $n }}" {{ ($perPage ?? 10) == $n ? 'selected' : '' }}>{{ $n }}</option>
          @endforeach
        </select>
      </div>
      <div>
        <button class="btn" type="submit">Apply</button>
      </div>
    </form>
    @if (session('ok'))
      <div style="margin-bottom:12px; padding:10px 12px; border-radius:10px; background:rgba(13,71,161,0.08); color:#0D47A1;">
        {!! session('ok') !!}
      </div>
    @endif
    <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:12px; flex-wrap:wrap;">
      <div style="display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
        <a class="btn" href="{{ route('students.export') }}">Export CSV</a>
        <a class="btn secondary" href="{{ route('students.csv_template') }}" style="background:#90A4AE;">Download CSV Template</a>
        <form method="POST" action="{{ route('students.seed_demo') }}" onsubmit="return confirm('Seed ~20 demo students?');">
          @csrf
          <button type="submit" class="btn" style="background:#1565C0;">Add Demo Students</button>
        </form>
      </div>
      <form method="POST" action="{{ route('students.import') }}" enctype="multipart/form-data" style="display:flex; align-items:center; gap:8px;">
        @csrf
        <input type="file" name="csv_file" accept=".csv,text/csv" required />
        <button class="btn" type="submit">Import CSV</button>
      </form>
    </div>

    <details style="margin-bottom:12px;">
      <summary style="cursor:pointer;">Advanced Export Options</summary>
      <div style="margin-top:8px; display:flex; align-items:center; gap:14px; flex-wrap:wrap;">
        <div class="muted">Select columns to export:</div>
        @php $defaultCols = ['last_name','first_name','gender','grade','status','qr_uid']; @endphp
        @foreach (['last_name'=>'Last Name','first_name'=>'First Name','gender'=>'Gender','grade'=>'Grade','status'=>'Status','qr_uid'=>'QR UID'] as $key=>$label)
          <label style="display:inline-flex; gap:6px; align-items:center;"><input type="checkbox" class="exp-col" value="{{ $key }}" {{ in_array($key,$defaultCols) ? 'checked' : '' }}> {{ $label }}</label>
        @endforeach
        <button id="btnExportAdv" type="button" class="btn">Export Selected</button>
      </div>
    </details>
    @if ($students->count() === 0)
      <p>No students yet.</p>
    @else
      <form id="bulkForm" method="POST" action="{{ route('students.bulk_destroy') }}">
        @csrf
      <table>
        <thead>
          <tr>
            <th style="width:36px;"><input type="checkbox" id="selectAll"></th>
            <th>
              @php $nextDir = ($sort==='last_name' && $dir==='asc') ? 'desc' : 'asc'; @endphp
              <a href="{{ route('students.index', array_merge(request()->all(), ['sort' => 'last_name', 'dir' => $nextDir])) }}">Name</a>
              @if($sort==='last_name') <span class="muted">{{ $dir==='asc' ? '▲' : '▼' }}</span> @endif
            </th>
            <th>
              @php $nextDir = ($sort==='gender' && $dir==='asc') ? 'desc' : 'asc'; @endphp
              <a href="{{ route('students.index', array_merge(request()->all(), ['sort' => 'gender', 'dir' => $nextDir])) }}">Gender</a>
              @if($sort==='gender') <span class="muted">{{ $dir==='asc' ? '▲' : '▼' }}</span> @endif
            </th>
            <th>
              @php $nextDir = ($sort==='grade' && $dir==='asc') ? 'desc' : 'asc'; @endphp
              <a href="{{ route('students.index', array_merge(request()->all(), ['sort' => 'grade', 'dir' => $nextDir])) }}">Grade</a>
              @if($sort==='grade') <span class="muted">{{ $dir==='asc' ? '▲' : '▼' }}</span> @endif
            </th>
            <th>
              @php $nextDir = ($sort==='status' && $dir==='asc') ? 'desc' : 'asc'; @endphp
              <a href="{{ route('students.index', array_merge(request()->all(), ['sort' => 'status', 'dir' => $nextDir])) }}">Status</a>
              @if($sort==='status') <span class="muted">{{ $dir==='asc' ? '▲' : '▼' }}</span> @endif
            </th>
            <th>QR UID</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          @foreach ($students as $s)
            <tr>
              <td><input type="checkbox" name="ids[]" value="{{ $s->id }}" class="rowChk"></td>
              <td>{{ $s->last_name }}, {{ $s->first_name }}</td>
              <td>{{ $s->gender }}</td>
              <td>{{ $s->grade_name }}</td>
              <td>
                <span style="padding:4px 8px; border-radius:8px; font-size:12px; font-weight:600; {{ $s->status==='active' ? 'background:rgba(76,175,80,0.1); color:#388E3C;' : 'background:rgba(211,47,47,0.1); color:#C62828;' }}">{{ ucfirst($s->status) }}</span>
              </td>
              <td><code>{{ $s->qr_uid }}</code></td>
              <td>
                <div style="display:flex; gap:6px;">
                  <a class="btn" href="{{ route('students.edit', $s->id) }}">Edit</a>
                  <form method="POST" action="{{ route('students.toggle', $s->id) }}" onsubmit="return confirm('Toggle status for this student?');">
                    @csrf
                    <button type="submit" class="btn" style="background:#0D47A1;">Toggle Status</button>
                  </form>
                  <form method="POST" action="{{ route('students.destroy', $s->id) }}" onsubmit="return confirm('Delete this student? This action cannot be undone.');">
                    @csrf
                    <button type="submit" class="btn secondary" style="background:#D32F2F;">Delete</button>
                  </form>
                </div>
              </td>
            </tr>
          @endforeach
        </tbody>
      </table>
      <div style="margin-top:10px; display:flex; gap:8px;">
        <button type="submit" form="bulkForm" class="btn secondary" style="background:#D32F2F;" onclick="return confirm('Delete selected students? This cannot be undone.');">Bulk Delete Selected</button>
      </div>
      </form>
      <div style="margin-top:12px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px;">
        <div class="muted">Showing {{ $students->firstItem() }}–{{ $students->lastItem() }} of {{ $students->total() }} students</div>
        <div>{{ $students->links() }}</div>
      </div>
    @endif
  </div>
</div>

<dialog id="confirmDeleteModal">
  <form method="dialog" style="background:#fff; border-radius:12px; padding:18px; min-width:320px;">
    <h3 style="margin-top:0; color:#0D47A1;">Confirm Deletion</h3>
    <p>Delete this student? This action cannot be undone.</p>
    <div style="display:flex; gap:8px; justify-content:flex-end; margin-top:12px;">
      <button class="btn" value="cancel" style="background:#90A4AE;">Cancel</button>
      <button class="btn secondary" value="confirm" style="background:#D32F2F;">Delete</button>
    </div>
  </form>
</dialog>

<script>
  // Optional enhancement: Use modal instead of browser confirm for delete
  document.addEventListener('DOMContentLoaded', function(){
    const modal = document.getElementById('confirmDeleteModal');
    const selectAll = document.getElementById('selectAll');
    const rowChks = document.querySelectorAll('.rowChk');
    if (selectAll && rowChks.length) {
      selectAll.addEventListener('change', function(){
        rowChks.forEach(ch => ch.checked = selectAll.checked);
      });
    }
    document.querySelectorAll('form[action$="/delete"]').forEach(function(form){
      form.addEventListener('submit', function(e){
        e.preventDefault();
        if (!modal.showModal) { if (confirm('Delete this student? This action cannot be undone.')) form.submit(); return; }
        modal.showModal();
        modal.addEventListener('close', function handler(){
          modal.removeEventListener('close', handler);
          if (modal.returnValue === 'confirm') form.submit();
        });
      });
    });

    // Advanced export builder
    const btnExportAdv = document.getElementById('btnExportAdv');
    if (btnExportAdv) {
      btnExportAdv.addEventListener('click', function(){
        const cols = Array.from(document.querySelectorAll('.exp-col:checked')).map(cb=>cb.value);
        if (cols.length === 0) { alert('Select at least one column'); return; }
        const params = new URLSearchParams(window.location.search);
        cols.forEach(c=>params.append('cols[]', c));
        window.location.href = '{{ route('students.export_advanced') }}' + '?' + params.toString();
      });
    }
  });
  </script>
@endsection
