<?php require __DIR__ . '/../../includes/navBar.php'; ?>
<?php require __DIR__ . '/../../includes/modal.php'; ?>

<?php
    // Datos desde back end (si existen)

    $venta = $_SESSION['venta_extra'] ?? [];

    $condIva = $venta['cond_iva'] ?? 'consumidor_final';
    $cuit = $venta['cuit'] ?? '';
    $formaPago = $venta['forma_pago'] ?? 'efectivo';
    $tipoPago = $venta['tipo_pago']  ?? 'pago_unico';
    $descuentoIngresado = $venta['descuento'] ?? 0;
    $recargoIngresado = $venta['recargo'] ?? 0;
?>

<div class="container my-5">

    <div class="card card-rounded card-shadow border-0 card-viewport">

        <!-- HEADER -->

        <div class="card-header header-dark px-4 py-3">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">

                <h4 class="mb-0 title-shadow">
                    <i class="fas fa-receipt icon-xl me-2"></i>
                    Resumen de Venta
                </h4>

                <a href="?opt=crear_venta" class="btn btn-soft-secondary text-white">
                    <i class="fas fa-arrow-left me-1"></i>
                    Volver
                </a>

            </div>
        </div>

        <!-- BODY -->

        <form id="form_crear_venta" method='POST' action="index.php?opt=guardar_datos_venta" novalidate>

            <!-- CAMPO OCULTO (para verificación de token) -->

            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

            <div class="card-body p-4 d-flex flex-column card-body-scroll">

                <!-- CLIENTE -->

                <div class="mb-4 flex-shrink-0">

                    <h6 class="text-muted mb-2">Datos Del Cliente</h6>

                    <div class="row g-3">
                        
                        <!-- NOMBRE Y APELLIDO -->

                        <div class="col-md-3">
                            <label class="label-formventa">Nombre y Apellido</label>
                            <input class="form-control campo-readonly" readonly
                                value="<?= htmlspecialchars($cliente['nombre'] . ' ' . $cliente['apellido']) ?? '' ?>">
                        </div>

                        <!-- TELÉFONO -->

                        <div class="col-md-3">
                            <label class="label-formventa">Teléfono Cliente</label>
                            <input class="form-control campo-readonly" readonly
                                value="<?= htmlspecialchars($cliente['telefono'] ?? '') ?>">
                        </div>

                        <!-- COND. IVA -->

                        <div class="col-md-3">
                            <label class="label-formventa">Cond. IVA</label>
                            <select class="form-select form-select-sm" name="cond_iva" id="condIva">
                                <option value="consumidor_final" <?= $condIva === 'consumidor_final' ? 'selected' : '' ?>>
                                    Consumidor Final
                                </option>
                                <option value="responsable_inscripto" <?= $condIva === 'responsable_inscripto' ? 'selected' : '' ?>>
                                    Responsable Inscripto
                                </option>
                                <option value="monotributo" <?= $condIva === 'monotributo' ? 'selected' : '' ?>>
                                    Monotributo
                                </option>
                            </select>
                        </div>
                        
                        <!-- CUIT -->

                        <div class="col-md-3">
                            <label class="form-label">CUIT</label>

                            <div class="d-flex gap-2">
                                
                                <input type="text" name="cuit_1" maxlength="2" class="form-control text-center"
                                    data-bs-toggle="tooltip"
                                    title="Tipo de persona"
                                    value="<?= substr($cuit ?? '', 0, 2) ?>">

                                <input type="text" name="cuit_2" maxlength="8" class="form-control text-center"
                                    data-bs-toggle="tooltip"
                                    title="DNI"
                                    value="<?= substr($cuit ?? '', 2, 8) ?>">

                                <input type="text" name="cuit_3" maxlength="1" class="form-control text-center"
                                    data-bs-toggle="tooltip"
                                    title="Dígito verificador"
                                    value="<?= substr($cuit ?? '', 10, 1) ?>">
                            </div>
                        </div>

                    </div>
                </div>

                <!-- PRODUCTOS -->

                <h6 class="text-muted mb-2">Productos</h6>

                <div class="table-scroll my-3">

                    <table class="table table-fixed table-hover align-middle mb-0 table-resumen-venta">
                        <thead class="table-dark">
                            <tr>
                                <th>Producto</th>
                                <th class="text-end">Precio Unit. Fin.</th>
                                <th class="text-end">Descuento (%)</th>
                                <th class="text-end">Cantidad</th>
                                <th class="text-end">Subtotal</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php foreach ($productos as $p): ?>
                                <tr>
                                    <td>
                                        <?= htmlspecialchars($p['marca'] . ' ' . $p['modelo']) ?>
                                    </td>
                                    <td class="text-end">
                                        $ <?= number_format($p['precio_final'], 2) ?>
                                    </td>
                                    <td class="text-end">
                                        <?= htmlspecialchars($p['descuento_total']) ?> %
                                    </td>
                                    <td class="text-end">
                                        <?= $p['cantidad'] ?>
                                    </td>
                                    <td class="text-end">
                                        $ <?= number_format($p['precio_final'] * $p['cantidad'], 2) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                </div>

                <!-- DATOS DE PAGO -->

                <div class="flex-shrink-0 mt-0">

                    <h6 class="text-muted mb-2">Datos De Pago</h6>

                    <div class="row g-3">

                        <!-- FORMA DE PAGO -->

                        <div class="col-md-3">
                            <label class="label-formventa">Forma de pago</label>
                            <select class="form-select form-select-sm" name="forma_pago" id="formaPago">
                                <option value="efectivo" <?= $formaPago === 'efectivo' ? 'selected' : '' ?>>Efectivo</option>
                                <option value="transferencia" <?= $formaPago === 'transferencia' ? 'selected' : '' ?>>Transferencia</option>
                                <option value="debito" <?= $formaPago === 'debito' ? 'selected' : '' ?>>Débito</option>
                                <option value="credito" <?= $formaPago === 'credito' ? 'selected' : '' ?>>Crédito</option>
                                <option value="echeq" <?= $formaPago === 'echeq' ? 'selected' : '' ?>>Echeq</option>
                            </select>
                        </div>

                        <!-- TIPO DE PAGO -->

                        <div class="col-md-3">
                            <label class="label-formventa">Tipo de pago</label>
                            <select class="form-select form-select-sm" name="tipo_pago" id="tipoPago">
                                <option value="pago_unico" <?= $tipoPago === 'pago_unico' ? 'selected' : '' ?>>Pago Único</option>
                                <option value="3_cuotas" <?= $tipoPago === '3_cuotas' ? 'selected' : '' ?>>3 Cuotas</option>
                                <option value="6_cuotas" <?= $tipoPago === '6_cuotas' ? 'selected' : '' ?>>6 Cuotas</option>
                                <option value="12_cuotas" <?= $tipoPago === '12_cuotas' ? 'selected' : '' ?>>12 Cuotas</option>
                            </select>
                        </div>

                        <!-- DESCUENTO -->

                        <div class="col-md-3">
                            <label class="label-formventa">Descuento (%)</label>
                            <div class="input-porcentaje">
                                <input
                                    type="number"
                                    name="descuento"
                                    id="descuentoPago"
                                    value="<?= number_format($descuentoIngresado ?? 0, 2, '.', '') ?>"
                                    min="0"
                                    step="0.01"
                                    class="form-control form-control-sm text-end"
                                >
                                <span class="input-group-text">%</span>
                            </div>
                        </div>

                        <!-- RECARGO -->

                        <div class="col-md-3">
                            <label class="label-formventa">Recargo (%)</label>
                            <div class="input-porcentaje">
                                <input
                                    type="number"
                                    name="recargo"
                                    id="recargoPago"
                                    value="<?= number_format($recargoIngresado ?? 0, 2, '.', '') ?>"
                                    min="0"
                                    step="0.01"
                                    class="form-control form-control-sm text-end"
                                >
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- TOTALES -->

                <div class="flex-shrink-0 mt-3">

                    <div class="d-flex align-items-center gap-2 mb-2">
                        <h6 class="text-muted mb-0">Totales</h6>
                    </div>

                    <div class="row g-3">

                        <!-- SUBTOTAL -->

                        <div class="col-md-3">
                            <label class="label-formventa">Subtotal</label>
                            <input class="form-control campo-readonly" readonly
                                value="$ <?= number_format($subtotal, 2) ?>">
                        </div>

                        <!-- DESCUENTO TOTAL -->

                        <div class="col-md-3">
                            <label class="label-formventa">Descuento</label>
                            <input class="form-control campo-readonly" readonly
                                value="$ <?= number_format($descuento, 2) ?>">
                        </div>

                        <!-- RECARGO TOTAL -->

                        <div class="col-md-3">
                            <label class="label-formventa">Recargo</label>
                            <input class="form-control campo-readonly" readonly
                                value="$ <?= number_format($recargo, 2) ?>">
                        </div>

                        <!-- TOTAL -->

                        <div class="col-md-3">
                            <label class="label-formventa fw-semibold">Total</label>
                            <input class="form-control campo-readonly fw-semibold" readonly
                                value="$ <?= number_format($total, 2) ?>">
                        </div>
                    </div>
                    
                </div>

                <!-- ACCIONES -->

                <div class="mt-4 pt- d-flex justify-content-between align-items-center flex-wrap gap-3">

                    <!-- ACCIÓN SECUNDARIA (BORRADOR) -->
                    
                    <button 
                        type="submit" 
                        class="btn btn-soft-secondary text-white py-2"
                        data-bs-toggle="tooltip"
                        data-bs-placement="top"
                        title="Guarda la venta sin confirmarla para continuar más tarde">
                        
                        <i class="fas fa-save me-1"></i>
                        Guardar como borrador
                    </button>

                    <!-- ACCIONES PRINCIPALES -->
                     
                    <div class="d-flex gap-2">

                        <button
                            type="submit"
                            formaction="index.php?opt=confirmar_venta"
                            formmethod="POST"
                            class="btn btn-primary py-2">
                            <i class="fas fa-check me-1"></i>
                            Confirmar venta
                        </button>

                    </div>
                </div>

                <!-- Errores provenientes de ventaController -->

                <!-- ERROR -->

                <script>
                    const serverErrors = <?php 
                        if (!empty($_SESSION['flash_error'])) {
                            $errorsArray = explode('<br>', $_SESSION['flash_error']);
                            unset($_SESSION['flash_error']);
                            echo json_encode($errorsArray);
                        } else {
                            echo '[]';
                        }
                    ?>;
                </script>

                <!-- SUCCES -->

                <script>
                    const serverSuccess = <?php
                        if (!empty($_SESSION['flash_success'])) {
                            $successArray = explode('<br>', $_SESSION['flash_success']);
                            unset($_SESSION['flash_success']);
                            echo json_encode($successArray);
                        } else {
                            echo '[]';
                        }
                    ?>;
                </script>

                <!-- MODAL -->

                <script src="js/globalModal.js"></script>

            </div>
        </form>
    </div>
</div>

<!-- Validar mediante js -->

<script src="js/ventas/ventaValidator.js"></script>

<!-- LÓGICA DE FORMA DE PAGOS -->

<script>
    document.addEventListener("DOMContentLoaded", () => {

        const formaPago = document.getElementById("formaPago");
        const tipoPago = document.getElementById("tipoPago");
        const recargoPago = document.getElementById("recargoPago");

        const reglasPago = {
            efectivo: ['pago_unico'],
            transferencia: ['pago_unico'],
            echeq: ['pago_unico'],
            debito: ['pago_unico'],
            credito: ['pago_unico', '3_cuotas', '6_cuotas', '12_cuotas']
        };

        function actualizarTipoPago() {

            const forma = formaPago.value;
            const permitidos = reglasPago[forma] ?? ['pago_unico'];

            Array.from(tipoPago.options).forEach(opt => {
                opt.disabled = !permitidos.includes(opt.value);
            });

            // Si el valor actual no está permitido, forzamos uno válido

            if (!permitidos.includes(tipoPago.value)) {
                tipoPago.value = permitidos[0];
            }
        }

        // Eventos

        formaPago.addEventListener("change", actualizarTipoPago);

        // Init

        actualizarTipoPago();
    });
</script>

<!-- Evita que Chrome use BFCache -->

<script>
    window.onpageshow = function(event) {
        if (event.persisted) {
            window.location.reload();
        }
    };
</script>

<!-- Tooltip -->

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        tooltipTriggerList.forEach(el => new bootstrap.Tooltip(el));
    });
</script>

<!-- Pasar al siguiente input en CUIT -->

<script>
    document.querySelectorAll("input[name^='cuit_']").forEach((input, index, inputs) => {
        input.addEventListener("input", () => {
            if (input.value.length === input.maxLength && inputs[index + 1]) {
                inputs[index + 1].focus();
            }
        });
    });
</script>