<?php
// ventas.php — Aprobación e impresión de tickets (2/3/4 cifras) con carritos independientes
declare(strict_types=1);
session_start();
date_default_timezone_set('America/Guayaquil');

// Seguridad básica
if (!isset($_SESSION['idusuario'], $_SESSION['usuario'], $_SESSION['sucursal'])) {
  header('Location: index.php'); exit();
}

$idusuario   = (int)$_SESSION['idusuario'];
$usuario     = htmlspecialchars((string)$_SESSION['usuario']);
$sucursal_id = $_SESSION['sucursal'] ?? null;
if (!is_numeric($sucursal_id)) { die("ID de sucursal inválido"); }

// Conexión
require_once __DIR__ . '/conex.php';
if (!isset($conn) || $conn === null) { die("Error: No se pudo establecer la conexión a la base de datos."); }

// Sucursal
$sucursal = '';
$stmt = mysqli_prepare($conn, "SELECT sucursal FROM tbr_sucursal WHERE idsucursal = ?");
mysqli_stmt_bind_param($stmt, "i", $sucursal_id);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($res)) { $sucursal = $row['sucursal']; } else { die("Sucursal no encontrada."); }
mysqli_stmt_close($stmt);

// Permisos de usuario
$venta = 0; $pago = 0;
$stmtu = mysqli_prepare($conn, "SELECT venta, pago FROM tbr_usuario WHERE idusuario = ?");
mysqli_stmt_bind_param($stmtu, "i", $idusuario);
mysqli_stmt_execute($stmtu);
$resu = mysqli_stmt_get_result($stmtu);
if ($row = mysqli_fetch_assoc($resu)) { $venta = (int)$row['venta']; $pago = (int)$row['pago']; } else { die("Usuario no encontrado"); }
mysqli_stmt_close($stmtu);
if ($venta != 1) { header("Location: pago.php"); exit; }
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sistema de Gestión · Ventas</title>
  <link rel="shortcut icon" href="../resources/img/crud.ico">

  <!-- CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet">

  <style>
    body{background:#f4f6f9;}
    .navbar{margin-bottom:20px;}
    .sidebar{width:150px;background:#343a40;padding:20px;height:100vh;position:fixed;left:0;top:0;display:flex;flex-direction:column;align-items:center;}
    .sidebar a{color:#fff;text-decoration:none;padding:10px 15px;display:block;width:100%;text-align:center;}
    .sidebar a:hover{background:#495057;border-radius:8px;}
    .sidebar .active{font-weight:bold;color:#17a2b8;}
    .main-content{margin-left:0;transition:margin-left .3s;}
    @media (min-width:769px){.main-content{margin-left:150px;}}
    .loader{position:fixed;inset:0;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:bold;z-index:2000;}
    .loader::before{content:'';width:40px;height:40px;border:5px solid #fff;border-radius:50%;border-top-color:transparent;animation:spin 1s linear infinite;margin-right:12px;}
    @keyframes spin{to{transform:rotate(360deg);}}
    .input-group{border:1px solid #ced4da;border-radius:8px;align-items:center;background:#fff;}
    .input-group:hover{box-shadow:0 0 10px rgba(0,123,255,.15);}
    .input-group-text{background:#17a2b8;color:#fff;border-radius:8px 0 0 8px;}
    .form-control{border-left:0;border-radius:0 8px 8px 0;padding:10px;font-size:2rem;}
    .tab-pane.dos-cifras{background:rgba(255,204,0,.08);border:2px solid #ffcc00;}
    .tab-pane.tres-cifras{background:rgba(0,153,255,.06);border:2px solid #1e90ff;}
    .tab-pane.cuatro-cifras{background:rgba(40,167,69,.06);border:2px solid #28a745;}
    .table-sm th,.table-sm td{padding:.45rem .5rem;}
  </style>
</head>

<body>
  <!-- Sidebar -->
  <nav class="sidebar" id="sidebar">
    <ul class="nav flex-column text-center">
      <li class="nav-item"><a href="dashboard.php"><i class="fa fa-tachometer-alt"></i> Dashboard</a></li>
      <?php if ($venta == 1): ?>
      <li class="nav-item">
        <a href="ventas.php" class="nav-link <?php echo basename($_SERVER['PHP_SELF'])=='ventas.php'?'active':''; ?>">
          <i class="fas fa-shopping-cart fa-2x"></i>
          <div class="text-uppercase" style="font-size:12px;">Ventas</div>
        </a>
      </li>
      <?php endif; ?>
      <?php if ($pago == 1): ?>
      <li class="nav-item">
        <a href="pago.php" class="nav-link <?php echo basename($_SERVER['PHP_SELF'])=='pago.php'?'active':''; ?>">
          <i class="fas fa-money-check-alt fa-2x"></i>
          <div class="text-uppercase" style="font-size:12px;">Pago</div>
        </a>
      </li>
      <?php endif; ?>
      <li class="nav-item"><a href="historial.php" class="nav-link"><i class="fa fa-history fa-2x"></i><div class="text-uppercase" style="font-size:12px;">Historial</div></a></li>
      <li class="nav-item"><a href="reporte_usu2.php" class="nav-link"><i class="fa fa-cubes fa-2x"></i><div class="text-uppercase" style="font-size:12px;">Utilidad 2 cifras</div></a></li>
      <li class="nav-item"><a href="reporte_usu3.php" class="nav-link"><i class="fa fa-cubes fa-2x"></i><div class="text-uppercase" style="font-size:12px;">Utilidad 3 cifras</div></a></li>
      <li class="nav-item"><a href="reporte_usu4.php" class="nav-link"><i class="fa fa-cubes fa-2x"></i><div class="text-uppercase" style="font-size:12px;">Utilidad 4 cifras</div></a></li>
      <li class="nav-item"><a href="javascript:void(0)" class="nav-link" onclick="cerrar();"><i class="fas fa-sign-out-alt fa-2x"></i><div class="text-uppercase" style="font-size:12px;">Cerrar Sesión</div></a></li>
    </ul>
  </nav>

  <!-- Contenido Principal -->
  <div class="main-content" id="mainContent">
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container-fluid">
        <button class="navbar-toggler" type="button" aria-label="Toggle navigation" onclick="toggleSidebar()">
          <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="#"><i class="fas fa-tachometer-alt"></i> Panel de Venta</a>
        <div class="collapse navbar-collapse">
          <ul class="navbar-nav ms-auto">
            <li class="nav-item"><a class="nav-link active"><i class="fa fa-store"></i> <?php echo " ".$sucursal; ?></a></li>
            <li class="nav-item"><a class="nav-link active"><i class="fa fa-user-secret"></i> <?php echo " ".$usuario; ?></a></li>
            <li class="nav-item"><a class="nav-link"><i class="fa fa-calendar-check"></i> <span id="fechaActual"></span></a></li>
            <li class="nav-item d-none d-md-block"><a class="nav-link"><em class="fas fa-clock text-mac"></em>&nbsp;<span id="horaActual"></span></a></li>
          </ul>
        </div>
      </div>
    </nav>

    <!-- Tabs -->
    <ul class="nav nav-tabs" id="myTab" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="dos-cifras-tab" data-bs-toggle="tab" data-bs-target="#dos-cifras" type="button" role="tab">Dos Cifras</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="tres-cifras-tab" data-bs-toggle="tab" data-bs-target="#tres-cifras" type="button" role="tab">Tres Cifras</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="cuatro-cifras-tab" data-bs-toggle="tab" data-bs-target="#cuatro-cifras" type="button" role="tab">Cuatro Cifras</button>
      </li>
    </ul>

    <div class="tab-content mt-3" id="myTabContent">
      <!-- ====== DOS CIFRAS ====== -->
      <div class="tab-pane fade show active dos-cifras" id="dos-cifras" role="tabpanel">
        <div class="card border-primary mb-3">
          <div class="card-body">
            <div class="row">
              <!-- Columna izquierda -->
              <div class="col-12 col-lg-4">
                <div class="card border-primary mb-3">
                  <div class="card-body">
                    <form onsubmit="return false;">
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-calendar-week fa-3x"></i></span>
                          <input id="date2_2c" type="date" class="form-control" required>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-play fa-3x"></i></span>
                          <select class="form-control" id="loterias_2c" required>
                            <option value="" selected disabled>— Selecciona una lotería —</option>
                          </select>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-list-ol fa-3x"></i></span>
                          <input class="form-control numberNoBotones" id="number_2c" type="text" inputmode="numeric" placeholder="Ingrese Número (00-99)" required>
                        </div>
                      </div>
                      <div class="form-group mb-4">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-dollar-sign fa-3x"></i></span>
                          <input class="form-control numberNoBotones" id="valor_2c" type="number" placeholder="Ingrese Valor" min="0.50" step="0.01" required>
                        </div>
                      </div>
                      <div class="form-group">
                        <button type="button" onclick="cargar2c()" class="btn btn-success w-100">Cargar</button>
                      </div>
                    </form>
                  </div>
                </div>

                <div class="card border-info mb-3">
                  <div class="card-header bg-info text-center text-white"><h6 class="mb-0">Números copados hoy (2 cifras)</h6></div>
                  <div class="card-body p-2">
                    <table class="table table-responsive table-sm text-center mb-0">
                      <tbody id="tbCopados_2c"><tr><td colspan="3">Cargando números...</td></tr></tbody>
                    </table>
                  </div>
                </div>
              </div>

              <!-- Carrito -->
              <div class="col-12 col-lg-4">
                <div class="card border-danger mb-3">
                  <div class="card-body p-0">
                    <div class="table-responsive w-100">
                      <table id="ticket_2c" class="table table-striped table-sm mb-0 w-100">
                        <thead>
                          <tr>
                            <th>Lotería</th><th>Fecha</th><th>Número</th><th>Valor</th><th>Acción</th>
                          </tr>
                        </thead>
                        <tbody></tbody>
                        <tfoot>
                          <tr>
                            <th colspan="3" class="text-end">Total</th>
                            <th id="total-value_2c">$0.00</th><th></th>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  </div>
                  <div class="form-group px-3 pb-3 pt-2">
                    <button type="button" onclick="aprobar2c()" class="btn btn-primary w-100" id="save_2c">Aprobar</button>
                  </div>
                  <div class="mt-1 px-3 pb-3" id="progress-container_2c" style="display:none;">
                    <div class="progress"><div id="progress-bar_2c" class="progress-bar" style="width:0%;">0%</div></div>
                    <small id="progress-text_2c" class="text-muted d-block mt-1 text-center"></small>
                  </div>
                </div>
              </div>

              <!-- Últimos -->
              <div class="col-12 col-lg-4">
                <div class="card border-warning mb-3">
                  <div class="card-header bg-warning text-center"><h6 class="mb-0">Últimos números (2 cifras)</h6></div>
                  <div class="card-body p-2">
                    <table class="table table-responsive table-sm text-center mb-0">
                      <tbody id="tbUltimas_2c"><tr><td colspan="3">Cargando números...</td></tr></tbody>
                    </table>
                  </div>
                </div>
              </div>

            </div><!-- row -->
          </div>
        </div>
      </div>

      <!-- ====== TRES CIFRAS ====== -->
      <div class="tab-pane fade tres-cifras" id="tres-cifras" role="tabpanel">
        <div class="card border-primary mb-3">
          <div class="card-body">
            <div class="row">
              <!-- Columna izquierda -->
              <div class="col-12 col-lg-4">
                <div class="card border-primary mb-3">
                  <div class="card-body">
                    <form onsubmit="return false;">
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-calendar-week fa-3x"></i></span>
                          <input id="date2_3c" type="date" class="form-control" required>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-play fa-3x"></i></span>
                          <select class="form-control" id="loterias_3c" required>
                            <option value="" selected disabled>— Selecciona una lotería —</option>
                          </select>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-list-ol fa-3x"></i></span>
                          <input class="form-control numberNoBotones" id="number_3c" type="text" inputmode="numeric" placeholder="Ingrese Número (000-999)" required>
                        </div>
                      </div>
                      <div class="form-group mb-4">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-dollar-sign fa-3x"></i></span>
                          <input class="form-control numberNoBotones" id="valor_3c" type="number" placeholder="Ingrese Valor" min="0.50" step="0.01" required>
                        </div>
                      </div>
                      <div class="form-group">
                        <button type="button" onclick="cargar3c()" class="btn btn-success w-100">Cargar</button>
                      </div>
                    </form>
                  </div>
                </div>

                <div class="card border-info mb-3">
                  <div class="card-header bg-info text-center text-white"><h6 class="mb-0">Números copados hoy (3 cifras)</h6></div>
                  <div class="card-body p-2">
                    <table class="table table-responsive table-sm text-center mb-0">
                      <tbody id="tbCopados_3c"><tr><td colspan="3">Cargando números...</td></tr></tbody>
                    </table>
                  </div>
                </div>
              </div>

              <!-- Carrito -->
              <div class="col-12 col-lg-4">
                <div class="card border-danger mb-3">
                  <div class="card-body p-0">
                    <div class="table-responsive w-100">
                      <table id="ticket_3c" class="table table-striped table-sm mb-0 w-100">
                        <thead>
                          <tr>
                            <th>Lotería</th><th>Fecha</th><th>Número</th><th>Valor</th><th>Acción</th>
                          </tr>
                        </thead>
                        <tbody></tbody>
                        <tfoot>
                          <tr>
                            <th colspan="3" class="text-end">Total</th>
                            <th id="total-value_3c">$0.00</th><th></th>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  </div>
                  <div class="form-group px-3 pb-3 pt-2">
                    <button type="button" onclick="aprobar3c()" class="btn btn-primary w-100" id="save_3c">Aprobar</button>
                  </div>
                  <div class="mt-1 px-3 pb-3" id="progress-container_3c" style="display:none;">
                    <div class="progress"><div id="progress-bar_3c" class="progress-bar" style="width:0%;">0%</div></div>
                    <small id="progress-text_3c" class="text-muted d-block mt-1 text-center"></small>
                  </div>
                </div>
              </div>

              <!-- Últimos -->
              <div class="col-12 col-lg-4">
                <div class="card border-warning mb-3">
                  <div class="card-header bg-warning text-center"><h6 class="mb-0">Últimos números (3 cifras)</h6></div>
                  <div class="card-body p-2">
                    <table class="table table-responsive table-sm text-center mb-0">
                      <tbody id="tbUltimas_3c"><tr><td colspan="3">Cargando números...</td></tr></tbody>
                    </table>
                  </div>
                </div>
              </div>

            </div><!-- row -->
          </div>
        </div>
      </div>

      <!-- ====== CUATRO CIFRAS ====== -->
      <div class="tab-pane fade cuatro-cifras" id="cuatro-cifras" role="tabpanel">
        <div class="card border-primary mb-3">
          <div class="card-body">
            <div class="row">
              <!-- Columna izquierda -->
              <div class="col-12 col-lg-4">
                <div class="card border-primary mb-3">
                  <div class="card-body">
                    <form onsubmit="return false;">
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-calendar-week fa-3x"></i></span>
                          <input id="date2_4c" type="date" class="form-control" required>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-play fa-3x"></i></span>
                          <select class="form-control" id="loterias_4c" required>
                            <option value="" selected disabled>— Selecciona una lotería —</option>
                          </select>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-list-ol fa-3x"></i></span>
                          <input class="form-control numberNoBotones" id="number_4c" type="text" inputmode="numeric" placeholder="Ingrese Número (0000-9999)" required>
                        </div>
                      </div>
                      <div class="form-group mb-4">
                        <div class="input-group">
                          <span class="input-group-text"><i class="fas fa-dollar-sign fa-3x"></i></span>
                          <input class="form-control numberNoBotones" id="valor_4c" type="number" placeholder="Ingrese Valor" min="0.50" step="0.01" required>
                        </div>
                      </div>
                      <div class="form-group">
                        <button type="button" onclick="cargar4c()" class="btn btn-success w-100">Cargar</button>
                      </div>
                    </form>
                  </div>
                </div>

                <div class="card border-info mb-3">
                  <div class="card-header bg-info text-center text-white"><h6 class="mb-0">Números copados hoy (4 cifras)</h6></div>
                  <div class="card-body p-2">
                    <table class="table table-responsive table-sm text-center mb-0">
                      <tbody id="tbCopados_4c"><tr><td colspan="3">Cargando números...</td></tr></tbody>
                    </table>
                  </div>
                </div>
              </div>

              <!-- Carrito -->
              <div class="col-12 col-lg-4">
                <div class="card border-danger mb-3">
                  <div class="card-body p-0">
                    <div class="table-responsive w-100">
                      <table id="ticket_4c" class="table table-striped table-sm mb-0 w-100">
                        <thead>
                          <tr>
                            <th>Lotería</th><th>Fecha</th><th>Número</th><th>Valor</th><th>Acción</th>
                          </tr>
                        </thead>
                        <tbody></tbody>
                        <tfoot>
                          <tr>
                            <th colspan="3" class="text-end">Total</th>
                            <th id="total-value_4c">$0.00</th><th></th>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  </div>
                  <div class="form-group px-3 pb-3 pt-2">
                    <button type="button" onclick="aprobar4c()" class="btn btn-primary w-100" id="save_4c">Aprobar</button>
                  </div>
                  <div class="mt-1 px-3 pb-3" id="progress-container_4c" style="display:none;">
                    <div class="progress"><div id="progress-bar_4c" class="progress-bar" style="width:0%;">0%</div></div>
                    <small id="progress-text_4c" class="text-muted d-block mt-1 text-center"></small>
                  </div>
                </div>
              </div>

              <!-- Últimos -->
              <div class="col-12 col-lg-4">
                <div class="card border-warning mb-3">
                  <div class="card-header bg-warning text-center"><h6 class="mb-0">Últimos números (4 cifras)</h6></div>
                  <div class="card-body p-2">
                    <table class="table table-responsive table-sm text-center mb-0">
                      <tbody id="tbUltimas_4c"><tr><td colspan="3">Cargando números...</td></tr></tbody>
                    </table>
                  </div>
                </div>
              </div>

            </div><!-- row -->
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- JS -->
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <script>
    /* ===== Utils generales ===== */
    $.ajaxSetup({
      dataFilter: function (data, type) {
        if (type === 'json' && typeof data === 'string') {
          if (data.charCodeAt(0) === 0xFEFF) data = data.slice(1);
          data = data.replace(/^\uFEFF/, '');
        }
        return data;
      }
    });

    // Fecha/hora UI (Guayaquil)
    (function(){
      function pad2(n){return n.toString().padStart(2,'0');}
      function tick(){
        const now = new Date();
        const ec  = new Date(now.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
        const fecha = ec.toLocaleDateString('es-EC', { weekday:'long', year:'numeric', month:'long', day:'numeric' });
        const hora  = pad2(ec.getHours())+":"+pad2(ec.getMinutes());
        $('#fechaActual').text(fecha);
        $('#horaActual').text(hora);
      }
      tick(); setInterval(tick, 1000*30);
    })();

    function toggleSidebar(){ document.getElementById('sidebar').classList.toggle('show'); }

    function cerrar() {
      Swal.fire({
        title:'¿Estás seguro?', text:'¿Deseas cerrar sesión?', icon:'warning',
        showCancelButton:true, confirmButtonText:'Sí, cerrar sesión', cancelButtonText:'Cancelar'
      }).then((r)=>{
        if(!r.isConfirmed) return;
        const loader=document.createElement('div'); loader.className='loader'; loader.textContent='Cerrando sesión...'; document.body.appendChild(loader);
        fetch('../../controllers/usuario.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({boton:'cerrar'})})
          .then(resp=>resp.ok?resp.text():Promise.reject(new Error('Error '+resp.statusText)))
          .then(()=>location.href='../index.php')
          .catch(e=>Swal.fire('Error','Hubo un error al cerrar sesión: '+e.message,'error'))
          .finally(()=>loader.remove());
      });
    }

    // ===== Helpers fecha hoy EC
    function hoyEC() {
      const now = new Date();
      const ec  = new Date(now.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
      const y = ec.getFullYear();
      const m = String(ec.getMonth()+1).padStart(2,'0');
      const d = String(ec.getDate()).padStart(2,'0');
      return `${y}-${m}-${d}`;
    }

    // Set mínimos y defaults de fechas en las 3 pestañas
    document.addEventListener("DOMContentLoaded", function() {
      ['#date2_2c','#date2_3c','#date2_4c'].forEach(sel=>{
        const el = document.querySelector(sel);
        if (el){ const f=hoyEC(); el.min=f; if(!el.value) el.value=f; }
      });
    });
  </script>

  <!-- ============================= 2 CIFRAS ============================= -->
  <script>
    let dt_2c = null;

    function cargarLoterias_2c(){
      let fecha = $('#date2_2c').val();
      if (!fecha) { $('#loterias_2c').html("<option value=''>Seleccione fecha</option>"); return; }
      $.post('datos.php?Accion=GetLoterias', { fecha }, function(resp){
        $('#loterias_2c').html(resp);
      }).fail(()=>$('#loterias_2c').html("<option value=''>Error cargando loterías</option>"));
    }
    $(document).on('change','#date2_2c',cargarLoterias_2c);

    function initDt_2c(){
      if (dt_2c) { dt_2c.destroy(); dt_2c=null; $('#ticket_2c tbody').empty(); }
      dt_2c = $('#ticket_2c').DataTable({
        ajax:{ 
          url:'ticket_list.php', 
          type:'POST', 
          data:{ id_cifras:1 },
          dataSrc: function(j){ 
            $('#total-value_2c').text('$'+parseFloat(j?.total||0).toFixed(2)); 
            return j?.data||[]; 
          } 
        },
        processing:true, serverSide:false, searching:false, lengthChange:false, pageLength:10, responsive:true,
        columns:[
          {data:'loteria'}, 
          {data:'fecha'},
          {data:'numero', className:'text-center', render:(v)=>String(v??'').padStart(2,'0')},
          {data:'valor', className:'text-end', render:(v)=>'$'+(parseFloat(v||0)).toFixed(2)},
          {data:null, orderable:false, className:'text-center',
            render:(row)=>`<button class="btn btn-sm btn-outline-danger btn-del-2c" data-id="${row.id}"><i class="fa-solid fa-trash"></i></button>`}
        ],
        order:[[1,'asc']],
        language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"}
      });
    }

    function refresh_2c(){ 
      if (dt_2c) dt_2c.ajax.reload(null,false); 
    }

    function cargarUltimos_2c(){
      $.getJSON('obtener_numeros.php',{id_cifras:1}).done(function(data){
        let html=""; 
        if (Array.isArray(data)&&data.length){
          data.forEach((r,i)=>{ 
            const nf=String(r.numero??'').replace(/\D/g,'').slice(-2).padStart(2,'0');
            if(i%3===0) html+="<tr>"; 
            html+=`<td><div class="text-center">
            <small class="text-muted" style="font-size:14px">${r.loteria||''}</small><br>
            <button class="btn btn-dark" style="font-size:30px">${nf}</button><br>
            <small class="text-muted" style="font-size:16px">${r.valor||''}</small></div></td>`;
            if(i%3===2) html+="</tr>"; 
          }); 
          if(data.length%3!==0) html+="</tr>";
        } else html="<tr><td colspan='3'>No hay números</td></tr>";
        $('#tbUltimas_2c').html(html);
      }).fail(()=>$('#tbUltimas_2c').html("<tr><td colspan='3'>Error</td></tr>"));
    }

    function cargarCopados_2c(){
      $.getJSON('obtener_copados.php',{id_cifras:1}).done(function(data){
        const arr = data?.numeros_superan_cupo||[]; 
        let html="";
        if(arr.length){ 
          arr.forEach((r,i)=>{ 
            const nf=String(r.numero??'').replace(/\D/g,'').slice(-2).padStart(2,'0');
            if(i%3===0) html+="<tr>"; 
            html+=`<td><div class="text-center">
            <button class="btn btn-dark" style="font-size:30px">${nf}</button><br><small class="text-muted">T2</small></div></td>`;
            if(i%3===2) html+="</tr>"; 
          }); 
          if(arr.length%3!==0) html+="</tr>";
        } else html="<tr><td colspan='3'>Sin copados</td></tr>";
        $('#tbCopados_2c').html(html);
      }).fail(()=>$('#tbCopados_2c').html("<tr><td colspan='3'>Error</td></tr>"));
    }

    function cargar2c(){
      const date2=$('#date2_2c').val()?.trim(); 
      const loterias=$('#loterias_2c').val()?.trim();
      const numberRaw=$('#number_2c').val()?.trim(); 
      const valor=parseFloat($('#valor_2c').val());
      const hoy=hoyEC(); 
      if(date2<hoy){ return Swal.fire("Error","La fecha no puede ser menor que hoy.","error"); }
      const number=String(numberRaw||'').replace(/\D/g,'').slice(-2).padStart(2,'0'); 
      $('#number_2c').val(number);
      if(!date2||!loterias) return Swal.fire("Error","Completa los campos.","error");
      const n=parseInt(number,10); 
      if(isNaN(n)||n<0||n>99) return Swal.fire("Error","Número 00-99.","error");
      if(isNaN(valor)||valor<0.50) return Swal.fire("Error","Valor ≥ 0.50.","error");
      $.ajax({
        url:'guardar_ticket.php',
        type:'POST',
        dataType:'json',
        data:{date2,loterias,number,valor,id_cifras:1}
      })
      .done(r=>{ 
        if(r?.success){ 
          refresh_2c(); 
        } else if(r?.error==="Cupo_no_disponible"){ 
          Swal.fire({
            icon:"warning",
            title:"Cupo insuficiente",
            html:`${r.mensaje||''}<br><b>Disponible: $${r.cupo_restante||'0.00'}</b>`
          }); 
        } else { 
          Swal.fire("Error",r?.message||"No se pudo guardar.","error"); 
        }
      })
      .fail(xhr=>Swal.fire("Error",xhr?.responseText||"Error de red.","error"));
    }
    window.cargar2c = cargar2c;

    $(document).on('click','.btn-del-2c',function(){
      const id = parseInt($(this).data('id'),10); 
      if(!id) return;
      Swal.fire({
        title:'Eliminar ítem',
        text:'¿Quitar del carrito?',
        icon:'warning',
        showCancelButton:true
      })
      .then(r=>{ 
        if(!r.isConfirmed) return; 
        $.post('ticket_delete.php',{id},function(resp){
          if(resp?.success) refresh_2c(); 
          else Swal.fire('Atención',resp?.message||'No se pudo eliminar.','warning');
        },'json').fail(xhr=>Swal.fire('Error',xhr?.responseText||'Error','error')); 
      });
    });

    function prog2c(i,t){ 
      const pct=t>0?Math.floor((i/t)*100):0; 
      $('#progress-bar_2c').css('width',pct+'%').text(pct+'%'); 
      $('#progress-text_2c').text(`Procesados ${i} de ${t}`); 
    }

    function end2c(t){ 
      $('#progress-bar_2c').css('width','100%').text('100%'); 
      $('#progress-text_2c').text(`Completado: ${t} de ${t}`); 
      Swal.fire({icon:'success',title:'Completado',timer:1500,showConfirmButton:false})
        .then(()=>{ 
          $('#progress-container_2c').hide(); 
          $('#save_2c').prop('disabled',false).text('Aprobar'); 
          refresh_2c(); 
        }); 
    }

    function popup2c(){ 
      Swal.fire("Atención","Habilita pop-ups para imprimir.","info")
        .then(()=>$('#save_2c').prop('disabled',false).text('Aprobar')); 
    }

    function startAprobar2c(btn){
      $.getJSON('qr/contar_tickets.php',{id_cifras:1}).done(function(resp){
        const ids = Array.isArray(resp?.ids)?resp.ids:[];
        if(!ids.length){
          btn.prop('disabled',false).text('Aprobar');
          return Swal.fire('Advertencia','No hay tickets (2 cifras).','warning');
        }
        let i=0;
        $('#progress-container_2c').show();
        prog2c(i,ids.length);

        (function loop(){
          if(i>=ids.length){
            end2c(ids.length);
            return;
          }
          const id=ids[i];
          prog2c(i,ids.length);

          $.ajax({
            url:'qr/index.php',
            method:'GET',
            dataType:'json',
            data:{id}
          })
          .done(function(r){
            if(typeof r==='string'){
              const s=r.replace(/^\uFEFF/,'').trim();
              if(/^<!doctype html|^<html/i.test(s)){ i++; return loop(); }
              try{ r=JSON.parse(s);}catch(e){ i++; return loop(); }
            }
            const html=(r&&typeof r.html==='string')?r.html.replace(/^\uFEFF/,'').trim():'';
            if(!r||!r.success||!html){ i++; return loop(); }

            let w=window.open('','','width=300,height=600');
            if(!w){ popup2c(); return; }

            w.document.open();
            w.document.write(`
              <html><head><meta charset="utf-8" /><title>Impresión</title>
              <style>
                body{font-family:Arial,sans-serif;font-size:12px;text-align:center;padding:10px}
                img{max-width:100%}
                hr{border:none;border-top:1px dashed #000;margin:10px 0}
              </style>
              </head><body onload="window.print()">${html}</body></html>`);
            w.document.close();
            setTimeout(()=>{
              try{w.close();}catch(e){}
              i++; loop();
            }, 500);
          })
          .fail(()=>{ i++; loop(); });
        })();
      })
      .fail(()=>{
        Swal.fire('Error','Error de red.','error');
        btn.prop('disabled',false).text('Aprobar');
      });
    }

    function aprobar2c(){
      const btn = $('#save_2c');
      btn.prop('disabled',true).text('Procesando...');

      if (dt_2c) {
        dt_2c.ajax.reload(function(){
          startAprobar2c(btn);
        }, false);
      } else {
        startAprobar2c(btn);
      }
    }
    window.aprobar2c = aprobar2c;

    function initTab2c(){ 
      if(!dt_2c) initDt_2c(); 
      cargarLoterias_2c(); 
      cargarUltimos_2c(); 
      cargarCopados_2c(); 
    }
  </script>

  <!-- === Script de 3 cifras === -->
  <script>
  (function($){
    const $tab = $('#tres-cifras');
    const $date3c = $tab.find('#date2_3c');
    const $sel3c  = $tab.find('#loterias_3c');
    const $tbUlt3 = $tab.find('#tbUltimas_3c');
    const $tbCop3 = $tab.find('#tbCopados_3c');
    const $table3 = $tab.find('#ticket_3c');
    const $total3 = $tab.find('#total-value_3c');
    const $btnAprob3 = $tab.find('#save_3c');
    const $progBox3 = $tab.find('#progress-container_3c');
    const $progBar3 = $tab.find('#progress-bar_3c');
    const $progTxt3 = $tab.find('#progress-text_3c');

    let dtTicket3c = null;

    function cargarLoterias3c(){
      const fecha=($date3c.val()||'').trim();
      if(!fecha){ $sel3c.html("<option value=''>Seleccione fecha</option>"); return; }
      $.post('datos.php?Accion=GetLoterias',{fecha},(resp)=>$sel3c.html(resp))
        .fail(()=> $sel3c.html("<option value=''>Error</option>"));
    }

    function initDtTicket3c(){
      if(dtTicket3c){ dtTicket3c.destroy(); dtTicket3c=null; $table3.find('tbody').empty(); }
      dtTicket3c = $table3.DataTable({
        ajax:{ 
          url:'ticket_list3c.php', 
          type:'POST', 
          data:{id_cifras:2},
          dataSrc:(j)=>{ 
            $total3.text('$'+parseFloat(j?.total||0).toFixed(2)); 
            return j?.data||[]; 
          } 
        },
        processing:true, serverSide:false, searching:false, lengthChange:false, pageLength:10, responsive:true,
        columns:[
          {data:'loteria'},
          {data:'fecha'},
          {data:'numero',className:'text-center',render:(v)=>String(v??'').padStart(3,'0')},
          {data:'valor',className:'text-end',render:(v)=>'$'+(parseFloat(v||0)).toFixed(2)},
          {data:null,orderable:false,className:'text-center',
            render:(row)=>`<button class="btn btn-sm btn-outline-danger btn-del3c" data-id="${row.id}"><i class="fa-solid fa-trash"></i></button>`}
        ],
        order:[[1,'asc']],
        language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"}
      });
    }

    function refreshTicket3c(){ 
      if(dtTicket3c) dtTicket3c.ajax.reload(null,false); 
    }

    function cargarUltimos3c(){
      $.getJSON('obtener_numeros3.php',{id_cifras:2}).done(function(data){
        let html=""; 
        if(Array.isArray(data)&&data.length){
          data.forEach((r,i)=>{ 
            const nf=String(r.numero??'').replace(/\D/g,'').slice(-3).padStart(3,'0');
            if(i%3===0) html+="<tr>"; 
            html+=`<td><div class="text-center">
            <small class="text-muted" style="font-size:14px">${r.loteria||''}</small><br>
            <button class="btn btn-dark" style="font-size:30px">${nf}</button><br>
            <small class="text-muted" style="font-size:16px">${r.valor||''}</small></div></td>`;
            if(i%3===2) html+="</tr>"; 
          }); 
          if(data.length%3!==0) html+="</tr>";
        } else html="<tr><td colspan='3'>No hay números</td></tr>";
        $tbUlt3.html(html);
      }).fail(()=> $tbUlt3.html("<tr><td colspan='3'>Error</td></tr>"));
    }

    function cargarCopados3c(){
      $.getJSON('obtener_copados3.php',{id_cifras:2}).done(function(data){
        const arr=data?.numeros_superan_cupo||[]; 
        let html="";
        if(arr.length){ 
          arr.forEach((r,i)=>{ 
            const nf=String(r.numero??'').replace(/\D/g,'').slice(-3).padStart(3,'0');
            if(i%3===0) html+="<tr>"; 
            html+=`<td><div class="text-center">
            <button class="btn btn-dark" style="font-size:30px">${nf}</button><br><small class="text-muted">T3</small></div></td>`;
            if(i%3===2) html+="</tr>"; 
          }); 
          if(arr.length%3!==0) html+="</tr>";
        } else html="<tr><td colspan='3'>Sin copados</td></tr>";
        $tbCop3.html(html);
      }).fail(()=> $tbCop3.html("<tr><td colspan='3'>Error</td></tr>"));
    }

    function cargar3c() {
      const date2 = $('#date2_3c').val()?.trim();
      const loterias = $('#loterias_3c').val()?.trim();
      const numberRaw = $('#number_3c').val()?.trim();
      const valor = parseFloat($('#valor_3c').val());
      const hoy = hoyEC();

      if (date2 < hoy) {
        return Swal.fire("Error", "La fecha no puede ser menor que hoy.", "error");
      }

      const number = String(numberRaw || '').replace(/\D/g, '').slice(-3).padStart(3, '0');
      $('#number_3c').val(number);

      if (!date2 || !loterias) {
        return Swal.fire("Error", "Completa los campos.", "error");
      }

      const n = parseInt(number, 10);
      if (isNaN(n) || n < 0 || n > 999) {
        return Swal.fire("Error", "Número 000-999.", "error");
      }

      if (isNaN(valor) || valor < 0.50) {
        return Swal.fire("Error", "Valor ≥ 0.50.", "error");
      }

      $.ajax({
        url: 'guardar_ticket3.php',
        type: 'POST',
        dataType: 'json',
        data: { date2, loterias, number, valor, id_cifras: 2 }
      })
      .done(r => {
        if (r?.success) {
          refreshTicket3c();
        } else if (r?.error === "Cupo_no_disponible") {
          Swal.fire({
            icon: "warning",
            title: "Cupo insuficiente",
            html: `${r.mensaje || ''}<br><b>Disponible: $${r.cupo_restante || '0.00'}</b>`
          });
        } else {
          Swal.fire("Error", r?.message || "No se pudo guardar.", "error");
        }
      })
      .fail(xhr => Swal.fire("Error", xhr?.responseText || "Error de red.", "error"));
    }
    window.cargar3c = cargar3c;

    $tab.on('click','.btn-del3c',function(){
      const id=parseInt($(this).data('id'),10); 
      if(!id) return;
      Swal.fire({
        title:'Eliminar ítem',
        text:'¿Quitar del carrito?',
        icon:'warning',
        showCancelButton:true
      })
      .then(r=>{ 
        if(!r.isConfirmed) return; 
        $.post('ticket_delete.php',{id},function(resp){
          if(resp?.success) refreshTicket3c(); 
          else Swal.fire('Atención',resp?.message||'No se pudo eliminar.','warning');
        },'json').fail(xhr=>Swal.fire('Error',xhr?.responseText||'Error','error')); 
      });
    });

    function setProg3(i,t){ 
      const pct=t>0?Math.floor((i/t)*100):0; 
      $progBar3.css('width',pct+'%').text(pct+'%'); 
      $progTxt3.text(`Procesados ${i} de ${t}`); 
    }

    function endProg3(t){ 
      $progBar3.css('width','100%').text('100%'); 
      $progTxt3.text(`Completado: ${t} de ${t}`); 
      Swal.fire({icon:'success',title:'Completado',timer:1500,showConfirmButton:false})
        .then(()=>{ 
          $progBox3.hide(); 
          $btnAprob3.prop('disabled',false).text('Aprobar'); 
          refreshTicket3c(); 
        }); 
    }

    function popupBloq3(){ 
      Swal.fire("Atención","Habilita pop-ups para imprimir.","info")
        .then(()=>$btnAprob3.prop('disabled',false).text('Aprobar')); 
    }

    function startAprobar3c(){
      $btnAprob3.prop('disabled',true).text('Procesando...');

      $.getJSON('qr3/contar_tickets.php',{id_cifras:2}).done(function(resp){
        const ids=Array.isArray(resp?.ids)?resp.ids:[];
        if(!ids.length){
          $btnAprob3.prop('disabled',false).text('Aprobar');
          return Swal.fire('Advertencia','No hay tickets (3 cifras).','warning');
        }

        let i=0;
        $progBox3.show();
        setProg3(i,ids.length);

        (function loop(){
          if(i>=ids.length){
            endProg3(ids.length);
            return;
          }
          const id=ids[i];
          setProg3(i,ids.length);

          $.ajax({
            url:'qr3/index.php',
            method:'GET',
            dataType:'json',
            data:{id}
          })
          .done(function(r){
            if(typeof r==='string'){
              const s=r.replace(/^\uFEFF/,'').trim();
              if(/^<!doctype html|^<html/i.test(s)){ i++; return loop(); }
              try{ r=JSON.parse(s);}catch(e){ i++; return loop(); }
            }
            const html=(r&&typeof r.html==='string')?r.html.replace(/^\uFEFF/,'').trim():'';
            if(!r||!r.success||!html){ i++; return loop(); }

            let w=window.open('','','width=300,height=600');
            if(!w){ popupBloq3(); return; }

            w.document.open();
            w.document.write(`
              <html><head><meta charset="utf-8" /><title>Impresión</title>
              <style>
                body{font-family:Arial,sans-serif;font-size:12px;text-align:center;padding:10px}
                img{max-width:100%}
                hr{border:none;border-top:1px dashed #000;margin:10px 0}
              </style>
              </head><body onload="window.print()">${html}</body></html>`);
            w.document.close();
            setTimeout(()=>{
              try{w.close();}catch(e){}
              i++; loop();
            }, 500);
          })
          .fail(()=>{ i++; loop(); });
        })();
      })
      .fail(()=>{
        Swal.fire('Error','Error de red.','error');
        $btnAprob3.prop('disabled',false).text('Aprobar');
      });
    }

    window.aprobar3c = function(){
      if (dtTicket3c) {
        dtTicket3c.ajax.reload(function(){
          startAprobar3c();
        }, false);
      } else {
        startAprobar3c();
      }
    };

    function triggerInit3c(){ 
      if(!dtTicket3c) initDtTicket3c(); 
      cargarLoterias3c(); 
      cargarUltimos3c(); 
      cargarCopados3c(); 
    }
    window.triggerInit3c = triggerInit3c;
    $date3c.on('change', cargarLoterias3c);
  })(jQuery);
  </script>

  <!-- === Script de 4 cifras === -->
  <script>
  (function($){
    const $tab = $('#cuatro-cifras');
    const $date = $tab.find('#date2_4c');
    const $sel  = $tab.find('#loterias_4c');
    const $tbUlt = $tab.find('#tbUltimas_4c');
    const $tbCop = $tab.find('#tbCopados_4c');
    const $table = $tab.find('#ticket_4c');
    const $total = $tab.find('#total-value_4c');
    const $btnAprob = $tab.find('#save_4c');
    const $progBox = $tab.find('#progress-container_4c');
    const $progBar = $tab.find('#progress-bar_4c');
    const $progTxt = $tab.find('#progress-text_4c');

    let dt = null;

    function cargarLoterias4c(){
      const fecha = ($date.val()||'').trim();
      if(!fecha){ $sel.html("<option value=''>Seleccione fecha</option>"); return; }
      $.post('datos.php?Accion=GetLoterias',{fecha},(resp)=>$sel.html(resp))
        .fail(()=> $sel.html("<option value=''>Error</option>"));
    }

    function initDt(){
      if(dt){ dt.destroy(); dt=null; $table.find('tbody').empty(); }
      dt = $table.DataTable({
        ajax:{ 
          url:'ticket_list4c.php', 
          type:'POST', 
          data:{id_cifras:3},
          dataSrc:(j)=>{ 
            $total.text('$'+parseFloat(j?.total||0).toFixed(2)); 
            return j?.data||[]; 
          } 
        },
        processing:true, serverSide:false, searching:false, lengthChange:false, pageLength:10, responsive:true,
        columns:[
          {data:'loteria'},
          {data:'fecha'},
          {data:'numero',className:'text-center',render:(v)=>String(v??'').padStart(4,'0')},
          {data:'valor',className:'text-end',render:(v)=>'$'+(parseFloat(v||0)).toFixed(2)},
          {data:null,orderable:false,className:'text-center',
            render:(row)=>`<button class="btn btn-sm btn-outline-danger btn-del-4c" data-id="${row.id}"><i class="fa-solid fa-trash"></i></button>`}
        ],
        order:[[1,'asc']],
        language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"}
      });
    }

    function refresh(){ 
      if (dt) dt.ajax.reload(null,false); 
    }

    function cargarUltimos4c(){
      $.getJSON('obtener_numeros4.php',{id_cifras:3}).done(function(data){
        let html=""; 
        if(Array.isArray(data)&&data.length){
          data.forEach((r,i)=>{ 
            const nf=String(r.numero??'').replace(/\D/g,'').slice(-4).padStart(4,'0');
            if(i%3===0) html+="<tr>"; 
            html+=`<td><div class="text-center">
            <small class="text-muted" style="font-size:14px">${r.loteria||''}</small><br>
            <button class="btn btn-dark" style="font-size:30px">${nf}</button><br>
            <small class="text-muted" style="font-size:16px">${r.valor||''}</small></div></td>`;
            if(i%3===2) html+="</tr>"; 
          }); 
          if(data.length%3!==0) html+="</tr>";
        } else html="<tr><td colspan='3'>No hay números</td></tr>";
        $tbUlt.html(html);
      }).fail(()=> $tbUlt.html("<tr><td colspan='3'>Error</td></tr>"));
    }

    function cargarCopados4c(){
      $.getJSON('obtener_copados4.php',{id_cifras:3}).done(function(data){
        const arr=data?.numeros_superan_cupo||[]; 
        let html="";
        if(arr.length){ 
          arr.forEach((r,i)=>{ 
            const nf=String(r.numero??'').replace(/\D/g,'').slice(-4).padStart(4,'0');
            if(i%3===0) html+="<tr>"; 
            html+=`<td><div class="text-center">
            <button class="btn btn-dark" style="font-size:30px">${nf}</button><br><small class="text-muted">T4</small></div></td>`;
            if(i%3===2) html+="</tr>"; 
          }); 
          if(arr.length%3!==0) html+="</tr>";
        } else html="<tr><td colspan='3'>Sin copados</td></tr>";
        $tbCop.html(html);
      }).fail(()=> $tbCop.html("<tr><td colspan='3'>Error</td></tr>"));
    }

    function cargar4c(){
      const date2=($date.val()||'').trim(); 
      const loterias=($sel.val()||'').trim();
      const numberRaw=($('#number_4c').val()||'').trim(); 
      const valor=parseFloat(($('#valor_4c').val()||'').trim());
      if(date2<hoyEC()) return Swal.fire("Error","La fecha no puede ser menor que hoy.","error");
      const number=String(numberRaw).replace(/\D/g,'').slice(-4).padStart(4,'0'); 
      $('#number_4c').val(number);
      if(!date2||!loterias) return Swal.fire("Error","Completa los campos.","error");
      const n=parseInt(number,10); 
      if(isNaN(n)||n<0||n>9999) return Swal.fire("Error","Número 0000-9999.","error");
      if(isNaN(valor)||valor<0.50) return Swal.fire("Error","Valor ≥ 0.50.","error");
      $.ajax({
        url:'guardar_ticket4.php',
        type:'POST',
        dataType:'json',
        data:{date2,loterias,number,valor,id_cifras:3}
      })
      .done(r=>{ 
        if(r?.success){ 
          refresh(); 
        } else if(r?.error==="Cupo_no_disponible"){ 
          Swal.fire({
            icon:"warning",
            title:"Cupo insuficiente",
            html:`${r.mensaje||''}<br><b>Disponible: $${r.cupo_restante||'0.00'}</b>`
          }); 
        } else { 
          Swal.fire("Error",r?.message||"No se pudo guardar.","error"); 
        }
      })
      .fail(xhr=>Swal.fire("Error",xhr?.responseText||"Error de red.","error"));
    }
    window.cargar4c = cargar4c;

    $(document).on('click','.btn-del-4c',function(){
      const id=parseInt($(this).data('id'),10); 
      if(!id) return;
      Swal.fire({
        title:'Eliminar ítem',
        text:'¿Quitar del carrito?',
        icon:'warning',
        showCancelButton:true
      })
      .then(r=>{ 
        if(!r.isConfirmed) return; 
        $.post('ticket_delete.php',{id},function(resp){
          if(resp?.success) refresh(); 
          else Swal.fire('Atención',resp?.message||'No se pudo eliminar.','warning');
        },'json').fail(xhr=>Swal.fire('Error',xhr?.responseText||'Error','error')); 
      });
    });

    function setProg(i,t){ 
      const pct=t>0?Math.floor((i/t)*100):0; 
      $progBar.css('width',pct+'%').text(pct+'%'); 
      $progTxt.text(`Procesados ${i} de ${t}`); 
    }

    function endProg(t){ 
      $progBar.css('width','100%').text('100%'); 
      $progTxt.text(`Completado: ${t} de ${t}`); 
      Swal.fire({icon:'success',title:'Completado',timer:1500,showConfirmButton:false})
        .then(()=>{ 
          $progBox.hide(); 
          $btnAprob.prop('disabled',false).text('Aprobar'); 
          refresh(); 
        }); 
    }

    function popupBloq(){ 
      Swal.fire("Atención","Habilita pop-ups para imprimir.","info")
        .then(()=>$btnAprob.prop('disabled',false).text('Aprobar')); 
    }

    function startAprobar4c(){
      $btnAprob.prop('disabled',true).text('Procesando...');

      $.getJSON('qr4/contar_tickets.php',{id_cifras:3}).done(function(resp){
        const ids=Array.isArray(resp?.ids)?resp.ids:[];
        if(!ids.length){
          $btnAprob.prop('disabled',false).text('Aprobar');
          return Swal.fire('Advertencia','No hay tickets (4 cifras).','warning');
        }
        let i=0;
        $progBox.show();
        setProg(i,ids.length);

        (function loop(){
          if(i>=ids.length){
            endProg(ids.length);
            return;
          }
          const id=ids[i];
          setProg(i,ids.length);

          $.ajax({
            url:'qr4/index.php',
            method:'GET',
            dataType:'json',
            data:{id}
          })
          .done(function(r){
            if(typeof r==='string'){
              const s=r.replace(/^\uFEFF/,'').trim();
              if(/^<!doctype html|^<html/i.test(s)){ i++; return loop(); }
              try{ r=JSON.parse(s);}catch(e){ i++; return loop(); }
            }
            const html=(r&&typeof r.html==='string')?r.html.replace(/^\uFEFF/,'').trim():'';
            if(!r||!r.success||!html){ i++; return loop(); }

            let w=window.open('','','width=300,height=600');
            if(!w){ popupBloq(); return; }

            w.document.open();
            w.document.write(`
              <html><head><meta charset="utf-8" /><title>Impresión</title>
              <style>
                body{font-family:Arial,sans-serif;font-size:12px;text-align:center;padding:10px}
                img{max-width:100%}
                hr{border:none;border-top:1px dashed #000;margin:10px 0}
              </style>
              </head><body onload="window.print()">${html}</body></html>`);
            w.document.close();
            setTimeout(()=>{
              try{w.close();}catch(e){}
              i++; loop();
            }, 500);
          })
          .fail(()=>{ i++; loop(); });
        })();
      })
      .fail(()=>{
        Swal.fire('Error','Error de red.','error');
        $btnAprob.prop('disabled',false).text('Aprobar');
      });
    }

    window.aprobar4c = function(){
      if (dt) {
        dt.ajax.reload(function(){
          startAprobar4c();
        }, false);
      } else {
        startAprobar4c();
      }
    };

    function triggerInit(){ 
      if(!dt) initDt(); 
      cargarLoterias4c(); 
      cargarUltimos4c(); 
      cargarCopados4c(); 
    }
    window.triggerInit = triggerInit;
    $date.on('change', cargarLoterias4c);
  })(jQuery);
  </script>

  <!-- === Tabs recordadas + inicialización correcta al iniciar y al cambiar === -->
  <script>
  document.addEventListener("DOMContentLoaded", function () {
    const stored = localStorage.getItem("activeTab") || "#dos-cifras";
    const btn = document.querySelector(`[data-bs-target="${stored}"]`) || document.querySelector('[data-bs-target="#dos-cifras"]');
    if (btn) {
      new bootstrap.Tab(btn).show();
      setTimeout(() => {
        switch (btn.getAttribute('data-bs-target')) {
          case '#dos-cifras': if (typeof initTab2c === 'function') initTab2c(); break;
          case '#tres-cifras': if (typeof triggerInit3c === 'function') triggerInit3c(); break;
          case '#cuatro-cifras': if (typeof triggerInit === 'function') triggerInit(); break;
        }
      }, 150);
    }

    document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
      tab.addEventListener('shown.bs.tab', function () {
        const tgt = this.getAttribute("data-bs-target");
        localStorage.setItem("activeTab", tgt);
        switch (tgt) {
          case '#dos-cifras': if (typeof initTab2c === 'function') initTab2c(); break;
          case '#tres-cifras': if (typeof triggerInit3c === 'function') triggerInit3c(); break;
          case '#cuatro-cifras': if (typeof triggerInit === 'function') triggerInit(); break;
        }
      });
    });

    // Auto refresh de “últimos/copados” cada 30s (2 cifras)
    setInterval(()=>{
      if ($('#dos-cifras').hasClass('active')) { 
        cargarUltimos_2c(); 
        cargarCopados_2c(); 
      }
      // Si quieres puedes añadir refresco para 3c y 4c
      // if ($('#tres-cifras').hasClass('active')) { cargarUltimos3c(); cargarCopados3c(); }
      // if ($('#cuatro-cifras').hasClass('active')) { cargarUltimos4c(); cargarCopados4c(); }
    }, 30000);
  });
  </script>

</body>
</html>
