@extends('layouts.app')
@section('title', 'Promote Students')
@section('page_title', 'Promote Students')
@section('breadcrumbs')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li>
    <li class="breadcrumb-item"><a href="{{ route('students.index') }}">Students</a></li>
    <li class="breadcrumb-item active">Promote</li>
@endsection

@section('content')
    {{-- Step 1 — choose the class/section to promote --}}
    <div class="card mb-3">
        <div class="card-body">
            <h6 class="text-muted mb-3"><i class="bi bi-1-circle me-1"></i>Select class &amp; section to promote</h6>
            <form method="GET" class="row g-2 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small">Class <span class="text-danger">*</span></label>
                    <select name="class_id" id="src_class" class="form-select form-select-sm" required>
                        <option value="">Choose class…</option>
                        @foreach($classes as $class)
                            <option value="{{ $class->id }}" @selected(($sourceClassId ?? '') == $class->id)>{{ $class->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small">Section</label>
                    <select name="section_id" id="src_section" class="form-select form-select-sm">
                        <option value="">All Sections</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button class="btn btn-sm btn-primary"><i class="bi bi-search me-1"></i>Load Students</button>
                </div>
            </form>
        </div>
    </div>

    @error('student_ids')
        <div class="alert alert-warning py-2"><i class="bi bi-exclamation-triangle me-1"></i>{{ $message }}</div>
    @enderror

    @if($sourceClassId)
        @if($students->isEmpty())
            <div class="alert alert-info"><i class="bi bi-info-circle me-1"></i>No active students found in the selected class/section.</div>
        @else
            {{-- Step 2 — pick target and confirm the roster --}}
            <form method="POST" action="{{ route('students.promote-bulk') }}"
                  data-confirm="Promote the selected students to the chosen class? This changes their class/section.">
                @csrf

                <div class="card mb-3">
                    <div class="card-body">
                        <h6 class="text-muted mb-3"><i class="bi bi-2-circle me-1"></i>Promote selected students to…</h6>
                        <div class="row g-2 align-items-end">
                            <div class="col-md-3">
                                <label class="form-label small">Target Class <span class="text-danger">*</span></label>
                                <select name="target_class_id" id="tgt_class" class="form-select form-select-sm" required>
                                    <option value="">Choose class…</option>
                                    @foreach($classes as $class)
                                        <option value="{{ $class->id }}" @selected(($defaultTargetId ?? '') == $class->id)>{{ $class->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label small">Target Section</label>
                                <select name="target_section_id" id="tgt_section" class="form-select form-select-sm">
                                    <option value="">Keep unassigned</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <div class="small text-muted">
                                    @if($defaultTargetId)
                                        <i class="bi bi-lightbulb me-1"></i>Defaulted to the next class in sequence. Change it if needed.
                                    @else
                                        <i class="bi bi-exclamation-circle me-1"></i>No next class was found automatically — please choose the target class.
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center py-2">
                        <span class="fw-semibold">
                            <i class="bi bi-mortarboard me-1"></i>{{ $sourceClass?->name }}
                            @if($sourceSectionId){{ ' / '.optional($students->first()?->section)->name }}@endif
                            <span class="text-muted">— {{ $students->count() }} student(s)</span>
                        </span>
                        <div class="form-check mb-0">
                            <input class="form-check-input" type="checkbox" id="check_all" checked>
                            <label class="form-check-label small" for="check_all">Select all</label>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th style="width:44px"></th>
                                        <th style="width:60px">#</th>
                                        <th>Adm #</th>
                                        <th>Name</th>
                                        <th>Current Class / Section</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($students as $i => $s)
                                        <tr>
                                            <td>
                                                <input class="form-check-input row-check" type="checkbox"
                                                       name="student_ids[]" value="{{ $s->id }}" checked>
                                            </td>
                                            <td class="text-muted">{{ $i + 1 }}</td>
                                            <td>{{ $s->admission_number }}</td>
                                            <td class="fw-semibold">{{ $s->name }}</td>
                                            <td class="text-muted">
                                                {{ $sourceClass?->name }}{{ $s->section ? ' / '.$s->section->name : '' }}
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer d-flex justify-content-between align-items-center">
                        <span class="text-muted small"><span id="sel_count">{{ $students->count() }}</span> of {{ $students->count() }} selected</span>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-arrow-up-circle me-1"></i>Promote Selected
                        </button>
                    </div>
                </div>
            </form>
        @endif
    @endif
@endsection

@push('scripts')
<script>
    const PR_SECTIONS = @json($sections ?? []);
    const srcSel = @json($sourceSectionId ?? '');

    // Populate a section dropdown filtered by a chosen class.
    function fillSections(classSelId, sectionSelId, placeholder, selectedId) {
        const c = document.getElementById(classSelId).value;
        const sel = document.getElementById(sectionSelId);
        if (!sel) return;
        sel.innerHTML = '<option value="">' + placeholder + '</option>';
        PR_SECTIONS.filter(s => !c || String(s.class_id) === String(c)).forEach(s => {
            const o = document.createElement('option');
            o.value = s.id; o.textContent = s.name;
            if (String(s.id) === String(selectedId)) o.selected = true;
            sel.appendChild(o);
        });
    }

    // Source (Step 1)
    document.getElementById('src_class').addEventListener('change',
        () => fillSections('src_class', 'src_section', 'All Sections', srcSel));
    fillSections('src_class', 'src_section', 'All Sections', srcSel);

    // Target (Step 2) — only present once a roster is shown
    const tgtClass = document.getElementById('tgt_class');
    if (tgtClass) {
        tgtClass.addEventListener('change',
            () => fillSections('tgt_class', 'tgt_section', 'Keep unassigned', ''));
        fillSections('tgt_class', 'tgt_section', 'Keep unassigned', '');
    }

    // Select-all + live count
    const checkAll = document.getElementById('check_all');
    const rowChecks = () => Array.from(document.querySelectorAll('.row-check'));
    const countEl = document.getElementById('sel_count');
    function refreshCount() {
        if (countEl) countEl.textContent = rowChecks().filter(c => c.checked).length;
        if (checkAll) {
            const boxes = rowChecks();
            checkAll.checked = boxes.length > 0 && boxes.every(c => c.checked);
            checkAll.indeterminate = boxes.some(c => c.checked) && !checkAll.checked;
        }
    }
    if (checkAll) {
        checkAll.addEventListener('change', () => {
            rowChecks().forEach(c => { c.checked = checkAll.checked; });
            refreshCount();
        });
    }
    rowChecks().forEach(c => c.addEventListener('change', refreshCount));
    refreshCount();
</script>
@endpush
