@extends('layouts.app')

@section('title', 'Daftarkan Wajah Siswa')

@section('content')
<div class="mb-6">
    <a href="{{ route('students.index') }}" class="inline-flex items-center gap-1.5 text-[12.5px] font-medium text-gray-500 hover:text-[#0D2B5E] transition-colors">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg>
        Kembali ke Data Siswa
    </a>
    <h1 class="text-lg font-bold text-[#0D2B5E] mt-3">Registrasi Wajah</h1>
    <p class="text-sm text-gray-500 mt-0.5">Unggah foto wajah siswa untuk didaftarkan ke device face recognition.</p>
</div>

@if(session('warning'))
    <div class="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700">
        {{ session('warning') }}
    </div>
@endif

@if($errors->any())
    <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
        <ul class="list-disc list-inside space-y-0.5">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

@php
    // Fallback biar view ini tetap aman kalau controller belum kirim $currentSchedules
    $currentSchedules = $currentSchedules ?? collect();
@endphp

<div class="grid grid-cols-1 md:grid-cols-3 gap-5">
    {{-- Kartu info siswa --}}
    <div class="md:col-span-1 bg-white rounded-xl border border-black/5 shadow-sm p-5 h-fit">
        <div class="text-[11px] uppercase tracking-wider text-gray-400 font-semibold mb-3">Data Siswa</div>
        <dl class="space-y-3 text-sm">
            <div>
                <dt class="text-gray-400 text-[11.5px]">Nama</dt>
                <dd class="font-medium text-gray-800">{{ $student->namlen }}</dd>
            </div>
            <div>
                <dt class="text-gray-400 text-[11.5px]">NIS</dt>
                <dd class="font-medium text-gray-800">{{ $student->nis }}</dd>
            </div>
            <div>
                <dt class="text-gray-400 text-[11.5px]">Kelas</dt>
                <dd class="font-medium text-gray-800">{{ $student->kel }}</dd>
            </div>
        </dl>
    </div>

    {{-- Form upload --}}
    <div class="md:col-span-2 bg-white rounded-xl border border-black/5 shadow-sm p-6">
        <form action="{{ route('students.face.store', $student->id) }}" method="POST" enctype="multipart/form-data" class="space-y-5">
            @csrf

            <div>
                <label for="photo" class="block text-[12.5px] font-semibold text-gray-700 mb-1.5">
                    Foto Wajah (JPEG, maks 5MB)
                </label>

                <label for="photo" id="drop-label"
                       class="flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-gray-200 hover:border-[#0D2B5E]/30 transition-colors py-10 cursor-pointer bg-gray-50/50">
                    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" class="text-gray-400">
                        <path d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1M12 12V3m0 0L7 8m5-5l5 5"/>
                    </svg>
                    <span class="text-[13px] text-gray-500">
                        <span id="file-name">Klik untuk pilih foto</span>
                    </span>
                </label>

                <input id="photo" name="photo" type="file" accept="image/jpeg" required class="hidden"
                       onchange="document.getElementById('file-name').textContent = this.files[0] ? this.files[0].name : 'Klik untuk pilih foto'">
            </div>

            <div>
                <label class="block text-[12.5px] font-semibold text-gray-700 mb-1.5">
                    Mode Absen <span class="text-red-500">*</span>
                </label>

                <div class="grid grid-cols-2 gap-3">
                    <label class="flex items-start gap-2.5 rounded-lg border border-gray-200 p-3 cursor-pointer has-[:checked]:border-[#0D2B5E] has-[:checked]:bg-[#0D2B5E]/5 transition-colors">
                        <input type="radio" name="only_verify" value="0"
                               {{ old('only_verify', '0') == '0' ? 'checked' : '' }}
                               class="mt-0.5">
                        <span>
                            <span class="block text-[13px] font-medium text-gray-800">Absen + Buka Pintu</span>
                            <span class="block text-[11px] text-gray-400 mt-0.5">Wajah dikenali, pintu otomatis terbuka (default)</span>
                        </span>
                    </label>

                    <label class="flex items-start gap-2.5 rounded-lg border border-gray-200 p-3 cursor-pointer has-[:checked]:border-[#0D2B5E] has-[:checked]:bg-[#0D2B5E]/5 transition-colors">
                        <input type="radio" name="only_verify" value="1"
                               {{ old('only_verify') == '1' ? 'checked' : '' }}
                               class="mt-0.5">
                        <span>
                            <span class="block text-[13px] font-medium text-gray-800">Hanya Absen</span>
                            <span class="block text-[11px] text-gray-400 mt-0.5">Wajah dicatat, pintu TIDAK ikut terbuka</span>
                        </span>
                    </label>
                </div>
                <p class="text-[11px] text-amber-600 mt-1.5">
                    ⚠️ Efek "Hanya Absen" belum 100% terverifikasi di semua device — kalau perilakunya
                    tidak sesuai setelah dicoba, laporkan ke admin sistem.
                </p>
            </div>

            <div>
                <label class="block text-[12.5px] font-semibold text-gray-700 mb-1.5">
                    Daftarkan ke Device &amp; Jadwal <span class="text-red-500">*</span>
                </label>

                @if($devices->isEmpty())
                    <p class="text-[12.5px] text-amber-600">Belum ada device aktif. Tambahkan device dulu di halaman Master Device.</p>
                @else
                    <div class="space-y-3 rounded-lg border border-gray-200 p-3">
                        <label class="flex items-center gap-2 text-[12.5px] font-medium text-gray-500 pb-2 border-b border-gray-100">
                            <input type="checkbox" id="select-all-devices" class="rounded border-gray-300">
                            Pilih Semua ({{ $devices->count() }} device)
                        </label>

                        @foreach($devices as $device)
                            <div class="flex items-center justify-between gap-3 flex-wrap">
                                <label class="flex items-center gap-2 text-[13px] text-gray-700">
                                    <input type="checkbox" name="device_ids[]" value="{{ $device->id }}" class="device-checkbox rounded border-gray-300"
                                           {{ in_array($device->id, old('device_ids', $currentSchedules->keys()->all())) ? 'checked' : '' }}>
                                    {{ $device->name }}
                                    <span class="text-gray-400 text-[11.5px]">({{ $device->ip_address }})</span>
                                </label>

                                @if($device->schedules->isNotEmpty())
                                    <select name="schedules[{{ $device->id }}]" class="text-[12px] rounded-md border-gray-200 py-1.5">
                                        <option value="">Jadwal Default (template 1)</option>
                                        @foreach($device->schedules as $schedule)
                                            <option value="{{ $schedule->id }}"
                                                {{ (old("schedules.$device->id", $currentSchedules[$device->id] ?? null) == $schedule->id) ? 'selected' : '' }}>
                                                {{ $schedule->name }} ({{ $schedule->begin_time->format('H:i') }}-{{ $schedule->end_time->format('H:i') }})
                                            </option>
                                        @endforeach
                                    </select>
                                @else
                                    <span class="text-[11px] text-gray-400">Belum ada jadwal custom</span>
                                @endif
                            </div>
                        @endforeach
                    </div>
                    <p id="device-required-hint" class="text-[11px] text-red-500 mt-1.5 hidden">Pilih minimal 1 device.</p>
                    <p class="text-[11px] text-gray-400 mt-1.5">Kosongkan pilihan jadwal untuk pakai jadwal default (template 1).</p>
                @endif
            </div>

            <div class="flex items-center gap-3 pt-2">
                <button type="submit" id="submit-btn"
                        class="inline-flex items-center gap-2 rounded-lg bg-[#0D2B5E] px-4 py-2.5 text-[13px] font-semibold text-white hover:bg-[#0D2B5E]/90 transition-colors">
                    Daftarkan ke Device
                </button>
                <a href="{{ route('students.index') }}"
                   class="inline-flex items-center gap-2 rounded-lg border border-gray-200 px-4 py-2.5 text-[13px] font-medium text-gray-600 hover:bg-gray-50 transition-colors">
                    Batal
                </a>
            </div>
        </form>
    </div>
</div>

<script>
    document.getElementById('select-all-devices')?.addEventListener('change', function () {
        document.querySelectorAll('.device-checkbox').forEach(cb => cb.checked = this.checked);
    });

    // Validasi ringan di sisi browser: wajib pilih minimal 1 device sebelum submit.
    // Validasi utamanya tetap di server (controller), ini cuma biar user langsung tahu tanpa nunggu reload.
    document.querySelector('form')?.addEventListener('submit', function (e) {
        const checkboxes = document.querySelectorAll('.device-checkbox');
        if (checkboxes.length === 0) return; // gaada device sama sekali, biarin server yg nolak

        const anyChecked = Array.from(checkboxes).some(cb => cb.checked);
        const hint = document.getElementById('device-required-hint');

        if (!anyChecked) {
            e.preventDefault();
            hint?.classList.remove('hidden');
            hint?.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    });
</script>
@endsection