@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')
    <form method="POST" action="{{ route('cierres_turno.store') }}">
        @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>

    <script>
        (function () {
            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;

            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
