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

<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-clipboard-list icon-xl me-2"></i>
                    Nuevo Pedido
                </h4>

                <div class="d-flex gap-2">

                    <a href="?opt=listar_pedidos" class="btn btn-primary">
                        <i class="fas fa-folder-open me-1"></i>
                        Pedidos Registrados
                    </a>

                    <a href="?opt=crear_proveedor&from=crear_pedido" class="btn btn-success">
                        <i class="fas fa-plus me-1"></i>
                        Nuevo Proveedor
                    </a>

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

            </div>
        </div>

        <!-- BODY -->
         
        <form method='POST' action="index.php?opt=confirmar_pedido" 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">

                <!-- PROVEEDOR -->

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

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="text-muted mb-0">Proveedor</h6>

                        <div class="ms-4 d-flex gap-2">
                            <a href="?opt=seleccionar_proveedor" class="btn btn-primary btn-sm">
                                <i class="fas fa-user fa-fw me-1"></i>
                                Seleccionar Proveedor
                            </a>

                            <button
                                type="submit"
                                formaction="?opt=eliminar_proveedor"
                                formmethod="POST"
                                class="btn btn-danger btn-sm">
                                <i class="fas fa-times fa-fw me-1"></i>
                                Eliminar Proveedor
                            </button>
                        </div>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-2">
                            <label class="label-formventa mb-1">ID</label>
                            <input class="form-control campo-readonly"
                                value="<?= htmlspecialchars($proveedor['id'] ?? '') ?>" readonly>
                        </div>

                        <div class="col-md-2">
                            <label class="label-formventa mb-1">Razón Social</label>
                            <input class="form-control campo-readonly"
                                value="<?= htmlspecialchars($proveedor['razon_social'] ?? '') ?>" readonly>
                        </div>

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

                        <div class="col-md-2">
                            <label class="label-formventa mb-1">Email</label>
                            <input class="form-control campo-readonly"
                                value="<?= htmlspecialchars($proveedor['email'] ?? '') ?>" readonly>
                        </div>

                        <!-- COND. IVA -->

                        <div class="col">
                            <label class="label-formventa mb-1">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-2">
                            <label class="form-label">CUIT</label>

                            <div class="d-flex align-items-center justify-content-center gap-2">

                                <input 
                                    type="text" 
                                    name="cuit_1" 
                                    maxlength="2"
                                    class="form-control text-center"
                                    style="max-width: 50px;"
                                    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 flex-grow-1"
                                    style="max-width: 120px;"
                                    data-bs-toggle="tooltip"
                                    title="DNI"
                                    value="<?= substr($cuit ?? '', 2, 8) ?>">

                                <input 
                                    type="text" 
                                    name="cuit_3" 
                                    maxlength="1"
                                    class="form-control text-center"
                                    style="max-width: 40px;"
                                    data-bs-toggle="tooltip"
                                    title="Dígito verificador"
                                    value="<?= substr($cuit ?? '', 10, 1) ?>">

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

                <!-- LISTADO -->

                <div class="d-flex justify-content-between align-items-center mb-2 flex-shrink-0">
                    <h6 class="text-muted mb-0">Listado de Productos</h6>

                    <div class="ms-4 d-flex gap-2">

                        <button
                            type="submit"
                            formaction="index.php?opt=agregar_producto_pedido"
                            formmethod="POST"
                            class="btn btn-success btn-sm">
                            <i class="fas fa-plus fa-fw me-1"></i>
                            Agregar Producto
                        </button>

                        <button
                            type="button"
                            class="btn btn-danger btn-sm btnConfirmar"
                            title="Vaciar Lista"
                            data-action="vaciar_caja_pedido"
                            data-cuit="<?= htmlspecialchars($cuit) ?>"
                            data-cond_iva="<?= $condIVA ?>"
                            data-mensaje="Todos los productos serán retirados de la lista, ¿estás seguro?"
                            data-titulo="Vaciar Lista"
                            data-bs-toggle="modal"
                            data-bs-target="#modalConfirmacion">

                            <i class="fas fa-times fa-fw me-1"></i>
                            Vaciar Lista
                        </button>

                    </div>
                </div>

                <!-- TABLA -->

                <div class="table-scroll-crear my-2">

                    <table id="tablaProductosPedido" class="table table-fixed table-hover align-middle mb-0 table-resumen-venta">

                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>Producto</th>
                                <th class="text-left">Costo Unit.</th>
                                <th class="text-left">Cantidad</th>
                                <th class="text-left">Precio Unit.</th>
                                <th class="text-left">Stock Final</th>
                                <th class="text-center">Acciones</th>
                            </tr>
                        </thead>

                        <tbody>
                        <?php if (empty($productos)): ?>
                            <tr>
                                <td colspan="7" class="text-center">-</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($productos as $p): ?>
                                <tr>
                                    <!-- ID PRODUCTO -->

                                    <td><?= $p['id_producto'] ?></td>

                                    <!-- MARCA Y MODELO -->

                                    <td>
                                        <?= htmlspecialchars($p['marca'] . ' ' . $p['modelo']) ?>
                                    </td>

                                    <!-- COSTO -->

                                    <td class="text-left">
                                        <div class="input-group input-group-sm input-precio" style="width: 150px;">
                                            <span class="input-group-text">$</span>

                                            <input
                                                type="number"
                                                name="costo[<?= $p['id_producto'] ?>]"
                                                value="<?= number_format($p['costo'], 2, '.', '') ?>"
                                                min="1"
                                                step="0.01"
                                                class="form-control">
                                        </div>
                                    </td>

                                    <!-- CANTIDAD -->

                                    <td class="text-center">
                                        <input type="number"
                                            name="cantidad[<?= $p['id_producto'] ?>]"
                                            value="<?= htmlspecialchars($p['cantidad']) ?>"
                                            min="1"
                                            class="form-control form-control-sm"
                                            style="width: 60px;">
                                    </td>

                                    <!-- PRECIO -->

                                    <td class="text-left">
                                        $ <?= number_format($p['precio'], 2) ?>
                                    </td>

                                    <!-- STOCK FINAL -->

                                    <td class="text-left">
                                        <?= htmlspecialchars($p['stock_final']) ?>
                                    </td>
                                    
                                    <!-- ACCIONES -->

                                    <td class="text-center">
                                        <div class="d-inline-flex gap-2">

                                        <button
                                            type="submit"
                                            name="id_producto"
                                            value="<?= $p['id_producto'] ?>"
                                            formaction="index.php?opt=editar_datos_producto"
                                            formmethod="POST"
                                            class="btn btn-primary btn-sm">
                                            <i class="fas fa-pen fa-fw"></i>
                                        </button>

                                        <button
                                            type="submit"
                                            name="id_producto"
                                            value="<?= $p['id_producto'] ?>"
                                            formaction="?opt=eliminar_producto_pedido"
                                            formmethod="POST"
                                            class="btn btn-danger btn-sm">
                                            <i class="fas fa-times fa-fw"></i>
                                        </button>
                                            
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>

                    </table>
                </div>

                <!-- TOTALES -->

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

                    <h6 class="text-muted mb-3">Datos de Pedido</h6>

                    <div class="row g-3">

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

                        <!-- FECHA -->

                        <div class="col-md-2">
                            <label class="label-formventa">Fecha</label>
                            <input class="form-control campo-readonly form-control-sm" readonly
                                value="<?= date('d/m/Y') ?>">
                        </div>
                        
                    </div>

                    <div class="mt-3 text-end">

                        <button type="submit" class="btn btn-primary py-2">
                            <i class="fas fa-save me-1"></i> Confirmar Pedido
                        </button>
                        
                    </div>

                </div>

                <!-- Errores provenients de pedidoController -->

                <!-- 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/pedidos/pedidoValidator.js"></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>