<?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-wrench icon-xl me-2"></i> 
                    Actualizar Servicio N° <?= htmlspecialchars($idServicio) ?>
                </h4>

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

                    <!-- BOTÓN FANTASMA (mantiene el layout) -->

                    <a class="btn btn-success invisible">
                        <i class="fas fa-plus me-1"></i>
                    </a>

                    <a href="?opt=listar_servicios" 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=actualizar_servicio&id= <?= $idServicio ?>" 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">

                <!-- DETALLE DE LO REALIZADO -->

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

                    <div class="row g-3">

                        <div class="col-md-12">
                            <label class="label-formventa mb-1">Detalle a Realizar</label>
                            <textarea class="form-control" rows="3"
                                data-bs-toggle="tooltip"
                                data-bs-placement="top"
                                title="Detalle del trabajo a realizar en el equipo"
                                name="detalle_realizado"><?= htmlspecialchars($detalleRealizado) ?></textarea>
                        </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 Insumos</h6>

                    <div class="ms-4 d-flex gap-2">
                        <button
                            type="submit"
                            formaction="index.php?opt=agregar_insumo&id=<?= $idServicio ?>"
                            formmethod="POST"
                            class="btn btn-success btn-sm">
                            <i class="fas fa-plus fa-fw me-1"></i>
                            Agregar Insumo
                        </button>

                        <button
                            type="button"
                            class="btn btn-danger btn-sm btnConfirmar"
                            title="Vaciar Lista"
                            data-action="vaciar_caja_servicio"
                            data-id="<?= $idServicio ?>"
                            data-detalle_realizado="<?= htmlspecialchars($detalleRealizado) ?>"
                            data-mano_obra="<?= $manoObra ?>"
                            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="tablaInsumosServicio" 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.</th>
                                <th class="text-left">Cantidad</th>
                                <th class="text-center">Acciones</th>
                            </tr>
                        </thead>

                        <tbody>
                        <?php if (empty($insumos)): ?>
                            <tr>
                                <td colspan="6" class="text-center">-</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($insumos as $i): ?>
                                <tr>

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

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

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

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

                                    <td class="text-center">
                                        <div class="d-inline-flex gap-2">
                                            <button
                                                type="submit"
                                                name="id_producto"
                                                value="<?= $i['id_producto'] ?>"
                                                formaction="index.php?opt=editar_cantidad_insumo&id=<?= $idServicio ?>"
                                                class="btn btn-primary btn-sm">
                                                <i class="fas fa-pen fa-fw"></i>
                                            </button>

                                            <button
                                                type="submit"
                                                name="id_producto"
                                                value="<?= $i['id_producto'] ?>"
                                                formaction="?opt=eliminar_insumo&id=<?= $idServicio ?>"
                                                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">

                    <div class="row g-3 align-items-end">

                        <div class="col-md-3">
                            <label class="label-formventa">Mano de Obra</label>

                            <div class="input-group input-moneda input-group-sm">
                                <span class="input-group-text">$</span>

                                <input class="form-control"
                                    name="mano_obra"
                                    value="<?= $manoObra ?>">

                                <button
                                    type="submit"
                                    formaction="index.php?opt=agregar_mano_obra&id= <?= $idServicio ?>"
                                    formmethod="POST"
                                    class="btn btn-primary">
                                    <i class="fas fa-check"></i>
                                </button>

                            </div>
                        </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">

                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-1 py-1"></i> Actualizar Servicio
                        </button>

                    </div>

                </div>

                <!-- Errores provinientes de servicioController -->

                <!-- 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/servicios/servicioValidator.js"></script>

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

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

<!-- Tooltip -->

<script>
document.addEventListener('DOMContentLoaded', function () {

    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');

    tooltipTriggerList.forEach(el => {

        const tooltip = new bootstrap.Tooltip(el);
        let timeout;

        el.addEventListener('shown.bs.tooltip', () => {
            timeout = setTimeout(() => tooltip.hide(), 2000);
        });

        el.addEventListener('hide.bs.tooltip', () => {
            clearTimeout(timeout);
        });

    });

});
</script>