@extends('admin.layouts.app')

@section('title', 'Listas de Curso')
@section('page_title', 'Listas de Curso')

@section('content')
    <style>
        .legacy-wrap { background:#efefef; border:1px solid #d0d0d0; padding:18px 14px 28px; }
        .legacy-title { text-align:center; color:#00607f; font-size:38px; margin:8px 0 14px; font-weight:800; }
        .filters { max-width: 980px; margin: 0 auto 8px; }
        .form-grid {
            display:grid;
            grid-template-columns: 90px minmax(260px, 1fr) 90px minmax(260px, 1fr) 16px;
            gap:10px 12px;
            align-items:center;
            margin-bottom:10px;
        }
        .form-grid-second {
            display:grid;
            grid-template-columns: 90px 110px 16px 140px 1fr;
            gap:10px 12px;
            align-items:center;
            margin-bottom:8px;
        }
        .nowrap { white-space: nowrap; }
        label { font-weight:700; font-size:15px; }
        select { background:#d9e7e7; border:1px solid #08708e; border-radius:0; height:30px; padding:4px 8px; width:100%; }
        .req { color:#d98b00; font-weight:700; }
        .print-links {
            display:flex;
            align-items:center;
            justify-content:flex-end;
            gap:8px;
            font-weight:700;
            margin-top:8px;
        }
        .btn-print {
            display:inline-flex;
            align-items:center;
            justify-content:center;
            min-width:140px;
            height:34px;
            padding:0 14px;
            border-radius:6px;
            text-decoration:none;
            font-weight:800;
            border:1px solid #0e6f88;
            background:linear-gradient(180deg, #0f7f9d 0%, #0d6d88 100%);
            color:#fff;
            box-shadow:0 1px 0 rgba(255,255,255,.3) inset, 0 2px 6px rgba(0,0,0,.12);
        }
        .btn-print:hover { filter:brightness(1.05); }
        .table-box { border:2px solid #0e7a96; background:#fff; max-width:980px; margin:0 auto; }
        .table-title { background:#0e6f88; color:#fff; padding:6px 10px; font-weight:800; letter-spacing:2px; text-transform:uppercase; }
        .legacy-table { width:100%; border-collapse:collapse; }
        .legacy-table th, .legacy-table td { border:1px solid #95a5ad; padding:5px 6px; font-size:15px; text-align:left; vertical-align:middle; }
        .legacy-table th { background:#d5dddd; font-weight:800; }
        .legacy-table tbody tr:nth-child(even) { background:#ccdbdd; }
        .total { max-width:980px; margin:4px auto 0; text-align:right; font-size:13px; }
    </style>

    <div class="legacy-wrap">
        <h2 class="legacy-title ui-title">Listas de Curso</h2>

        <form method="GET" class="filters" id="listasForm">
            <input type="hidden" name="annio" value="{{ $annio }}">
            <div class="form-grid">
                <label for="profesor">Profesor</label>
                <select id="profesor" name="profesor" onchange="document.getElementById('listasForm').submit()">
                    <option value="">(Todos)</option>
                    @foreach($profesores as $p)
                        @php
                            $fullName = trim(($p->nombres ?? '') . ' ' . ($p->apellido1 ?? '') . ' ' . ($p->apellido2 ?? ''));
                        @endphp
                        <option value="{{ (int) $p->id }}" @selected((string)$profesor === (string)$p->id)>{{ $fullName }}</option>
                    @endforeach
                </select>
                <label for="asignatura">Asignatura</label>
                <select id="asignatura" name="asignatura" onchange="document.getElementById('listasForm').submit()">
                    <option value="">(Todos)</option>
                    @foreach($asignaturas as $a)
                        <option value="{{ (int) $a->id }}" @selected((string)$asignatura === (string)$a->id)>{{ mb_strtoupper((string)$a->nombre) }}</option>
                    @endforeach
                </select>
                <span class="req">*</span>
            </div>

            <div class="form-grid-second">
                <label for="periodo">Periodo</label>
                <select id="periodo" name="periodo" onchange="document.getElementById('listasForm').submit()">
                    <option value=""></option>
                    @foreach($periodos as $p)
                        <option value="{{ (int) $p->id }}" @selected((string)$periodo === (string)$p->id)>{{ $p->label }}</option>
                    @endforeach
                </select>
                <span class="req">*</span>
                <label for="papel" class="nowrap">Tamaño de papel</label>
                <select id="papel" name="papel" onchange="document.getElementById('listasForm').submit()">
                    <option value="Carta" @selected($papel === 'Carta')>Carta</option>
                    <option value="Oficio" @selected($papel === 'Oficio')>Oficio</option>
                </select>
            </div>
            <div class="print-links">
                <span>Imprimir Lista para:</span>
                <a class="btn-print" href="{{ route('admin.general.cursos.print', ['tipo' => 'calificaciones']) }}" data-print-type="calificaciones">Calificaciones</a>
                <a class="btn-print" href="{{ route('admin.general.cursos.print', ['tipo' => 'asistencia']) }}" data-print-type="asistencia">Asistencia</a>
            </div>
        </form>

        <div class="table-box">
            <div class="table-title ui-table-title">Listas de Curso</div>
            <table class="legacy-table ui-table">
                <thead>
                <tr>
                    <th style="width:30px;"><input type="checkbox" id="all_courses"></th>
                    <th>Curso</th>
                    <th>Nivel</th>
                    <th>Cantidad de estudiantes</th>
                    <th>Director</th>
                </tr>
                </thead>
                <tbody>
                @forelse($rows as $r)
                    <tr>
                        <td><input type="checkbox" class="course-check" value="{{ (int) $r->id }}"></td>
                        <td>{{ $r->nombre }}</td>
                        <td>{{ $r->nivel }}</td>
                        <td>{{ (int) ($r->tot_estudiantes ?? 0) > 0 ? (int) $r->tot_estudiantes : '' }}</td>
                        <td>{{ $r->director }}</td>
                    </tr>
                @empty
                    <tr><td colspan="5">Sin cursos para los filtros aplicados.</td></tr>
                @endforelse
                </tbody>
            </table>
        </div>
        <div class="total ui-total">Total registros: {{ $rows->count() }}</div>
    </div>

    <script>
        (function () {
            const allCourses = document.getElementById('all_courses');
            const checks = Array.from(document.querySelectorAll('.course-check'));
            const printLinks = Array.from(document.querySelectorAll('a[data-print-type]'));

            if (allCourses) {
                allCourses.addEventListener('change', function () {
                    checks.forEach((c) => { c.checked = allCourses.checked; });
                });
            }

            printLinks.forEach((link) => {
                link.addEventListener('click', function (e) {
                    const selected = checks.filter((c) => c.checked);
                    if (selected.length === 0) {
                        e.preventDefault();
                        alert('Debes seleccionar al menos un curso antes de continuar.');
                        return;
                    }

                    const targetUrl = new URL(link.getAttribute('href'), window.location.origin);
                    const form = document.getElementById('listasForm');
                    const formData = new FormData(form);

                    formData.forEach((value, key) => {
                        if (value !== null && value !== '') {
                            targetUrl.searchParams.set(key, String(value));
                        }
                    });

                    selected.forEach((checkbox) => {
                        targetUrl.searchParams.append('curso_ids[]', checkbox.value);
                    });

                    e.preventDefault();
                    window.open(targetUrl.toString(), '_blank', 'noopener');
                });
            });
        })();
    </script>
@endsection

