@extends('layouts.app')

@section('content')
<div class="space-y-6">
    <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8">
        <h2 class="text-2xl font-bold text-slate-900">Barra institucional</h2>
        @if($institutionLocked)
            <div class="mt-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-amber-700">
                Configuración institucional bloqueada. Una vez inicia el proceso electoral (primer voto) o se configura por primera vez, no se puede modificar.
            </div>
        @else
            <form method="POST" action="{{ route('admin.institution.update') }}" enctype="multipart/form-data" class="mt-5 grid grid-cols-1 md:grid-cols-2 gap-4">
                @csrf
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Nombre del colegio</label>
                    <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="text" name="school_name" value="{{ $institution?->school_name ?? 'SISVOT Colegio' }}" required>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Año electoral</label>
                    <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="text" name="election_year" value="{{ $institution?->election_year ?? now()->year }}" required>
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Logo del colegio (cualquier extensión, nombre con espacios)</label>
                    <input id="school_logo_input" class="w-full rounded-xl border border-slate-300 px-4 py-3 bg-white" type="file" name="school_logo">
                    <div class="mt-3">
                        <img id="school_logo_preview" src="{{ $institution?->logo_url }}" alt="Preview logo" class="h-20 w-20 rounded-xl object-cover border border-slate-200 {{ $institution?->logo_url ? '' : 'hidden' }}">
                    </div>
                </div>
                <div class="md:col-span-2">
                    <button class="w-full md:w-auto h-14 px-8 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition" type="submit">Guardar barra institucional (única vez)</button>
                </div>
            </form>
        @endif
    </div>

    <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8">
        <h1 class="text-3xl font-bold text-slate-900">Administración Electoral</h1>
        <p class="mt-2 text-slate-600">Configura elección, carga candidatos y gestiona el cierre oficial.</p>

        @if(session('status'))
            <div class="mt-4 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-emerald-700">{{ session('status') }}</div>
        @endif

        @if($errors->has('general'))
            <div class="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-red-700">{{ $errors->first('general') }}</div>
        @endif

        @if($errors->any() && !$errors->has('general'))
            <div class="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-red-700">{{ $errors->first() }}</div>
        @endif
    </div>

    <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8">
        <h3 class="text-xl font-bold text-slate-900">Crear nueva elección</h3>
        <p class="mt-1 text-slate-600">Solo disponible cuando no exista una elección activa. El historial se conserva automáticamente.</p>
        <form method="POST" action="{{ route('admin.elections.store') }}" class="mt-5 grid grid-cols-1 md:grid-cols-2 gap-4">
            @csrf
            <div class="md:col-span-2">
                <label class="block text-sm font-semibold text-slate-700 mb-2">Nombre elección</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="text" name="name" required>
            </div>

            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Inicio registro candidatos</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="datetime-local" name="candidate_upload_starts_at" required>
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Fin registro candidatos</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="datetime-local" name="candidate_upload_ends_at" required>
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Fin votación</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="datetime-local" name="ends_at" required>
            </div>

            <div class="md:col-span-2">
                <button class="w-full md:w-auto h-14 px-8 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition" type="submit">Crear elección</button>
            </div>
        </form>
    </div>

    <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8 overflow-x-auto">
        <h3 class="text-xl font-bold text-slate-900">Historial de elecciones</h3>
        <table class="min-w-full text-sm mt-4">
            <thead class="text-left text-slate-500 border-b border-slate-200">
                <tr>
                    <th class="py-2 pr-3">ID</th>
                    <th class="py-2 pr-3">Nombre</th>
                    <th class="py-2 pr-3">Estado</th>
                    <th class="py-2 pr-3">Inicio</th>
                    <th class="py-2 pr-3">Fin</th>
                </tr>
            </thead>
            <tbody>
            @forelse($electionsHistory as $historyElection)
                <tr class="border-b border-slate-100">
                    <td class="py-2 pr-3">{{ $historyElection->id }}</td>
                    <td class="py-2 pr-3">{{ $historyElection->name }}</td>
                    <td class="py-2 pr-3">{{ $historyElection->is_active ? 'Activa' : 'Cerrada' }}</td>
                    <td class="py-2 pr-3">{{ $historyElection->voting_started_at ?? 'No iniciada' }}</td>
                    <td class="py-2 pr-3">{{ $historyElection->ends_at }}</td>
                </tr>
            @empty
                <tr><td colspan="5" class="py-3 text-slate-500">No hay elecciones registradas.</td></tr>
            @endforelse
            </tbody>
        </table>
    </div>

    <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8">
        <h3 class="text-xl font-bold text-slate-900">Crear jurados</h3>
        <p class="mt-1 text-slate-600">El administrador crea las cuentas de jurado para acceso al panel de seguimiento.</p>
        <form method="POST" action="{{ route('admin.juries.store') }}" class="mt-5 grid grid-cols-1 md:grid-cols-2 gap-4">
            @csrf
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Nombre completo</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="text" name="jury_name" required>
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Correo</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="email" name="jury_email" required>
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Contraseña</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="password" name="jury_password" required>
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Confirmar contraseña</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="password" name="jury_password_confirmation" required>
            </div>
            <div class="md:col-span-2">
                <button class="w-full md:w-auto h-14 px-8 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition" type="submit">Crear jurado</button>
            </div>
        </form>

        <div class="mt-6">
            <h4 class="font-semibold text-slate-800 mb-2">Jurados registrados</h4>
            <ul class="list-disc ml-5 text-slate-700 text-sm space-y-1">
                @forelse($juries as $jury)
                    <li>{{ $jury->name }} ({{ $jury->email }})</li>
                @empty
                    <li>No hay jurados creados.</li>
                @endforelse
            </ul>
        </div>
    </div>

    <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8">
        <h3 class="text-xl font-bold text-slate-900">Importar estudiantes por CSV</h3>
        <p class="mt-1 text-slate-600">Carga masiva de estudiantes habilitados para votar.</p>

        <form method="POST" action="{{ route('admin.students.import') }}" enctype="multipart/form-data" class="mt-5 space-y-4">
            @csrf
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Archivo CSV</label>
                <input class="w-full rounded-xl border border-slate-300 px-4 py-3 bg-white" type="file" name="students_csv" required>
            </div>
            <div class="flex flex-wrap gap-3">
                <button class="w-full md:w-auto h-14 px-8 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition" type="submit">Importar estudiantes</button>
                <a class="inline-flex items-center justify-center w-full md:w-auto h-14 px-8 rounded-2xl bg-slate-200 text-slate-800 font-semibold hover:bg-slate-300 transition" href="{{ route('admin.students.template') }}">Descargar plantilla CSV</a>
            </div>
        </form>

        <div class="mt-6 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-700">
            <p class="font-semibold text-slate-900">Estructura obligatoria del CSV (encabezados exactos):</p>
            <ul class="list-disc ml-5 mt-2 space-y-1">
                <li><span class="font-semibold">full_name</span>: nombre completo del estudiante (texto).</li>
                <li><span class="font-semibold">grade_level</span>: grado numérico entre 1 y 11.</li>
                <li><span class="font-semibold">login_code</span>: código único de acceso del estudiante (sin repetir).</li>
                <li><span class="font-semibold">pin</span>: clave de votación del estudiante en texto (el sistema la cifra).</li>
                <li><span class="font-semibold">login_pin_hash</span>: hash ya calculado del PIN (bcrypt/argon). Puedes usar esta columna en lugar de <span class="font-semibold">pin</span>.</li>
            </ul>
            <p class="mt-3 font-semibold text-slate-900">Columna opcional:</p>
            <ul class="list-disc ml-5 mt-1 space-y-1">
                <li><span class="font-semibold">document_number</span>: documento/identificación (opcional).</li>
            </ul>
            <p class="mt-3 font-semibold text-slate-900">Ejemplo de CSV:</p>
            <pre class="mt-2 bg-white border border-slate-200 rounded-lg p-3 overflow-x-auto">full_name,grade_level,login_code,pin,login_pin_hash,document_number
Sofia Diaz,5,STU5001,1234,,10203040
Mateo Perez,11,STU1102,,$2y$10$hashEjemploYaCalculado...,99887766</pre>
            <p class="mt-3">Notas:</p>
            <ul class="list-disc ml-5 mt-1 space-y-1">
                <li>Guardar el archivo en formato CSV UTF-8.</li>
                <li>Si un <span class="font-semibold">login_code</span> ya existe, el estudiante se actualiza.</li>
                <li>En cada fila debes enviar <span class="font-semibold">pin</span> o <span class="font-semibold">login_pin_hash</span>.</li>
                <li>La importación reinicia estado de voto del estudiante importado (<span class="font-semibold">has_voted = false</span>).</li>
            </ul>
        </div>
    </div>

    @if(!$election)
        <div class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-amber-700">No hay elección configurada.</div>
    @else
        <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8 space-y-4">
            <p><span class="font-semibold">Elección:</span> {{ $election->name }}</p>
            <p><span class="font-semibold">Estado:</span> {{ $election->is_active ? ($election->voting_started_at ? 'Votación en curso' : 'Preparada (sin iniciar)') : 'Cerrada' }}</p>
            <p><span class="font-semibold">Ventana registro candidatos:</span> {{ $election->candidate_upload_starts_at }} a {{ $election->candidate_upload_ends_at }}</p>
            <p><span class="font-semibold">Inicio real votación:</span> {{ $election->voting_started_at ?? 'Pendiente (presiona Iniciar votación)' }}</p>

            @if($election->is_active)
                <div class="rounded-xl border border-slate-200 bg-slate-50 p-5">
                    <h3 class="text-xl font-bold text-slate-900">Registrar candidato</h3>
                    <p class="mt-1 text-slate-600">Disponible en el rango de fechas permitido.</p>
                    <form method="POST" action="{{ route('admin.candidates.store') }}" enctype="multipart/form-data" class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                        @csrf
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Rol</label>
                            <select class="w-full rounded-xl border border-slate-300 px-4 py-3" name="role" required>
                                <option value="personero">Personero</option>
                                <option value="contralor">Contralor</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Número</label>
                            <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="number" name="display_number" min="1" max="99" required>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Nombre completo</label>
                            <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="text" name="full_name" required>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Grado</label>
                            <select class="w-full rounded-xl border border-slate-300 px-4 py-3" name="grade_id" required>
                                @foreach($grades as $grade)
                                    <option value="{{ $grade->id }}">{{ $grade->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Foto (cualquier extensión/nombre)</label>
                            <input id="candidate_photo_input" class="w-full rounded-xl border border-slate-300 px-4 py-3 bg-white" type="file" name="photo" required>
                            <div class="mt-3">
                                <img id="candidate_photo_preview" alt="Preview candidato" class="h-28 w-28 rounded-xl object-cover border border-slate-200 hidden">
                                <p id="candidate_photo_text" class="text-xs text-slate-500 hidden">Archivo seleccionado</p>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Propuesta (opcional)</label>
                            <input class="w-full rounded-xl border border-slate-300 px-4 py-3" type="text" name="proposal">
                        </div>
                        <div class="md:col-span-2">
                            <button class="w-full md:w-auto h-14 px-8 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition" type="submit">Guardar candidato</button>
                        </div>
                    </form>
                </div>
            @endif

            <div class="flex flex-wrap gap-3">
                <a class="inline-flex items-center justify-center h-14 px-7 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition" href="{{ route('admin.dashboard.pdf') }}">Descargar acta PDF</a>
                @if($election->is_active && !$election->voting_started_at)
                <form method="POST" action="{{ route('admin.election.start') }}">
                    @csrf
                    <button class="h-14 px-7 rounded-2xl bg-emerald-600 text-white font-semibold hover:bg-emerald-700 transition" type="submit">Iniciar votación</button>
                </form>
                @endif
                @if($election->is_active)
                <form method="POST" action="{{ route('admin.election.close') }}">
                    @csrf
                    <button class="h-14 px-7 rounded-2xl bg-red-600 text-white font-semibold hover:bg-red-700 transition" type="submit">Cerrar elección oficialmente</button>
                </form>
                @endif
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
            <div class="bg-white rounded-2xl border border-slate-200 p-5"><p class="text-sm text-slate-500">Total tarjetones</p><p class="text-2xl font-bold">{{ $totalBallots }}</p></div>
            <div class="bg-white rounded-2xl border border-slate-200 p-5"><p class="text-sm text-slate-500">Habilitados para votar</p><p class="text-2xl font-bold">{{ $eligibleVoters }}</p></div>
            <div class="bg-white rounded-2xl border border-slate-200 p-5"><p class="text-sm text-slate-500">Participación</p><p class="text-2xl font-bold">{{ $turnoutPercent }}%</p></div>
            <div class="bg-white rounded-2xl border border-slate-200 p-5"><p class="text-sm text-slate-500">Certificados emitidos</p><p class="text-2xl font-bold">{{ $receiptsCount }}</p></div>
        </div>

        @if($revealWinners)
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-emerald-700">
                Ganador Personero: {{ $personeroWinner?->full_name ?? 'N/A' }} | Ganador Contralor: {{ $contralorWinner?->full_name ?? 'N/A' }}
            </div>
        @else
            <div class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-amber-700">El ganador solo se declara cuando la elección esté cerrada oficialmente.</div>
        @endif

        <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 overflow-x-auto">
            <h3 class="text-xl font-bold mb-4">Resultados Personero</h3>
            <table class="min-w-full text-sm">
                <thead class="text-left text-slate-500 border-b border-slate-200"><tr><th class="py-2 pr-3">Candidato</th><th class="py-2 pr-3">Votos</th><th class="py-2">% sobre tarjetones</th></tr></thead>
                <tbody>
                @foreach($personeroResults as $row)
                    <tr class="border-b border-slate-100"><td class="py-2 pr-3">#{{ $row->display_number }} - {{ $row->full_name }}</td><td class="py-2 pr-3">{{ $row->votes_count }}</td><td class="py-2">{{ $row->percent }}%</td></tr>
                @endforeach
                <tr><td class="py-2 pr-3 font-semibold">Voto en blanco</td><td class="py-2 pr-3 font-semibold">{{ $personeroBlank }}</td><td></td></tr>
                </tbody>
            </table>
        </div>

        <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 overflow-x-auto">
            <h3 class="text-xl font-bold mb-4">Resultados Contralor</h3>
            <table class="min-w-full text-sm">
                <thead class="text-left text-slate-500 border-b border-slate-200"><tr><th class="py-2 pr-3">Candidato</th><th class="py-2 pr-3">Votos</th><th class="py-2">% sobre tarjetones</th></tr></thead>
                <tbody>
                @foreach($contralorResults as $row)
                    <tr class="border-b border-slate-100"><td class="py-2 pr-3">#{{ $row->display_number }} - {{ $row->full_name }}</td><td class="py-2 pr-3">{{ $row->votes_count }}</td><td class="py-2">{{ $row->percent }}%</td></tr>
                @endforeach
                <tr><td class="py-2 pr-3 font-semibold">Voto en blanco</td><td class="py-2 pr-3 font-semibold">{{ $contralorBlank }}</td><td></td></tr>
                </tbody>
            </table>
        </div>

        <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 overflow-x-auto">
            <h3 class="text-xl font-bold mb-4">Últimos certificados emitidos</h3>
            <table class="min-w-full text-sm">
                <thead class="text-left text-slate-500 border-b border-slate-200"><tr><th class="py-2 pr-3">Código</th><th class="py-2 pr-3">Hora</th><th class="py-2">Validación</th></tr></thead>
                <tbody>
                @foreach($recentReceipts as $receipt)
                    <tr class="border-b border-slate-100">
                        <td class="py-2 pr-3">{{ $receipt->receipt_code }}</td>
                        <td class="py-2 pr-3">{{ $receipt->voted_at }}</td>
                        <td class="py-2"><a class="text-blue-600 hover:text-blue-800" href="{{ route('voting.receipt.verify', $receipt->receipt_code) }}">Verificar</a></td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>
    @endif

    <form method="POST" action="{{ route('admin.logout') }}">
        @csrf
        <button class="w-full md:w-auto h-14 px-8 rounded-2xl bg-slate-700 text-white font-semibold hover:bg-slate-800 transition" type="submit">Cerrar sesión admin</button>
    </form>
</div>

<script>
    (function () {
        const logoInput = document.getElementById('school_logo_input');
        const logoPreview = document.getElementById('school_logo_preview');
        if (logoInput && logoPreview) {
            logoInput.addEventListener('change', function (event) {
                const file = event.target.files && event.target.files[0];
                if (!file) return;
                if (file.type && file.type.startsWith('image/')) {
                    logoPreview.src = URL.createObjectURL(file);
                    logoPreview.classList.remove('hidden');
                }
            });
        }

        const candidateInput = document.getElementById('candidate_photo_input');
        const candidatePreview = document.getElementById('candidate_photo_preview');
        const candidateText = document.getElementById('candidate_photo_text');
        if (candidateInput && candidatePreview && candidateText) {
            candidateInput.addEventListener('change', function (event) {
                const file = event.target.files && event.target.files[0];
                if (!file) return;
                if (file.type && file.type.startsWith('image/')) {
                    candidatePreview.src = URL.createObjectURL(file);
                    candidatePreview.classList.remove('hidden');
                    candidateText.classList.add('hidden');
                } else {
                    candidatePreview.classList.add('hidden');
                    candidateText.textContent = 'Archivo seleccionado: ' + file.name;
                    candidateText.classList.remove('hidden');
                }
            });
        }
    })();
</script>
@endsection
