@extends('partials.layout')

@section('title','Crear cierre de turno')
@section('subtitle','Agregar un nuevo registro en cierres_turno')

@section('back')
    <a class="btn" href="{{ route('cierres_turno.index') }}">← Volver</a>
@endsection

@section('content')
    @if($items->isNotEmpty())
        <div style="width:100%;max-width:720px;margin:0 auto 12px auto;padding:10px 12px;border:1px solid #e2e8f0;border-radius:12px;background:linear-gradient(135deg,#eff6ff,#f8fafc);box-shadow:0 6px 18px rgba(15,23,42,0.08)">
            <div style="display:flex;flex-direction:column;gap:8px">
                <div style="font-size:11px;text-transform:uppercase;letter-spacing:1px;color:#2563eb;font-weight:700">Precios del día</div>
                <div style="overflow-x:auto;width:100%">
                    <table style="width:100%;border-collapse:collapse;background:#fff;border:1px solid #dbeafe;border-radius:12px;overflow:hidden">
                        <thead>
                            <tr style="background:#eff6ff;text-align:left">
                                <th style="padding:6px 8px;font-size:11px;text-transform:uppercase;letter-spacing:.8px;color:#1e3a8a">Tipo</th>
                                <th style="padding:6px 8px;font-size:11px;text-transform:uppercase;letter-spacing:.8px;color:#1e3a8a">TM</th>
                                <th style="padding:6px 8px;font-size:11px;text-transform:uppercase;letter-spacing:.8px;color:#1e3a8a">TT</th>
                                <th style="padding:6px 8px;font-size:11px;text-transform:uppercase;letter-spacing:.8px;color:#1e3a8a">TN</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($items as $item)
                                <tr style="border-top:1px solid #e5eefb">
                                    <td style="padding:6px 8px;font-size:12px;font-weight:700;color:#111827">{{ $item->tipoCombustible->nombre ?? 'N/A' }}</td>
                                    <td style="padding:6px 8px;font-size:12px;color:#111827">{{ number_format($item->precio_turno_manana, 2) }}</td>
                                    <td style="padding:6px 8px;font-size:12px;color:#111827">{{ number_format($item->precio_turno_tarde, 2) }}</td>
                                    <td style="padding:6px 8px;font-size:12px;color:#111827">{{ number_format($item->precio_turno_noche, 2) }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    @else
        <div style="margin-bottom:16px;padding:14px 16px;border:1px dashed #cbd5e1;border-radius:12px;background:#f8fafc;color:#475569">No hay registros de precios disponibles.</div>
    @endif

    <form method="POST" action="{{ route('cierres_turno.store') }}" id="create-cuadre-form">
        @csrf
        <div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px">
            <div style="grid-column:1/-1">
                <label style="display:block;font-weight:700;margin-bottom:6px">Usuario</label>
                <input type="hidden" name="id_usuario" value="{{ old('id_usuario', auth()->id()) }}">
                <input type="text"
                       value="{{ (auth()->user()->nombres ?? auth()->user()->name ?? '') }} {{ auth()->user()->apellidos ?? '' }}"
                       readonly
                       style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc">
            </div>

            <div style="grid-column:1/-1">
                <label style="display:block;font-weight:700;margin-bottom:6px">Fecha</label>
                <input type="date" name="fecha" value="{{ old('fecha', date('Y-m-d')) }}" required style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px">
            </div>

            <div style="grid-column:1/-1">
                <label style="display:block;font-weight:700;margin-bottom:6px">Turno</label>
                <select name="id_turno" required style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px">
                    <option value="">-- Seleccione --</option>
                    @foreach($turnos as $t)
                        <option value="{{ $t->id_turno }}" {{ old('id_turno')==$t->id_turno?'selected':'' }}>
                            {{ $t->turnos }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">Venta Diesel</label>
                <input type="number" step="any" id="venta_diesel"
                       value="{{ old('venta_diesel', $ventasPorCombustible['diesel'] ?? 0) }}"
                       readonly
                       style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc">
            </div>

            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">Venta Premium</label>
                <input type="number" step="any" id="venta_premium"
                       value="{{ old('venta_premium', $ventasPorCombustible['premium'] ?? 0) }}"
                       readonly
                       style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc">
            </div>

            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">Venta Regular</label>
                <input type="number" step="any" id="venta_regular"
                       value="{{ old('venta_regular', $ventasPorCombustible['regular'] ?? 0) }}"
                       readonly
                       style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc">
            </div>

            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">Total ventas (calculado)</label>
                <input type="number" step="any" name="total_ventas" id="total_ventas"
                       value="{{ old('total_ventas', $totalVentasCalculado ?? 0) }}"
                       readonly
                       style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc">
            </div>

            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">EFECTIVO</label>
                <input type="number" step="any" name="efectivo" value="{{ old('efectivo') }}" style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px">
            </div>
            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">CREDITO</label>
                <input type="number" step="any" name="credito" value="{{ old('credito') }}" style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px">
            </div>
            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">VISA</label>
                <input type="number" step="any" name="visa" value="{{ old('visa') }}" style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px">
            </div>
            <div>
                <label style="display:block;font-weight:700;margin-bottom:6px">DESCUENTOS</label>
                <input type="number" step="any" name="descuentos" value="{{ old('descuentos') }}" style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px">
            </div>

            <div style="grid-column:1/-1">
                <label style="display:block;font-weight:700;margin-bottom:6px">DIFERENCIA (calculada)</label>
                <input type="number" step="any" name="diferencia" id="diferencia"
                       value="{{ old('diferencia') }}" readonly
                       style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc;">
            </div>

        </div>

        <div style="margin-top:14px;display:flex;gap:10px;flex-wrap:wrap">
            <button class="btn primary" type="submit">Guardar</button>
            <a class="btn" href="{{ route('cierres_turno.index') }}">Cancelar</a>
        </div>
    </form>

    <div id="confirmar-guardado-modal" aria-hidden="true" style="display:none;position:fixed;inset:0;z-index:50;align-items:center;justify-content:center;padding:16px;background:rgba(15,23,42,0.55);backdrop-filter:blur(2px)">
        <div role="dialog" aria-modal="true" aria-labelledby="confirmar-guardado-title" style="width:min(100%,440px);background:#fff;border-radius:16px;box-shadow:0 24px 80px rgba(15,23,42,0.28);overflow:hidden">
            <div style="padding:18px 20px;border-bottom:1px solid #e2e8f0;background:linear-gradient(135deg,#eff6ff,#ffffff)">
                <h3 id="confirmar-guardado-title" style="margin:0;font-size:18px;color:#0f172a">Confirmar grabación</h3>
            </div>
            <div style="padding:18px 20px;color:#334155;font-size:14px;line-height:1.6">
                <p style="margin:0">¿Deseas grabar el cierre de turno? Esta acción enviará la información registrada al sistema.</p>
            </div>
            <div style="padding:0 20px 20px 20px;display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap">
                <button type="button" id="cancelar-guardado-modal" class="btn">Cancelar</button>
                <button type="button" id="confirmar-guardado-modal-btn" class="btn primary">Sí, grabar</button>
            </div>
        </div>
    </div>

    <script>
        (function () {
            const form = document.getElementById('create-cuadre-form');
            const modal = document.getElementById('confirmar-guardado-modal');
            const confirmarBtn = document.getElementById('confirmar-guardado-modal-btn');
            const cancelarBtn = document.getElementById('cancelar-guardado-modal');
            const totalVentasEl = document.getElementById('total_ventas');
            const efectivoEl = document.querySelector('input[name="efectivo"]');
            const creditoEl = document.querySelector('input[name="credito"]');
            const visaEl = document.querySelector('input[name="visa"]');
            const descuentosEl = document.querySelector('input[name="descuentos"]');
            const diferenciaEl = document.getElementById('diferencia');
            const turnoEl = document.querySelector('select[name="id_turno"]');
            const fechaEl = document.querySelector('input[name="fecha"]');
            const idUsuarioEl = document.querySelector('input[name="id_usuario"]');
            const ventaDieselEl = document.getElementById('venta_diesel');
            const ventaPremiumEl = document.getElementById('venta_premium');
            const ventaRegularEl = document.getElementById('venta_regular');
            let totalDiferencias = 0;
            let puedeEnviar = false;

            function abrirModalConfirmacion() {
                if (!modal) return;
                modal.style.display = 'flex';
                modal.setAttribute('aria-hidden', 'false');
            }

            function cerrarModalConfirmacion() {
                if (!modal) return;
                modal.style.display = 'none';
                modal.setAttribute('aria-hidden', 'true');
            }

            form?.addEventListener('submit', (event) => {
                if (puedeEnviar) {
                    return;
                }

                event.preventDefault();
                abrirModalConfirmacion();
            });

            confirmarBtn?.addEventListener('click', () => {
                if (!form) return;
                puedeEnviar = true;
                form.submit();
            });

            cancelarBtn?.addEventListener('click', cerrarModalConfirmacion);

            modal?.addEventListener('click', (event) => {
                if (event.target === modal) {
                    cerrarModalConfirmacion();
                }
            });

            document.addEventListener('keydown', (event) => {
                if (event.key === 'Escape') {
                    cerrarModalConfirmacion();
                }
            });

            async function cargarResumenVentas() {
                const idTurno = turnoEl?.value;
                const fecha = fechaEl?.value;
                const idUsuario = idUsuarioEl?.value;

                if (!idTurno || !fecha) {
                    if (ventaDieselEl) ventaDieselEl.value = '0.00';
                    if (ventaPremiumEl) ventaPremiumEl.value = '0.00';
                    if (ventaRegularEl) ventaRegularEl.value = '0.00';
                    if (totalVentasEl) totalVentasEl.value = '0.00';
                    calcDiferencia();
                    return;
                }

                const url = `{{ route('cierres_turno.resumen_ventas') }}?id_turno=${encodeURIComponent(idTurno)}&fecha=${encodeURIComponent(fecha)}&id_usuario=${encodeURIComponent(idUsuario ?? '')}`;

                try {
                    const response = await fetch(url, {
                        headers: { 'X-Requested-With': 'XMLHttpRequest' }
                    });

                    if (!response.ok) {
                        throw new Error('No se pudo obtener el resumen de ventas');
                    }

                    const data = await response.json();

                    if (ventaDieselEl) ventaDieselEl.value = Number(data?.combustibles?.diesel ?? 0).toFixed(2);
                    if (ventaPremiumEl) ventaPremiumEl.value = Number(data?.combustibles?.premium ?? 0).toFixed(2);
                    if (ventaRegularEl) ventaRegularEl.value = Number(data?.combustibles?.regular ?? 0).toFixed(2);
                    if (totalVentasEl) totalVentasEl.value = Number(data?.total ?? 0).toFixed(2);
                    totalDiferencias = Number(data?.total_diferencias ?? 0);

                    calcDiferencia();
                } catch (e) {
                    if (ventaDieselEl) ventaDieselEl.value = '0.00';
                    if (ventaPremiumEl) ventaPremiumEl.value = '0.00';
                    if (ventaRegularEl) ventaRegularEl.value = '0.00';
                    if (totalVentasEl) totalVentasEl.value = '0.00';
                    calcDiferencia();
                }
            }

            function num(el) {
                const v = parseFloat(el?.value);
                return Number.isFinite(v) ? v : 0;
            }

            function calcDiferencia() {
                const totalVentas = num(totalVentasEl);
                const efectivo = num(efectivoEl);
                const credito = num(creditoEl);
                const visa = num(visaEl);
                const descuentos = num(descuentosEl);

                const diferencia = totalVentas - (efectivo + credito + visa + descuentos + totalDiferencias);
                if (diferenciaEl) {
                    diferenciaEl.value = diferencia.toFixed(2);
                }
            }

            [efectivoEl, creditoEl, visaEl, descuentosEl].forEach((el) => {
                ['input', 'change'].forEach((evt) => el?.addEventListener(evt, calcDiferencia));
            });

            turnoEl?.addEventListener('change', cargarResumenVentas);

            calcDiferencia();
        })();
    </script>
@endsection
