<?php
session_start();

if (!isset($_SESSION['id_usuario'])) {
    header('Location: Login_LG.html?error=Sesion expirada');
    exit;
}
if (($_SESSION['rol'] ?? '') !== 'CAJA') {
    header('Location: home.php?error=sin_permiso');
    exit;
}

// Variables de sesión
$idUsuario    = $_SESSION['id_usuario'] ?? '';
$rol          = $_SESSION['rol'] ?? '';
$nombreCajero = $_SESSION['nombre_cajero'] ?? $idUsuario;

require_once __DIR__ . '/../backend/database/Conexion_SQL_Server.php';

/* =========================
   CARGA DE CATÁLOGOS
========================= */

// EMPLEADOS (para meseros / empleados que eliminan)
$meserosActivos = [];
$sqlMes = "SELECT ID_EMPLEADO, NOMBRE_EMPLEADO, APELLIDO_EMPLEADO
           FROM EMPLEADO
           ORDER BY APELLIDO_EMPLEADO, NOMBRE_EMPLEADO";
$stmtMes = sqlsrv_query($conn, $sqlMes);
if ($stmtMes !== false) {
    while ($r = sqlsrv_fetch_array($stmtMes, SQLSRV_FETCH_ASSOC)) {
        $meserosActivos[] = $r;
    }
}

// POS activos/operativos
$posActivos = [];
$sqlPos = "SELECT CAST(ID_POS AS VARCHAR(10)) AS ID_POS, LOCAL_POS, MARCA_POS, ESTADO_POS
           FROM POS
           WHERE ESTADO_POS IN ('ACTIVO','OPERATIVO')
           ORDER BY ID_POS";
$stmtPos = sqlsrv_query($conn, $sqlPos);
if ($stmtPos !== false) {
    while ($p = sqlsrv_fetch_array($stmtPos, SQLSRV_FETCH_ASSOC)) {
        $p['ID_POS'] = (string)$p['ID_POS'];
        $posActivos[] = $p;
    }
}

// Responsables activos
$responsablesActivos = [];
$sqlResp = "SELECT ID_RESPONSABLE, NOMBRE_RESPONSABLE, CARGO_RESPONSABLE
            FROM RESPONSABLE
            WHERE ESTADO_RESPONSABLE = 'ACTIVO'
            ORDER BY NOMBRE_RESPONSABLE";
$stmtResp = sqlsrv_query($conn, $sqlResp);
if ($stmtResp !== false) {
    while ($r = sqlsrv_fetch_array($stmtResp, SQLSRV_FETCH_ASSOC)) {
        $responsablesActivos[] = $r;
    }
}

// Categorías activas
$categoriasActivas = [];
$sqlCat = "SELECT ID_CATEGORIA
           FROM CATEGORIA_PRODUCTO
           WHERE ESTADO_CATEGORIA = 'ACTIVO'
           ORDER BY ID_CATEGORIA";
$stmtCat = sqlsrv_query($conn, $sqlCat);
if ($stmtCat !== false) {
    while ($c = sqlsrv_fetch_array($stmtCat, SQLSRV_FETCH_ASSOC)) {
        $categoriasActivas[] = $c;
    }
}

// Productos activos (para filtrado front por categoría)
$productosActivos = [];
$sqlProd = "SELECT ID_PRODUCTO, NOMBRE_PRODUCTO, ID_CATEGORIA, PRECIO_PRODUCTO
            FROM PRODUCTO
            WHERE ESTADO_PRODUCTO = 'ACTIVO'
            ORDER BY NOMBRE_PRODUCTO";
$stmtProd = sqlsrv_query($conn, $sqlProd);
if ($stmtProd !== false) {
    while ($pr = sqlsrv_fetch_array($stmtProd, SQLSRV_FETCH_ASSOC)) {
        $pr['ID_PRODUCTO']     = (string)$pr['ID_PRODUCTO'];
        $pr['ID_CATEGORIA']    = (string)$pr['ID_CATEGORIA'];
        $pr['NOMBRE_PRODUCTO'] = (string)$pr['NOMBRE_PRODUCTO'];
        $pr['PRECIO_PRODUCTO'] = (float)$pr['PRECIO_PRODUCTO'];
        $productosActivos[] = $pr;
    }
}

// Motivos de eliminado (según check)
$motivosEliminado = [
    'DEMORO MUCHO',
    'ERROR DEL CLIENTE',
    'CAMBIO DE PARECER EL HUESPED',
    'ERROR MOZO',
    'ERROR COCINA',
    'ERROR BAR',
    'NO LE GUSTO AL HUESPED',
    'CAMBIO COMPROBANTE',
    'PRUEBA',
    'FALTA DE INSUMOS',
];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="color-scheme" content="light dark" />
    <meta name="theme-color" content="#0B0F12" />
    <title>Propinas y Reporte POS</title>

    <!-- Bootstrap / Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Tus estilos -->
    <link rel="stylesheet" href="../css/Estilos_appCaja.css">
</head>
<body>
    <!-- Fondo -->
    <div class="bg-overlay"></div>

    <!-- ===== Header limpio y consistente ===== -->
    <header class="header-lg">
        <!-- Lado izquierdo: usuario -->
        <div class="header-left">
            <div class="header-avatar"><i class="bi bi-person-fill"></i></div>
            <div class="header-user">
            <span class="header-name"><?= htmlspecialchars($nombreCajero, ENT_QUOTES, 'UTF-8'); ?></span>
            <span class="header-role"><?= htmlspecialchars($rol, ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
        </div>

        <!-- Lado derecho: acciones -->
        <div class="header-actions">
            <a href="/Proyecto_Guardiana/frontend/app_View_Caja.php"
            class="btn-hdr btn-hdr--gold">
            <i class="bi bi-table"></i> Ver Listados
            </a>

            <form action="../backend/procesos/seguridad/logout.php" method="post" class="m-0"
                onsubmit="return confirm('¿Deseas cerrar sesión?');">
            <button type="submit" class="btn-hdr btn-hdr--ghost">
                <i class="bi bi-box-arrow-right"></i> Cerrar sesión
            </button>
            </form>
        </div>
    </header>


    <div class="container container-guardiana mt-4">
        <!-- MENSAJES -->
        <?php if(isset($_GET['ok']) || isset($_GET['err'])): ?>
            <div id="msgAlert"
                 class="alert alert-dismissible fade show <?= isset($_GET['ok'])?'alert-success':'alert-danger' ?> shadow"
                 role="alert" aria-live="polite" aria-atomic="true">
                <div class="d-flex align-items-center gap-2">
                    <i class="bi <?= isset($_GET['ok'])?'bi-check-circle-fill':'bi-exclamation-triangle-fill' ?>"></i>
                    <span><?= isset($_GET['ok']) ? htmlspecialchars($_GET['ok']) : htmlspecialchars($_GET['err']) ?></span>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
            </div>
        <?php endif; ?>

        <div class="panel-card">
            <h2 class="h-title mb-2">
                Registros del día
                <span class="subtle">(<?= htmlspecialchars(date('Y-m-d')) ?>)</span>
            </h2>
            <div class="rule-rose"></div>

            <!-- Pestañas -->
            <ul class="nav nav-tabs" id="regTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="pfisico-tab" data-bs-toggle="tab" data-bs-target="#pfisico"
                        type="button" role="tab" aria-controls="pfisico" aria-selected="true">
                        Propina Físico
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="ptarjeta-tab" data-bs-toggle="tab" data-bs-target="#ptarjeta"
                        type="button" role="tab" aria-controls="ptarjeta" aria-selected="false">
                        Propina Tarjeta (POS)
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="rpos-tab" data-bs-toggle="tab" data-bs-target="#rpos" type="button"
                        role="tab" aria-controls="rpos" aria-selected="false">
                        Reporte POS
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="idesc-tab" data-bs-toggle="tab" data-bs-target="#idesc" type="button"
                        role="tab" aria-controls="idesc" aria-selected="false">
                        Informe Descuento
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="icortesia-tab" data-bs-toggle="tab" data-bs-target="#icortesia"
                        type="button" role="tab" aria-controls="icortesia" aria-selected="false">
                        Informe Cortesía
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="inota-tab" data-bs-toggle="tab" data-bs-target="#inota" type="button"
                        role="tab" aria-controls="inota" aria-selected="false">
                        Informe Nota de Crédito
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="igasto-tab" data-bs-toggle="tab" data-bs-target="#igasto"
                        type="button" role="tab" aria-controls="igasto" aria-selected="false">
                        Informe Gasto
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="ielim-tab" data-bs-toggle="tab" data-bs-target="#ielim"
                        type="button" role="tab" aria-controls="ielim" aria-selected="false">
                        Informe Eliminado
                    </button>
                </li>
            </ul>

            <div class="tab-content" id="regTabsContent">
                <!-- TAB 1: Propina Físico -->
                <div class="tab-pane fade show active" id="pfisico" role="tabpanel" aria-labelledby="pfisico-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header">
                            <div class="banner-icon"><i class="bi bi-cash-stack fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Propinas en físico — Meseros</h3>
                                <p class="banner-sub">Registra propinas entregadas en efectivo</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formPropinaFisica"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Prop_Fisico.php"
                                  method="post" class="form-grid cols-2" autocomplete="off" novalidate>
                                <div>
                                    <label for="pf_mesero" class="form-label">Nombre del mesero</label>
                                    <select class="form-select" id="pf_mesero" name="pf_mesero" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($meserosActivos as $m): ?>
                                            <option value="<?= htmlspecialchars($m['ID_EMPLEADO']) ?>">
                                                <?= htmlspecialchars($m['APELLIDO_EMPLEADO'] . ', ' . $m['NOMBRE_EMPLEADO']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label for="pf_monto" class="form-label">Monto de propinas (S/)</label>
                                    <input type="number" step="0.01" min="0" class="form-control" id="pf_monto"
                                           name="pf_monto" placeholder="0.00" required>
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar propina física
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">Consejo: verifica que el mesero esté activo antes de registrar.</div>
                    </section>
                </div>

                <!-- TAB 2: Propina Tarjeta -->
                <div class="tab-pane fade" id="ptarjeta" role="tabpanel" aria-labelledby="ptarjeta-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header" style="background:linear-gradient(90deg,#0b3c5d 0%, #1f2937 100%);">
                            <div class="banner-icon"><i class="bi bi-credit-card-2-front fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Propinas por Tarjeta (POS)</h3>
                                <p class="banner-sub">Calcula automáticamente el 5% de comisión POS</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formPropinaTarjeta"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Prop_Tarjeta.php"
                                  method="post" class="form-grid cols-3" autocomplete="off" novalidate>
                                <div>
                                    <label for="pt_ref" class="form-label">Referencia</label>
                                    <input type="text" class="form-control" id="pt_ref" name="pt_ref" maxlength="10"
                                           placeholder="REF001" required autocomplete="off">
                                </div>
                                <div class="col-span-2">
                                    <label for="pt_mesero" class="form-label">Nombre del mesero</label>
                                    <select class="form-select" id="pt_mesero" name="pt_mesero" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($meserosActivos as $m): ?>
                                            <option value="<?= htmlspecialchars($m['ID_EMPLEADO']) ?>">
                                                <?= htmlspecialchars($m['APELLIDO_EMPLEADO'] . ', ' . $m['NOMBRE_EMPLEADO']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label for="pt_monto" class="form-label">Monto Propina (S/)</label>
                                    <input type="number" step="0.01" min="0" class="form-control" id="pt_monto"
                                           name="pt_monto" placeholder="0.00" required>
                                </div>
                                <div>
                                    <label for="pt_desc" class="form-label">Descuento POS 5% (S/)</label>
                                    <input type="text" class="form-control" id="pt_desc" name="pt_desc" value="0.00" readonly>
                                </div>
                                <div>
                                    <label class="form-label">Neto (S/)</label>
                                    <input type="text" class="form-control" id="pt_neto" value="0.00" readonly>
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar propina tarjeta
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">Tip: el neto se muestra con truncado visual a 2 decimales.</div>
                    </section>
                </div>

                <!-- TAB 3: Reporte POS -->
                <div class="tab-pane fade" id="rpos" role="tabpanel" aria-labelledby="rpos-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header" style="background:linear-gradient(90deg,#0b5d3c 0%, #1f2937 100%);">
                            <div class="banner-icon"><i class="bi bi-receipt fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Reporte POS — Cobros y Monto</h3>
                                <p class="banner-sub">Consolida transacciones por dispositivo POS</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formReportePos"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Reporte_Pos.php"
                                  method="post" class="form-grid cols-3" autocomplete="off" novalidate>
                                <div>
                                    <label for="rp_pos" class="form-label">ID del POS</label>
                                    <select class="form-select" id="rp_pos" name="rp_pos" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($posActivos as $p): ?>
                                            <option value="<?= htmlspecialchars($p['ID_POS']) ?>">
                                                <?= htmlspecialchars($p['ID_POS'].' — '.$p['MARCA_POS'].' — '.$p['LOCAL_POS']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label for="rp_cant" class="form-label">Cantidad de cobros (nº transacciones)</label>
                                    <input type="number" min="0" step="1" class="form-control" id="rp_cant"
                                           name="rp_cant" placeholder="0" required>
                                </div>
                                <div>
                                    <label for="rp_monto" class="form-label">Monto total POS (S/)</label>
                                    <input type="number" min="0" step="0.01" class="form-control" id="rp_monto"
                                           name="rp_monto" placeholder="0.00" required>
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar reporte POS
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">Si un POS está “INACTIVO”, no aparecerá en la lista.</div>
                    </section>
                </div>

                <!-- TAB 4: Informe Descuento -->
                <div class="tab-pane fade" id="idesc" role="tabpanel" aria-labelledby="idesc-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header" style="background:linear-gradient(90deg,#5d0b3c 0%, #1f2937 100%);">
                            <div class="banner-icon"><i class="bi bi-percent fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Informe de Descuento</h3>
                                <p class="banner-sub">Calcula el descuento y registra el total final automáticamente</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formInformeDescuento"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Info_Descuento.php"
                                  method="post" class="form-grid cols-3" autocomplete="off" novalidate>
                                <div>
                                    <label for="id_check" class="form-label">CHECK (código / número)</label>
                                    <input type="number" inputmode="numeric" class="form-control" id="id_check"
                                           name="id_check" placeholder="Ej: 4569" step="1" min="0" max="9999999999" required>
                                </div>
                                <div class="col-span-2">
                                    <label for="id_persona" class="form-label">Nombre de la persona</label>
                                    <input type="text" class="form-control" id="id_persona" name="id_persona"
                                           maxlength="100" placeholder="Cliente / Huésped" required>
                                </div>
                                <div class="col-span-3">
                                    <label for="id_motivo" class="form-label">Motivo del descuento</label>
                                    <input type="text" class="form-control" id="id_motivo" name="id_motivo"
                                           maxlength="500" placeholder="Ej: Promoción del día / Cortesía / Error" required>
                                </div>
                                <div>
                                    <label for="id_monto" class="form-label">Monto base (S/)</label>
                                    <input type="number" step="0.01" min="0" class="form-control" id="id_monto"
                                           name="id_monto" placeholder="0.00" required>
                                </div>
                                <div>
                                    <label for="id_porc" class="form-label">% Descuento</label>
                                    <input type="number" step="0.1" min="0" max="100" class="form-control" id="id_porc"
                                           name="id_porc" placeholder="0.0" required>
                                </div>
                                <div>
                                    <label for="id_desc_monet" class="form-label">Descuento (S/) (1 dec.)</label>
                                    <input type="text" class="form-control" id="id_desc_monet" name="id_desc_monet"
                                           value="0.0" readonly>
                                </div>
                                <div>
                                    <label for="id_total" class="form-label">Total final (S/) (2 dec.)</label>
                                    <input type="text" class="form-control" id="id_total" name="id_total"
                                           value="0.00" readonly>
                                </div>
                                <div class="col-span-2">
                                    <label for="id_responsable" class="form-label">Responsable</label>
                                    <select class="form-select" id="id_responsable" name="id_responsable" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($responsablesActivos as $r): ?>
                                            <option value="<?= htmlspecialchars($r['ID_RESPONSABLE']) ?>">
                                                <?= htmlspecialchars($r['NOMBRE_RESPONSABLE'] . ($r['CARGO_RESPONSABLE'] ? ' — '.$r['CARGO_RESPONSABLE'] : '')) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar descuento
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">
                            Regla: el descuento en dinero se guarda con 1 decimal y el total con 2 (redondeo a paso 0.10 en backend).
                        </div>
                    </section>
                </div>

                <!-- TAB 5: Informe Cortesía -->
                <div class="tab-pane fade" id="icortesia" role="tabpanel" aria-labelledby="icortesia-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header" style="background:linear-gradient(90deg,#6a00a3 0%, #1f2937 100%);">
                            <div class="banner-icon"><i class="bi bi-gift fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Informe de Cortesía</h3>
                                <p class="banner-sub">Registra una cortesía con su motivo y responsable</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formInformeCortesia"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Info_Cortesia.php"
                                  method="post" class="form-grid cols-3" autocomplete="off" novalidate>
                                <div>
                                    <label for="ic_check" class="form-label">CHECK (código / número)</label>
                                    <input type="number" inputmode="numeric" class="form-control" id="ic_check"
                                           name="ic_check" placeholder="Ej: 7891" step="1" min="0" max="9999999999" required>
                                </div>
                                <div class="col-span-2">
                                    <label for="ic_persona" class="form-label">Nombre del beneficiario</label>
                                    <input type="text" class="form-control" id="ic_persona" name="ic_persona"
                                           maxlength="100" placeholder="Cliente / Huésped" required>
                                </div>
                                <div class="col-span-3">
                                    <label for="ic_motivo" class="form-label">Motivo de la cortesía</label>
                                    <input type="text" class="form-control" id="ic_motivo" name="ic_motivo"
                                           maxlength="500" placeholder="Ej: Cumpleaños / Inconveniente de servicio / Invitación" required>
                                </div>
                                <div>
                                    <label for="ic_monto" class="form-label">Monto cortesía (S/)</label>
                                    <input type="number" step="0.01" min="0" class="form-control" id="ic_monto"
                                           name="ic_monto" placeholder="0.00" required>
                                </div>
                                <div class="col-span-2">
                                    <label for="ic_responsable" class="form-label">Responsable</label>
                                    <select class="form-select" id="ic_responsable" name="ic_responsable" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($responsablesActivos as $r): ?>
                                            <option value="<?= htmlspecialchars($r['ID_RESPONSABLE']) ?>">
                                                <?= htmlspecialchars($r['NOMBRE_RESPONSABLE'] . ($r['CARGO_RESPONSABLE'] ? ' — '.$r['CARGO_RESPONSABLE'] : '')) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar cortesía
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">El usuario que registra se toma de la sesión.</div>
                    </section>
                </div>

                <!-- TAB 6: Informe Nota de Crédito -->
                <div class="tab-pane fade" id="inota" role="tabpanel" aria-labelledby="inota-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header" style="background:linear-gradient(90deg,#0b5d6a 0%, #1f2937 100%);">
                            <div class="banner-icon"><i class="bi bi-file-earmark-text fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Informe Nota de Crédito</h3>
                                <p class="banner-sub">Registra notas de crédito por documento, anulaciones o correcciones</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formNotaCredito"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Info_Nota_Credito.php"
                                  method="post" class="form-grid cols-3" autocomplete="off" novalidate>
                                <div>
                                    <label for="nc_tipo" class="form-label">Tipo de documento</label>
                                    <select class="form-select" id="nc_tipo" name="nc_tipo" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <option value="BOLETA">BOLETA</option>
                                        <option value="FUNCIONARIO">FUNCIONARIO</option>
                                        <option value="FACTURA">FACTURA</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="nc_ref_anu" class="form-label">Ref. Anulación (opcional)</label>
                                    <input type="text" class="form-control" id="nc_ref_anu" name="nc_ref_anu" maxlength="10"
                                           placeholder="ER023ER" pattern="[A-Za-z0-9]{0,10}"
                                           inputmode="latin-prose" style="text-transform:uppercase;">
                                    <div class="form-text">Máx. 10 caracteres alfanuméricos (se guarda en MAYÚSCULAS).</div>
                                </div>
                                <div>
                                    <label for="nc_ref_cor" class="form-label">Ref. Corrección (opcional)</label>
                                    <input type="text" class="form-control" id="nc_ref_cor" name="nc_ref_cor" maxlength="10"
                                           placeholder="AB12Z9" pattern="[A-Za-z0-9]{0,10}"
                                           inputmode="latin-prose" style="text-transform:uppercase;">
                                    <div class="form-text">Máx. 10 caracteres alfanuméricos (se guarda en MAYÚSCULAS).</div>
                                </div>
                                <div>
                                    <label for="nc_items" class="form-label">Cantidad de ítems</label>
                                    <input type="number" min="0" step="1" class="form-control" id="nc_items"
                                           name="nc_items" placeholder="0" required>
                                </div>
                                <div>
                                    <label for="nc_monto" class="form-label">Monto a devolver (S/)</label>
                                    <input type="number" min="0" step="0.01" class="form-control" id="nc_monto"
                                           name="nc_monto" placeholder="0.00" required>
                                    <div class="form-text">Se guarda redondeado al paso 0.10 en backend (DAO).</div>
                                </div>
                                <div class="col-span-3">
                                    <label for="nc_motivo" class="form-label">Motivo</label>
                                    <input type="text" class="form-control" id="nc_motivo" name="nc_motivo"
                                           maxlength="200" placeholder="Detalle del motivo…" required>
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar nota de crédito
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">El usuario (ID_USUARIO) se toma de la sesión.</div>
                    </section>
                </div>

                <!-- TAB 7: Informe Gasto -->
                <div class="tab-pane fade" id="igasto" role="tabpanel" aria-labelledby="igasto-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header" style="background:linear-gradient(90deg,#7A1E26 0%, #1f2937 100%);">
                            <div class="banner-icon"><i class="bi bi-cash-coin fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Informe de Gasto</h3>
                                <p class="banner-sub">Registra cualquier gasto operativo del día</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formInformeGasto"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Info_Gasto.php"
                                  method="post" class="form-grid cols-3" autocomplete="off" novalidate>
                                <div class="col-span-2">
                                    <label for="ig_persona" class="form-label">Persona que entrega</label>
                                    <input type="text" class="form-control" id="ig_persona" name="ig_persona"
                                           maxlength="100" placeholder="Ej: Juan Pérez / Proveedor de verduras" required>
                                </div>
                                <div>
                                    <label for="ig_monto" class="form-label">Monto del gasto (S/)</label>
                                    <input type="number" step="0.01" min="0" class="form-control" id="ig_monto"
                                           name="ig_monto" placeholder="0.00" required>
                                </div>
                                <div class="col-span-3">
                                    <label for="ig_motivo" class="form-label">Motivo del gasto (opcional)</label>
                                    <input type="text" class="form-control" id="ig_motivo" name="ig_motivo"
                                           maxlength="200" placeholder="Descripción breve del gasto...">
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar gasto
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">El usuario que registra se toma desde la sesión (<code>ID_USUARIO</code>).</div>
                    </section>
                </div>

                <!-- TAB 8: Informe Eliminado -->
                <div class="tab-pane fade" id="ielim" role="tabpanel" aria-labelledby="ielim-tab" tabindex="0">
                    <section class="banner mt-3">
                        <div class="banner-header" style="background:linear-gradient(90deg,#A34A00 0%, #1f2937 100%);">
                            <div class="banner-icon"><i class="bi bi-x-octagon fs-5"></i></div>
                            <div>
                                <h3 class="banner-title">Informe de Eliminado</h3>
                                <p class="banner-sub">Registra ítems eliminados: categoría, producto, motivo y total</p>
                            </div>
                        </div>
                        <div class="banner-body">
                            <form id="formInformeEliminado"
                                  action="/Proyecto_Guardiana/backend/procesos/Guardar_Info_Eliminado.php"
                                  method="post" class="form-grid cols-3" autocomplete="off" novalidate>
                                <div class="col-span-2">
                                    <label for="ie_empleado" class="form-label">Empleado (mesero / quien elimina)</label>
                                    <select class="form-select" id="ie_empleado" name="ie_empleado" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($meserosActivos as $m): ?>
                                            <option value="<?= htmlspecialchars($m['ID_EMPLEADO']) ?>">
                                                <?= htmlspecialchars($m['APELLIDO_EMPLEADO'] . ', ' . $m['NOMBRE_EMPLEADO']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label for="ie_categoria" class="form-label">Categoría</label>
                                    <select class="form-select" id="ie_categoria" name="ie_categoria" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($categoriasActivas as $c): ?>
                                            <option value="<?= htmlspecialchars($c['ID_CATEGORIA']) ?>">
                                                <?= htmlspecialchars($c['ID_CATEGORIA']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-span-2">
                                    <label for="ie_producto" class="form-label">Producto</label>
                                    <select class="form-select" id="ie_producto" name="ie_producto" required>
                                        <option value="" selected disabled>Seleccione una categoría primero…</option>
                                    </select>

                                    <!-- Catálogo al front -->
                                    <script type="application/json" id="data-productos">
                                        <?= json_encode($productosActivos, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>
                                    </script>
                                </div>
                                <div>
                                    <label for="ie_unidades" class="form-label">Unidades</label>
                                    <input type="number" min="0" step="1" class="form-control" id="ie_unidades"
                                           name="ie_unidades" placeholder="0" required>
                                </div>
                                <div>
                                    <label for="ie_precio" class="form-label">Precio unitario (S/)</label>
                                    <input type="number" step="0.01" min="0" class="form-control" id="ie_precio"
                                           name="ie_precio" placeholder="0.00" required readonly>
                                </div>
                                <div>
                                    <label for="ie_total" class="form-label">Total (S/)</label>
                                    <input type="text" class="form-control" id="ie_total" name="ie_total"
                                           value="0.00" readonly>
                                </div>
                                <div class="col-span-2">
                                    <label for="ie_motivo" class="form-label">Motivo</label>
                                    <select class="form-select" id="ie_motivo" name="ie_motivo" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($motivosEliminado as $mot): ?>
                                            <option value="<?= htmlspecialchars($mot) ?>"><?= htmlspecialchars($mot) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label for="ie_responsable" class="form-label">Responsable</label>
                                    <select class="form-select" id="ie_responsable" name="ie_responsable" required>
                                        <option value="" selected disabled>Seleccione…</option>
                                        <?php foreach($responsablesActivos as $r): ?>
                                            <option value="<?= htmlspecialchars($r['ID_RESPONSABLE']) ?>">
                                                <?= htmlspecialchars($r['NOMBRE_RESPONSABLE'] . ($r['CARGO_RESPONSABLE'] ? ' — '.$r['CARGO_RESPONSABLE'] : '')) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="d-flex gap-12" style="grid-column:1/-1;">
                                    <button type="submit" class="btn btn-dark btn-cta flex-fill">
                                        Registrar eliminado
                                    </button>
                                </div>
                            </form>
                        </div>
                        <div class="banner-footer">El total se calcula como <code>unidades × precio</code> (validado también en backend).</div>
                    </section>
                </div>
            </div><!-- /tab-content -->
        </div><!-- /panel-card -->
    </div><!-- /container -->

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Scripts UX/Calculadoras -->
    <script>
    // ========================== Bloqueo doble envío ==========================
    document.querySelectorAll('form').forEach(f => {
      let locked = false;
      f.addEventListener('submit', e => {
        if (locked) { e.preventDefault(); return; }
        locked = true;
        f.querySelectorAll('button[type="submit"]').forEach(b => {
          b.disabled = true;
          b.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Guardando...';
        });
        setTimeout(() => locked = false, 2000);
      });
    });

    // ====================== Propina Tarjeta (5% y neto trunc) =================
    (function () {
        const monto = document.getElementById('pt_monto');
        const desc  = document.getElementById('pt_desc');
        const neto  = document.getElementById('pt_neto');

        const to2 = n => (isNaN(n) ? 0 : Math.round(Number(n) * 100) / 100).toFixed(2);
        const to2TruncFrom1 = n => {
            const v = Math.trunc((isNaN(n) ? 0 : Number(n)) * 10) / 10; // trunc 1 dec
            return v.toFixed(2);
        };

        function calc() {
            const m = parseFloat(monto?.value) || 0;
            const d = m * 0.05;
            const n = m - d;
            if (desc) desc.value = to2(d);
            if (neto) neto.value = to2TruncFrom1(n);
        }
        monto?.addEventListener('input', calc);
        calc();
    })();

    // ==================== Informe Descuento (paso 0.10 en total) ==============
    (function () {
        const monto = document.getElementById('id_monto');
        const porc  = document.getElementById('id_porc');
        const desc  = document.getElementById('id_desc_monet'); // 1 dec
        const total = document.getElementById('id_total');       // 2 dec

        const PASO = 0.10;
        function roundToStep(v, step) {
            if (!isFinite(v) || step <= 0) return v;
            return Math.round(v / step) * step;
        }

        function calcDesc() {
            const m = parseFloat(monto?.value) || 0;
            const p = parseFloat(porc?.value)  || 0;

            const dRaw = m * (p / 100);
            const dMon = Math.round(dRaw * 10) / 10; // 1 dec
            const t    = roundToStep(m - dMon, PASO);

            if (desc)  desc.value  = dMon.toFixed(1);
            if (total) total.value = t.toFixed(2);
        }

        monto?.addEventListener('input', calcDesc);
        porc?.addEventListener('input',  calcDesc);
        calcDesc();
    })();

    // ======================= Pestañas: foco + scroll suave ====================
    document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(tabEl => {
        tabEl.addEventListener('shown.bs.tab', (ev) => {
            const sel  = ev.target.getAttribute('data-bs-target');
            const pane = document.querySelector(sel);
            if (!pane) return;
            const firstField = pane.querySelector('input, select, textarea');
            if (firstField) firstField.focus({ preventScroll: true });
            pane.scrollIntoView({ behavior: 'smooth', block: 'start' });
        });
    });

    // ================== Mantener pestaña + autocierre de alertas ==============
    document.addEventListener('DOMContentLoaded', () => {
        const params = new URLSearchParams(location.search);
        const tabParam = params.get('tab'); // pfisico|ptarjeta|...

        // Forzar pestaña si viene ?tab=
        if (tabParam) {
            const trigger = document.querySelector(`#regTabs button[data-bs-target="#${tabParam}"]`);
            if (trigger && window.bootstrap?.Tab) new bootstrap.Tab(trigger).show();
        }

        // Guardar última pestaña activa
        document.querySelectorAll('#regTabs button[data-bs-toggle="tab"]').forEach(btn => {
            btn.addEventListener('shown.bs.tab', (e) => {
                const sel = e.target.getAttribute('data-bs-target'); // "#ptarjeta"
                if (sel) localStorage.setItem('regTabs.active', sel.substring(1));
            });
        });

        // Restaurar última pestaña si no vino ?tab=
        if (!tabParam) {
            const last = localStorage.getItem('regTabs.active'); // ej: "ptarjeta"
            if (last) {
                const trigger = document.querySelector(`#regTabs button[data-bs-target="#${last}"]`);
                if (trigger && window.bootstrap?.Tab) new bootstrap.Tab(trigger).show();
            }
        }

        // Auto-cierre de alerta con pausa al hover
        const msg = document.getElementById('msgAlert');
        if (msg && window.bootstrap?.Alert) {
            const bsAlert = bootstrap.Alert.getOrCreateInstance(msg);
            let timer = setTimeout(() => {
                if (document.body.contains(msg)) bsAlert.close();
            }, 4000);
            msg.addEventListener('mouseenter', () => clearTimeout(timer));
            msg.addEventListener('mouseleave', () => {
                if (!msg.classList.contains('show')) return;
                timer = setTimeout(() => {
                    if (document.body.contains(msg)) bsAlert.close();
                }, 1500);
            });
        }

        // Nota de crédito: upcase y alfanumérico (máx 10)
        (function () {
            const onlyAZ09 = s => s.replace(/[^A-Za-z0-9]/g, '').toUpperCase().slice(0, 10);
            ['nc_ref_anu', 'nc_ref_cor'].forEach(id => {
                const el = document.getElementById(id);
                if (!el) return;
                const handler = () => { el.value = onlyAZ09(el.value); };
                el.addEventListener('input', handler);
                el.addEventListener('blur',  handler);
            });
        })();

        // Eliminado: productos por categoría + precio auto + total
        (function () {
            const selCat     = document.getElementById('ie_categoria');
            const selProd    = document.getElementById('ie_producto');
            const inputUnid  = document.getElementById('ie_unidades');
            const inputPrecio= document.getElementById('ie_precio');
            const inputTotal = document.getElementById('ie_total');

            let catalogo = [];
            try {
                const raw = document.getElementById('data-productos')?.textContent || '[]';
                catalogo = JSON.parse(raw);
            } catch (_) { catalogo = []; }

            const precioMap = {};
            catalogo.forEach(p => { precioMap[String(p.ID_PRODUCTO)] = Number(p.PRECIO_PRODUCTO || 0); });

            const format2 = n => (Math.round(Number(n || 0) * 100) / 100).toFixed(2);

            function poblarProductos(idCategoria) {
                selProd.innerHTML = '<option value="" selected disabled>Seleccione…</option>';
                if (!idCategoria) return;
                const lista = catalogo.filter(x => String(x.ID_CATEGORIA) === String(idCategoria));
                for (const p of lista) {
                    const opt = document.createElement('option');
                    opt.value = p.ID_PRODUCTO;
                    opt.textContent = `${p.NOMBRE_PRODUCTO}`;
                    opt.dataset.precio = format2(p.PRECIO_PRODUCTO);
                    selProd.appendChild(opt);
                }
                if (lista.length === 1) {
                    selProd.selectedIndex = 1;
                    selProd.dispatchEvent(new Event('change'));
                }
            }

            function calcularTotal() {
                const u  = Number(inputUnid?.value || 0);
                const pr = Number(inputPrecio?.value || 0);
                const tot= Math.max(0, u) * Math.max(0, pr);
                if (inputTotal) inputTotal.value = format2(tot);
            }

            selCat?.addEventListener('change', e => {
                poblarProductos(e.target?.value);
                if (inputPrecio) inputPrecio.value = '';
                if (inputTotal)  inputTotal.value  = '0.00';
            });

            selProd?.addEventListener('change', () => {
                const opt    = selProd.options[selProd.selectedIndex];
                const precio = opt?.dataset?.precio ?? '';
                const precioFallback = precioMap[String(selProd.value)];
                const final = precio !== '' ? Number(precio) : Number(precioFallback || 0);
                if (inputPrecio) inputPrecio.value = format2(final);
                calcularTotal();
            });

            inputUnid?.addEventListener('input', calcularTotal);
            inputPrecio?.addEventListener('input', calcularTotal);
        })();
    });
    // ======================== Fin DOMContentLoaded ============================
    </script>
</body>
</html>
