@extends('layouts.app')

@section('title', 'Registrar Ingreso - Ojo de Águila')
@section('header_title', 'Control de Acceso')

@section('content')
<div class="card" style="max-width: 800px; margin: 0 auto;">
    <div class="card-header">
        <h3 class="card-title">🚪 Registrar y controla los ingresos al recinto</h3>
    </div>
    <div class="card-body">
        
        <!-- Tabs de Tipo de Acceso -->
        <div class="tabs-container">
            <button type="button" class="tab-btn active" id="tab-person" onclick="switchTab('person')">
                👥 Persona a pie
            </button>
            <button type="button" class="tab-btn" id="tab-vehicle" onclick="switchTab('vehicle')">
                🚗 Persona con vehículo
            </button>
            <button type="button" class="tab-btn" id="tab-delivery" onclick="switchTab('delivery')">
                📦 Delivery / Entrega
            </button>
        </div>

        <form action="{{ route('access.store') }}" method="POST" id="access-form">
            @csrf
            
            <input type="hidden" name="access_type" id="access_type" value="person">

            <!-- 1. ESCÁNER DE CÉDULA DE IDENTIDAD CHILENA (CORE) -->
            <div class="scanner-container">
                <h4 class="scanner-title">Escanear Cédula de Identidad</h4>
                <p class="scanner-subtitle">Ingresa el RUT o simula el escaneo con el botón</p>
                
                <div class="scanner-box">
                    <div style="display: flex; gap: 8px; width: 100%; max-width: 400px; margin: 0 auto;">
                        <input type="text" id="scan_rut_input" class="form-control" style="background-color: rgba(255,255,255,0.08); border-color: rgba(255,255,255,0.15); color: #FFFFFF; font-size: 16px; font-weight: 700; text-align: center;" placeholder="12.345.678-9">
                        <button type="button" class="btn btn-primary" id="btn-verify-id" onclick="verifyRUT()">Validar</button>
                    </div>
                </div>

                <div style="display: flex; justify-content: center; gap: 12px; flex-wrap: wrap;">
                    <button type="button" class="btn btn-secondary" style="background-color: rgba(255,255,255,0.05); color: #FFFFFF; border-color: rgba(255,255,255,0.1);" onclick="simulateScanner('12345678-9')">
                        Simular Cédula Carlos
                    </button>
                    <button type="button" class="btn btn-secondary" style="background-color: rgba(255,255,255,0.05); color: #FFFFFF; border-color: rgba(255,255,255,0.1);" onclick="simulateScanner('15654321-K')">
                        Simular Cédula María
                    </button>
                </div>
            </div>

            <!-- 2. INFORMACIÓN DEL VISITANTE (AUTO-COMPLETADA AL ESCANEAR) -->
            <div class="card" style="border-color: var(--border-color); background-color: #F8FAFC; margin-bottom: 24px; display: none;" id="visitor-info-box">
                <div class="card-header" style="padding: 12px 20px; background-color: #FFFFFF; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; justify-content: space-between;">
                    <span style="font-size: 13px; font-weight: 700; color: var(--text-secondary);">Información del visitante</span>
                    <span class="scanner-badge" id="identity-badge">🟢 Identidad verificada</span>
                </div>
                <div class="card-body" style="padding: 20px; display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px;">
                    <div>
                        <label class="form-label">Nombres</label>
                        <input type="text" name="first_name" id="first_name" class="form-control" readonly required>
                    </div>
                    <div>
                        <label class="form-label">Apellidos</label>
                        <input type="text" name="last_name" id="last_name" class="form-control" readonly required>
                    </div>
                    <div>
                        <label class="form-label">RUT</label>
                        <input type="text" name="rut" id="rut" class="form-control" readonly required>
                    </div>
                    <div>
                        <label class="form-label">Nacionalidad</label>
                        <input type="text" name="nationality" id="nationality" class="form-control" readonly required>
                        <input type="hidden" name="birth_date" id="birth_date">
                    </div>
                </div>
            </div>

            <!-- 3. CAMPOS ADICIONALES PARA VEHÍCULOS -->
            <div id="vehicle-fields" style="display: none; border-top: 1px solid var(--border-color); padding-top: 20px; margin-bottom: 20px;">
                <h4 style="font-size: 14px; font-weight: 700; margin-bottom: 16px; color: var(--text-primary);">Detalles del Vehículo</h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div class="form-group">
                        <label for="plate" class="form-label required">Patente del Vehículo</label>
                        <input type="text" name="plate" id="plate" class="form-control" placeholder="AB-CD-12" style="text-transform: uppercase;">
                    </div>
                    <div class="form-group">
                        <label for="parking_space_id" class="form-label required">Estacionamiento Asignado</label>
                        <select name="parking_space_id" id="parking_space_id" class="form-control">
                            <option value="">-- Seleccionar espacio --</option>
                            @foreach($parkingSpaces as $space)
                                <option value="{{ $space->id }}">{{ $space->number }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>

            <!-- 4. CAMPOS ADICIONALES PARA DELIVERY -->
            <div id="delivery-fields" style="display: none; border-top: 1px solid var(--border-color); padding-top: 20px; margin-bottom: 20px;">
                <h4 style="font-size: 14px; font-weight: 700; margin-bottom: 16px; color: var(--text-primary);">Detalles de la Entrega</h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
                    <div class="form-group">
                        <label for="delivery_company" class="form-label required">Empresa repartidora</label>
                        <input type="text" name="delivery_company" id="delivery_company" class="form-control" placeholder="PedidosYa, Rappi, Chilexpress...">
                    </div>
                    <div class="form-group">
                        <label for="delivery_recipient" class="form-label">Destinatario (Residente / Oficina)</label>
                        <input type="text" name="delivery_recipient" id="delivery_recipient" class="form-control" placeholder="Nombre o Depto">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="delivery_point" class="form-label required">Punto de Entrega / Destino</label>
                    <select name="delivery_point" id="delivery_point" class="form-control">
                        <option value="recepcion">Recepción / Conserjería</option>
                        <option value="casillero">Casillero de entregas</option>
                        <option value="puerta">Puerta directa</option>
                    </select>
                </div>

                <!-- Simulación escáner QR -->
                <div class="form-group" style="background-color: #F8FAFC; border: 1px solid var(--border-color); padding: 16px; border-radius: var(--radius-md);">
                    <label class="form-label" style="display: flex; align-items: center; gap: 8px;">📷 Escáner de QR (Factura / Guía)</label>
                    <div style="display: flex; gap: 8px; margin-top: 8px;">
                        <input type="text" name="qr_url" id="qr_url" class="form-control" placeholder="URL de la factura escaneada..." style="font-size: 12px;">
                        <button type="button" class="btn btn-secondary" onclick="simulateQRScan()" style="font-size: 12px; white-space: nowrap;">Simular QR</button>
                    </div>
                </div>
            </div>

            <!-- 5. DETALLES DE ACCESO COMUNES -->
            <div style="border-top: 1px solid var(--border-color); padding-top: 20px; margin-bottom: 24px;">
                <h4 style="font-size: 14px; font-weight: 700; margin-bottom: 16px; color: var(--text-primary);">Detalles de Acceso</h4>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
                    <div class="form-group">
                        <label for="zone_id" class="form-label required">Destino dentro del recinto</label>
                        <select name="zone_id" id="zone_id" class="form-control" required>
                            <option value="">-- Seleccionar destino --</option>
                            @foreach($zones as $zone)
                                <option value="{{ $zone->id }}">{{ $zone->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="access_point_id" class="form-label required">Acceso / Puerta de Ingreso</label>
                        <select name="access_point_id" id="access_point_id" class="form-control" required>
                            @foreach($accessPoints as $ap)
                                <option value="{{ $ap->id }}">{{ $ap->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label for="accompanied_by" class="form-label">Acompañado por (opcional)</label>
                    <input type="text" name="accompanied_by" id="accompanied_by" class="form-control" placeholder="Ej: 2 personas adicionales, menores, etc.">
                </div>

                <div class="form-group">
                    <label for="observations" class="form-label">Observaciones (opcional)</label>
                    <textarea name="observations" id="observations" class="form-control" rows="3" placeholder="Ingresa alguna observación..."></textarea>
                </div>
            </div>

            <!-- Submit -->
            <button type="submit" class="btn btn-primary btn-full" style="height: 48px; font-size: 15px;" id="submit-btn" disabled>
                🛡️ Registrar Ingreso
            </button>
        </form>
    </div>
</div>

<script>
    function switchTab(type) {
        // Actualizar input hidden
        document.getElementById('access_type').value = type;

        // Modificar clases activas en botones de tabs
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.getElementById('tab-' + type).classList.add('active');

        // Mostrar / Ocultar secciones de campos específicos
        if (type === 'vehicle') {
            document.getElementById('vehicle-fields').style.display = 'block';
            document.getElementById('delivery-fields').style.display = 'none';
            document.getElementById('plate').required = true;
            document.getElementById('parking_space_id').required = true;
            document.getElementById('delivery_company').required = false;
        } else if (type === 'delivery') {
            document.getElementById('vehicle-fields').style.display = 'none';
            document.getElementById('delivery-fields').style.display = 'block';
            document.getElementById('plate').required = false;
            document.getElementById('parking_space_id').required = false;
            document.getElementById('delivery_company').required = true;
        } else {
            document.getElementById('vehicle-fields').style.display = 'none';
            document.getElementById('delivery-fields').style.display = 'none';
            document.getElementById('plate').required = false;
            document.getElementById('parking_space_id').required = false;
            document.getElementById('delivery_company').required = false;
        }
    }

    function simulateScanner(rut) {
        document.getElementById('scan_rut_input').value = rut;
        verifyRUT();
    }

    function verifyRUT() {
        const rutInput = document.getElementById('scan_rut_input').value;
        if (!rutInput) {
            alert('Por favor ingresa un RUT.');
            return;
        }

        fetch('/api/identity/verify?rut=' + encodeURIComponent(rutInput))
            .then(res => {
                if (!res.ok) throw new Error('Error al validar la identidad');
                return res.json();
            })
            .then(data => {
                if (data.success) {
                    // Completar campos y mostrar contenedor
                    document.getElementById('first_name').value = data.first_name;
                    document.getElementById('last_name').value = data.last_name;
                    document.getElementById('rut').value = data.rut;
                    document.getElementById('nationality').value = data.nationality;
                    document.getElementById('birth_date').value = data.birth_date;

                    document.getElementById('visitor-info-box').style.display = 'block';
                    document.getElementById('submit-btn').disabled = false;
                }
            })
            .catch(err => {
                alert('Ocurrió un error consultando al Registro Civil. Inténtalo de nuevo.');
                console.error(err);
            });
    }

    function simulateQRScan() {
        // Simular escaneo de URL de boleta/factura del SII de Chile
        const urls = [
            'https://www.sii.cl/consulta_boleta?folio=485728&monto=15400',
            'https://back.sii.cl/factura_electronica?rut_emisor=76123456-7&folio=998822',
            'https://www.sii.cl/boleta_electronica?token=a8f7c9e0d1f3b5a7'
        ];
        const randomUrl = urls[Math.floor(Math.random() * urls.length)];
        document.getElementById('qr_url').value = randomUrl;
    }
</script>
@endsection
