<?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-shopping-cart icon-xl me-2"></i>
                    Nueva Venta
                </h4>

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

                    <a href="?opt=listar_ventas" class="btn btn-primary">
                        <i class="fas fa-folder-open me-1"></i>
                        Ventas Registradas
                    </a>

                    <a href="?opt=crear_cliente&from=crear_venta" class="btn btn-success">
                        <i class="fas fa-plus me-1"></i>
                        Nuevo Cliente
                    </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>

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

            <!-- CLIENTE -->

            <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">Cliente</h6>

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

                        <a href="?opt=seleccionar_cliente" class="btn btn-primary btn-sm">
                            <i class="fas fa-user fa-fw me-1"></i>
                            Seleccionar Cliente
                        </a>

                        <form method="POST" action="?opt=eliminar_cliente" class="d-inline">
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

                            <button class="btn btn-danger btn-sm">
                                <i class="fas fa-times fa-fw me-1"></i>
                                Eliminar Cliente
                            </button>
                        </form>

                    </div>
                </div>

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

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

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

                    <div class="col-md-3">
                        <label class="label-formventa mb-1">Email</label>
                        <input class="form-control campo-readonly"
                            value="<?= htmlspecialchars($cliente['email'] ?? '') ?>" readonly>
                    </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">

                    <a href="?opt=agregar_producto" class="btn btn-success btn-sm">
                        <i class="fas fa-plus fa-fw me-1"></i>
                        Agregar Producto
                    </a>

                    <button
                        type="button"
                        class="btn btn-danger btn-sm btnConfirmar"
                        title="Vaciar Lista"
                        data-action="vaciar_caja_venta"
                        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="tablaProductosVenta" 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">Precio Unit. Fin.</th>
                            <th class="text-left">Descuento (%)</th>
                            <th class="text-left">Cantidad</th>
                            <th class="text-center">Acciones</th>
                        </tr>
                    </thead>

                    <tbody>
                    <?php if (empty($productos)): ?>
                        <tr>
                            <td colspan="6" class="text-center">-</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($productos as $p): ?>
                            <tr>
                                <form method="POST" action="index.php?opt=editar_cantidad" novalidate>
                                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                    <input type="hidden" name="id_producto" value="<?= $p['id_producto'] ?>">

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

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

                                    <td>$ <?= number_format($p['precio_final'], 2) ?></td>

                                    <td><?= htmlspecialchars($p['descuento_total']) ?> %</td>

                                    <td>
                                        <input type="number"
                                            name="cantidad"
                                            value="<?= $p['cantidad'] ?>"
                                            min="1"
                                            max="<?= $p['stock'] ?>"
                                            class="form-control form-control-sm"
                                            style="width: 60px;">
                                    </td>

                                    <td class="text-center">
                                        <button type="submit" class="btn btn-primary btn-sm">
                                            <i class="fas fa-pen fa-fw"></i>
                                        </button>

                                        <button
                                            type="submit"
                                            formaction="?opt=eliminar_producto"
                                            class="btn btn-danger btn-sm">
                                            <i class="fas fa-times fa-fw"></i>
                                        </button>
                                    </td>
                                </form>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>

                </table>
            </div>

            <!-- TOTALES -->

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

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

                <div class="row g-3">

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

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

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

                <div class="mt-3 text-end">
                    <a href="?opt=resumen_venta" class="btn btn-primary py-2">
                        Siguiente
                        <i class="fas fa-arrow-right ms-1"></i>
                    </a>
                </div>

            </div>

            <!-- Errores provinientes 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>
    </div>
</div>

<!-- Validar mediante js -->

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