<?php
// views/pages/raspadita/raspaditas.php — SOLO INTERFAZ (todo backend en api/)
declare(strict_types=1);

session_start();
date_default_timezone_set('America/Guayaquil');

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

$idusuario = (int)$_SESSION['idusuario'];
$usuario   = htmlspecialchars((string)$_SESSION['usuario'], ENT_QUOTES, 'UTF-8');

require_once __DIR__ . '/../conex.php';
if (!isset($conn) || !$conn instanceof mysqli) { die("Error: No se pudo establecer la conexión a la base de datos."); }
mysqli_set_charset($conn, 'utf8mb4');
@mysqli_query($conn, "SET time_zone = '-05:00'");

// Permisos
$venta = 0; $pago = 0; $rifa = 0; $raspadita = 0;
$stmtu = mysqli_prepare($conn, "SELECT venta, pago, rifa, raspadita FROM tbr_usuario WHERE idusuario = ? LIMIT 1");
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'] ?? 0);
  $pago      = (int)($row['pago'] ?? 0);
  $rifa      = (int)($row['rifa'] ?? 0);
  $raspadita = (int)($row['raspadita'] ?? 0);
}
mysqli_stmt_close($stmtu);

if ($raspadita !== 1) die("Acceso denegado (raspadita no habilitado).");
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sistema · Raspaditas</title>
  <link rel="shortcut icon" href="../resources/img/crud.ico">

  <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.big{border-left:0;border-radius:0 8px 8px 0;padding:10px;font-size:1.5rem;}
    .chip{display:inline-block;background:#0dcaf0;color:#083a44;padding:.25rem .6rem;border-radius:999px;font-weight:700;}
    .card-title-mini{font-size:14px;text-transform:uppercase;letter-spacing:.4px;margin-bottom:0;}
    .table-sm th,.table-sm td{padding:.45rem .5rem;}
    .scan-input{font-size:1.15rem;}
    .kpi{border-radius:14px;}
    .card-kpi-click{cursor:pointer;}
    .card-kpi-click:hover{box-shadow:0 0 14px rgba(0,0,0,.08);}
  </style>
</head>

<body>
  <!-- Sidebar -->
  <nav class="sidebar" id="sidebar">
    <ul class="nav flex-column text-center w-100">
      <li class="nav-item">
        <a href="../dashboard.php" class="nav-link">
          <i class="fa fa-tachometer-alt"></i>
          <div class="text-uppercase" style="font-size:12px;">Dashboard</div>
        </a>
      </li>

      <?php if ($rifa === 1): ?>
        <?php if ($venta === 1): ?>
        <li class="nav-item">
          <a href="../ventas.php" class="nav-link">
            <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">
            <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</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</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</div></a>
        </li>
      <?php endif; ?>

      <?php if ($raspadita === 1): ?>
      <li class="nav-item">
        <a href="raspaditas.php" class="nav-link <?php echo basename($_SERVER['PHP_SELF'])=='raspaditas.php'?'active':''; ?>">
          <i class="fa-solid fa-ticket fa-2x"></i>
          <div class="text-uppercase" style="font-size:12px;">Raspaditas</div>
        </a>
      </li>
      <?php endif; ?>

      <li class="nav-item mt-2">
        <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</div>
        </a>
      </li>
    </ul>
  </nav>

  <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="fa-solid fa-ticket"></i> Módulo Raspaditas</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-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"></em>&nbsp;<span id="horaActual"></span></a></li>
          </ul>
        </div>
      </div>
    </nav>

    <ul class="nav nav-tabs" id="tabsRasp" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="tab-venta" data-bs-toggle="tab" data-bs-target="#pane-venta" type="button" role="tab">
          <i class="fa-solid fa-cart-shopping"></i> Venta
        </button>
      </li>

      <li class="nav-item" role="presentation">
        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-pagos" type="button">
          <i class="fa-solid fa-trophy"></i> Pagar premiadas
        </button>
      </li>

      <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-reportes" data-bs-toggle="tab" data-bs-target="#pane-reportes" type="button" role="tab">
          <i class="fa-solid fa-chart-column"></i> Reportes
        </button>
      </li>
    </ul>

    <div class="tab-content mt-3" id="tabsRaspContent">

      <!-- ====================== VENTA ====================== -->
      <div class="tab-pane fade show active" id="pane-venta" role="tabpanel">
        <div class="row g-3">
          <div class="col-12 col-lg-4">
            <div class="card border-primary">
              <div class="card-header bg-primary text-white">
                <div class="d-flex justify-content-between align-items-center">
                  <div>
                    <div class="card-title-mini mb-1">Producto</div>
                    <div class="fw-bold">Raspadita <span class="chip">$0.50</span></div>
                  </div>
                  <i class="fa-solid fa-ticket fa-2x"></i>
                </div>
              </div>
              <div class="card-body">
                <div class="mb-3">
                  <label class="form-label fw-bold">Código de serie</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="fa-solid fa-barcode fa-2x"></i></span>
                    <input id="serieVenta" class="form-control big" placeholder="Ej: A12B34C" autocomplete="off" />
                  </div>
                  <small class="text-muted">
                    ✅ Antes de agregar, el sistema valida en <b>tbr_raspadita</b> que el código esté asignado a tu usuario.
                  </small>
                </div>

                <div class="d-grid gap-2">
                  <button class="btn btn-success btn-lg" id="btnAddVenta">
                    <i class="fa-solid fa-plus"></i> Agregar
                  </button>
                  <button class="btn btn-outline-danger" id="btnClearVenta">
                    <i class="fa-solid fa-broom"></i> Vaciar carrito
                  </button>
                  <button class="btn btn-primary btn-lg" id="btnConfirmarVenta">
                    <i class="fa-solid fa-circle-check"></i> Confirmar venta
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div class="col-12 col-lg-8">
            <div class="card border-danger">
              <div class="card-header bg-danger text-white d-flex justify-content-between align-items-center">
                <div class="fw-bold"><i class="fa-solid fa-list"></i> Carrito de venta</div>
                <div class="fw-bold">Total: <span id="totalVenta">$0.00</span></div>
              </div>
              <div class="card-body">
                <div class="table-responsive">
                  <table id="dtVenta" class="table table-striped table-sm w-100">
                    <thead>
                      <tr>
                        <th>Fecha</th>
                        <th>Código</th>
                        <th class="text-end">Valor</th>
                        <th class="text-center">Acción</th>
                      </tr>
                    </thead>
                    <tbody></tbody>
                  </table>
                </div>
                <small class="text-muted">*Carrito por sesión (en API). Confirmar venta guarda definitivo.</small>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- ====================== PAGO PREMIO ====================== -->
      <div class="tab-pane fade" id="tab-pagos">
        <div class="row g-3">
          <div class="col-12 col-lg-5">
            <div class="card kpi">
              <div class="card-body">
                <h6 class="mb-2"><i class="fa-solid fa-trophy"></i> Pago de raspaditas premiadas</h6>

                <label class="form-label">Escanee código</label>
                <input id="paySerie" class="form-control scan-input" placeholder="Escanee aquí…" autocomplete="off">

                <label class="form-label mt-2">Observación (opcional)</label>
                <input id="payObs" class="form-control" placeholder="Ej: Pagado en ventanilla">

                <div class="d-grid mt-3">
                  <button id="btnPagarPremio" class="btn btn-success" type="button" disabled onclick="pagarPremiada()">
                    <i class="fa-solid fa-hand-holding-dollar"></i> Registrar pago
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div class="col-12 col-lg-7">
            <div class="card">
              <div class="card-body">
                <h6 class="mb-2"><i class="fa-solid fa-circle-info"></i> Información</h6>
                <div id="payInfo" class="alert alert-light border mb-0">
                  Escanee un código para ver datos…
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- ====================== REPORTES ====================== -->
      <div class="tab-pane fade" id="pane-reportes" role="tabpanel">
        <div class="card border-info">
          <div class="card-header bg-info text-white">
            <div class="fw-bold"><i class="fa-solid fa-chart-column"></i> Reportes</div>
          </div>

          <div class="card-body">
            <div class="row g-3 align-items-end">
              <div class="col-12 col-md-4">
                <label class="form-label fw-bold">Desde</label>
                <input id="repDesde" type="date" class="form-control">
              </div>
              <div class="col-12 col-md-4">
                <label class="form-label fw-bold">Hasta</label>
                <input id="repHasta" type="date" class="form-control">
              </div>
              <div class="col-12 col-md-4 d-grid">
                <button class="btn btn-primary btn-lg" id="btnRepBuscar">
                  <i class="fa-solid fa-magnifying-glass"></i> Buscar
                </button>
              </div>
            </div>

            <hr>

            <div class="row g-3">
              <!-- Vendidas -->
              <div class="col-12 col-lg-4">
                <div class="card border-success h-100 card-kpi-click" id="cardRepVentas" role="button">
                  <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                      <div>
                        <div class="card-title-mini text-muted">Raspaditas vendidas</div>
                        <div class="fs-4 fw-bold" id="repVentasCant">0</div>
                        <div class="text-muted">Total: <span class="fw-bold" id="repVentasTotal">$0.00</span></div>
                      </div>
                      <i class="fa-solid fa-cart-shopping fa-2x text-success"></i>
                    </div>
                    <div class="mt-2 text-muted" style="font-size:12px;">Click para ver detalle</div>
                  </div>
                </div>
              </div>

              <!-- Pagos -->
              <div class="col-12 col-lg-4">
                <div class="card border-warning h-100 card-kpi-click" id="cardRepPagos" role="button">
                  <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                      <div>
                        <div class="card-title-mini text-muted">Premios pagados</div>
                        <div class="fs-4 fw-bold" id="repPagosCant">0</div>
                        <div class="text-muted">Total: <span class="fw-bold" id="repPagosTotal">$0.00</span></div>
                      </div>
                      <i class="fa-solid fa-trophy fa-2x text-warning"></i>
                    </div>
                    <div class="mt-2 text-muted" style="font-size:12px;">Click para ver detalle</div>
                  </div>
                </div>
              </div>

              <!-- Saldo -->
              <div class="col-12 col-lg-4">
                <div class="card border-dark h-100">
                  <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                      <div>
                        <div class="card-title-mini text-muted">Saldo</div>
                        <div class="fs-3 fw-bold" id="repSaldo">$0.00</div>
                        <div class="text-muted" style="font-size:12px;">Ventas − Premios pagados</div>
                      </div>
                      <i class="fa-solid fa-wallet fa-2x text-dark"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="alert alert-light border mt-3 mb-0">
              💡 Si no seleccionas fechas, el reporte toma <b>HOY</b>.
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- Modal detalle reportes -->
  <div class="modal fade" id="modalRepDetalle" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="repDetalleTitle">Detalle</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
        </div>

        <div class="modal-body">
          <div class="table-responsive">
            <table id="dtRepDetalle" class="table table-striped table-sm w-100">
              <thead></thead>
              <tbody></tbody>
            </table>
          </div>
        </div>

        <div class="modal-footer">
          <small class="text-muted me-auto" id="repDetalleRango"></small>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
        </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>
  function money(n){ const x = parseFloat(n || 0); return '$' + x.toFixed(2); }

  // 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('/rifa_prueba/views/pages/raspadita/login.php',{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:new URLSearchParams({boton:'cerrar'})
      })
      .then(()=>location.href='/rifa_prueba/views/pages/raspadita/login.php')
      .catch(()=>location.href='/rifa_prueba/views/pages/raspadita/login.php')
      .finally(()=>loader.remove());
    });
  }

  // ===================== HELPERS (escapeHtml + postJson) =====================
  function escapeHtml(s){
    return String(s ?? '').replace(/[&<>"'`=\/]/g, function(c){
      return ({
        '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;',
        '`':'&#x60;','=':'&#x3D;','/':'&#x2F;'
      })[c] || c;
    });
  }

  async function postJson(url, data){
    const res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type':'application/json; charset=utf-8' },
      body: JSON.stringify(data || {})
    });

    const txt = await res.text();
    let j = null;
    try { j = txt ? JSON.parse(txt) : null; } catch(e){}

    if(!res.ok){
      const msg = (j && (j.message || j.error)) ? (j.message || j.error) : (txt || `HTTP ${res.status}`);
      const err = new Error(msg);
      err.status = res.status;
      err.payload = j;
      throw err;
    }
    return j ?? {};
  }

  // ====================== API URLS ======================
  const API = {
    cart_list:      'api/venta_cart_list.php',
    cart_add:       'api/venta_cart_add.php',
    cart_del:       'api/venta_cart_delete.php',
    cart_clear:     'api/venta_cart_clear.php',
    venta_confirm:  'api/venta_confirmar.php',
  };
  </script>

  <script>
  /* ====================== VENTA ====================== */
  let dtVenta = null;

  function initDtVenta(){
    dtVenta = $('#dtVenta').DataTable({
      data: [],
      columns: [
        { title:'Fecha', data:'fecha' },
        { title:'Código', data:'serie' },
        { title:'Valor', data:'valor', className:'text-end', render:(v)=>money(v) },
        { title:'Acción', data:null, orderable:false, className:'text-center',
          render:(row)=> `<button class="btn btn-sm btn-outline-danger btnDelVenta" data-id="${row.id}">
                            <i class="fa-solid fa-trash"></i>
                          </button>`
        }
      ],
      searching:false,
      lengthChange:false,
      pageLength:10,
      responsive:true,
      language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"}
    });
  }

  function loadVenta(){
    return $.getJSON(API.cart_list).done(function(r){
      const arr = Array.isArray(r?.data) ? r.data : [];
      dtVenta.clear().rows.add(arr).draw(false);
      $('#totalVenta').text(money(r?.total || 0));
    });
  }

  function addVenta(){
    const serie = ($('#serieVenta').val() || '').trim();
    if(!serie) return Swal.fire('Error','Ingrese el código de serie.','error');

    $.ajax({
      url: API.cart_add,
      method: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify({ serie })
    })
    .done(function(){
      $('#serieVenta').val('').focus();
      loadVenta();
    })
    .fail(function(xhr){
      console.log('ADD VENTA ERROR:', xhr.status, xhr.responseText);
      let msg = 'No se pudo agregar.';
      try{ msg = xhr.responseJSON?.message || msg; }catch(e){}
      Swal.fire('Atención', msg, 'warning');
    });
  }

  function delVenta(id){
    $.ajax({
      url: API.cart_del,
      method: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify({ id })
    })
    .done(()=> loadVenta())
    .fail(function(xhr){
      console.log('DEL VENTA ERROR:', xhr.status, xhr.responseText);
      let msg = 'No se pudo eliminar.';
      try{ msg = xhr.responseJSON?.message || msg; }catch(e){}
      Swal.fire('Error', msg, 'error');
    });
  }

  function clearVenta(){
    $.ajax({
      url: API.cart_clear,
      method: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify({})
    })
    .done(()=> loadVenta())
    .fail(function(xhr){
      console.log('CLEAR VENTA ERROR:', xhr.status, xhr.responseText);
      let msg = 'No se pudo vaciar.';
      try{ msg = xhr.responseJSON?.message || msg; }catch(e){}
      Swal.fire('Error', msg, 'error');
    });
  }

  function confirmarVenta(){
    Swal.fire({
      title:'Confirmar venta',
      text:'Esto guardará la venta y dejará los códigos como vendidos definitivos.',
      icon:'question',
      showCancelButton:true,
      confirmButtonText:'Sí, confirmar',
      cancelButtonText:'Cancelar',
      input: 'text',
      inputLabel: 'Observación (opcional)',
      inputPlaceholder: 'Ej: Venta mostrador...'
    }).then((r)=>{
      if(!r.isConfirmed) return;

      $.ajax({
        url: API.venta_confirm,
        method: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: JSON.stringify({ observacion: r.value || '' })
      })
      .done(function(res){
        Swal.fire('Listo', res.message + `\nVenta #${res.id_venta}\nTotal: ${money(res.total)}`, 'success');
        loadVenta();
      })
      .fail(function(xhr){
        console.log('CONFIRM VENTA ERROR:', xhr.status, xhr.responseText);
        let msg = 'No se pudo confirmar.';
        try{ msg = xhr.responseJSON?.message || msg; }catch(e){}
        Swal.fire('Atención', msg, 'warning');
      });
    });
  }
  </script>

  <!-- ===================== PAGOS ===================== -->
  <script>
  const API_PREMIO_INFO  = 'api/raspadita_premio_info.php';
  const API_PREMIO_PAGAR = 'api/raspadita_premio_pagar.php';

  let premioActual = null;

  function setPayInfo(html, ok=false){
    const box = document.getElementById('payInfo');
    if(!box) return;
    box.className = 'alert ' + (ok ? 'alert-success' : 'alert-light border');
    box.innerHTML = html;
  }

  async function consultarPremiada(){
    const inp = document.getElementById('paySerie');
    const btn = document.getElementById('btnPagarPremio');
    const codigo = (inp?.value || '').trim().replace(/\s+/g,'');

    premioActual = null;
    if(btn) btn.disabled = true;

    if(!codigo){
      setPayInfo('Escanee un código para ver datos…', false);
      return;
    }

    try{
      const j = await postJson(API_PREMIO_INFO, { codigo });
      premioActual = j.data || null;

      const cad = (premioActual?.cadena || []).map(x=>`<li>${escapeHtml(x)}</li>`).join('');
      const pag = premioActual?.ya_pagada
        ? `<div class="mt-2"><span class="badge bg-danger">YA PAGADA</span>
             <div class="text-muted" style="font-size:12px;">
               ${escapeHtml((premioActual?.pago?.fecha_hora)||'')} · IP ${escapeHtml((premioActual?.pago?.ip)||'')}
             </div>
           </div>`
        : `<div class="mt-2"><span class="badge bg-success">LISTA PARA PAGAR</span></div>`;

      setPayInfo(`
        <div><b>Código:</b> ${escapeHtml(premioActual?.codigo || '')}</div>
        <div><b>Premio:</b> $${Number(premioActual?.premio||0).toFixed(2)}</div>
        <div><b>Fecha:</b> ${escapeHtml(premioActual?.fecha_hora || '')}</div>
        <hr class="my-2">
        <div class="fw-bold mb-1">Recorrido</div>
        <ul class="mb-2">${cad || '<li>—</li>'}</ul>
        ${pag}
      `, !premioActual?.ya_pagada);

      if(btn) btn.disabled = !!premioActual?.ya_pagada;

    }catch(e){
      // 404 aquí es “Código no existe” (tu API lo hace así)
      const msg = e.message || 'No se pudo validar';
      setPayInfo(`<b>Atención:</b> ${escapeHtml(msg)}`, false);
      if(btn) btn.disabled = true;
      premioActual = null;
    }
  }

  window.pagarPremiada = async function pagarPremiada(){
    const inp = document.getElementById('paySerie');
    const obs = document.getElementById('payObs');
    const btn = document.getElementById('btnPagarPremio');

    const codigo = (inp?.value || '').trim().replace(/\s+/g,'');
    const observacion = (obs?.value || '').trim();

    if(!codigo) return Swal.fire('Atención','Escanee un código.','warning');
    if(!premioActual || premioActual.codigo !== codigo){
      await consultarPremiada();
      if(!premioActual || premioActual.codigo !== codigo) return;
    }
    if(premioActual.ya_pagada) return Swal.fire('Atención','Esta premiada ya fue pagada.','warning');

    const r = await Swal.fire({
      title: 'Confirmar pago',
      html: `Vas a registrar el pago del código:<br><b>${escapeHtml(codigo)}</b><br>Premio: <b>$${Number(premioActual.premio||0).toFixed(2)}</b>`,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Sí, registrar pago',
      cancelButtonText: 'Cancelar'
    });
    if(!r.isConfirmed) return;

    try{
      if(btn) btn.disabled = true;

      const j = await postJson(API_PREMIO_PAGAR, {
        codigo,
        observacion,
        id_admin: (window.ID_ADMIN || 0)
      });

      Swal.fire('OK', j.message || 'Pago registrado', 'success');

      premioActual = null;
      if(inp){ inp.value=''; inp.focus(); }
      if(obs) obs.value='';
      setPayInfo('Pago registrado ✅. Escanee otro código…', true);

    }catch(e){
      Swal.fire('Error', e.message || 'No se pudo registrar', 'error');
    }finally{
      if(btn) btn.disabled = true;
    }
  };

  document.addEventListener('DOMContentLoaded', ()=>{
    const inp = document.getElementById('paySerie');
    if(inp){
      // recomendado para scanner: consulta al Enter
      inp.addEventListener('keydown', (ev)=>{
        if(ev.key === 'Enter'){
          ev.preventDefault();
          consultarPremiada();
        }
      });
    }
  });
  </script>

  <!-- ===================== REPORTES ===================== -->
  <script>
  const API_REP_RESUMEN = 'api/rasp_report_resumen.php';
  const API_REP_LIST    = 'api/rasp_report_list.php';

  let dtRep = null;
  let modalRep = null;

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

  function repGetRange(){
    const desde = ($('#repDesde').val() || '').trim();
    const hasta = ($('#repHasta').val() || '').trim();
    if(!desde && !hasta){
      const hoy = todayYmd();
      return {desde:hoy, hasta:hoy};
    }
    return {desde, hasta};
  }

  function repInitDt(){
    dtRep = $('#dtRepDetalle').DataTable({
      data: [],
      columns: [],
      searching: true,
      lengthChange: false,
      pageLength: 10,
      responsive: true,
      order: [],
      language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"}
    });
  }

  function repSetColumns(tipo){
    dtRep.clear().destroy();

    let cols = [];
    let thead = '';
    if(tipo === 'ventas'){
      cols = [
        { title:'Fecha', data:'fecha' },
        { title:'Código', data:'codigo' },
        { title:'Valor', data:'valor', className:'text-end', render:(v)=>money(v) },
        { title:'#Venta', data:'id_venta', className:'text-end' }
      ];
      thead = '<tr><th>Fecha</th><th>Código</th><th class="text-end">Valor</th><th class="text-end">#Venta</th></tr>';
    }else{
      cols = [
        { title:'Fecha', data:'fecha' },
        { title:'Código', data:'codigo' },
        { title:'Premio', data:'premio', className:'text-end', render:(v)=>money(v) },
        { title:'Observación', data:'observacion' },
        { title:'IP', data:'ip' }
      ];
      thead = '<tr><th>Fecha</th><th>Código</th><th class="text-end">Premio</th><th>Observación</th><th>IP</th></tr>';
    }

    $('#dtRepDetalle thead').html(thead);

    dtRep = $('#dtRepDetalle').DataTable({
      data: [],
      columns: cols,
      searching: true,
      lengthChange: false,
      pageLength: 10,
      responsive: true,
      order: [],
      language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"}
    });
  }

  async function repCargarResumen(){
    const {desde, hasta} = repGetRange();

    try{
      const j = await postJson(API_REP_RESUMEN, { desde, hasta });
      const d = j.data || {};

      $('#repVentasCant').text(String(d.ventas?.cantidad ?? 0));
      $('#repVentasTotal').text(money(d.ventas?.total ?? 0));

      $('#repPagosCant').text(String(d.pagos?.cantidad ?? 0));
      $('#repPagosTotal').text(money(d.pagos?.total ?? 0));

      $('#repSaldo').text(money(d.saldo ?? 0));
    }catch(e){
      Swal.fire('Error', e.message || 'No se pudo cargar el resumen', 'error');
    }
  }

  async function repAbrirDetalle(tipo){
    const {desde, hasta} = repGetRange();

    if(!modalRep){
      const el = document.getElementById('modalRepDetalle');
      modalRep = new bootstrap.Modal(el);
    }

    document.getElementById('repDetalleTitle').textContent =
      (tipo === 'ventas') ? 'Detalle · Raspaditas vendidas' : 'Detalle · Premios pagados';

    document.getElementById('repDetalleRango').textContent = `Rango: ${desde} a ${hasta}`;

    repSetColumns(tipo);

    try{
      const j = await postJson(API_REP_LIST, { tipo, desde, hasta });
      const arr = Array.isArray(j.data) ? j.data : [];
      dtRep.clear().rows.add(arr).draw(false);
      modalRep.show();
    }catch(e){
      Swal.fire('Error', e.message || 'No se pudo cargar el detalle', 'error');
    }
  }

  /* ====================== INIT ====================== */
  document.addEventListener('DOMContentLoaded', function(){
    // Venta
    initDtVenta();
    loadVenta();

    $('#btnAddVenta').on('click', addVenta);
    $('#btnConfirmarVenta').on('click', confirmarVenta);

    $('#btnClearVenta').on('click', function(){
      Swal.fire({
        title:'Vaciar carrito',
        text:'¿Deseas eliminar todos los códigos del carrito?',
        icon:'warning',
        showCancelButton:true,
        confirmButtonText:'Sí, vaciar',
        cancelButtonText:'Cancelar'
      }).then(r=>{ if(r.isConfirmed) clearVenta(); });
    });

    $('#serieVenta').on('keydown', function(e){
      if(e.key === 'Enter'){ e.preventDefault(); addVenta(); }
    });

    $(document).on('click', '.btnDelVenta', function(){
      const id = parseInt($(this).data('id'), 10);
      if(!id) return;
      Swal.fire({
        title:'Eliminar',
        text:'¿Quitar este código del carrito?',
        icon:'warning',
        showCancelButton:true,
        confirmButtonText:'Sí, eliminar',
        cancelButtonText:'Cancelar'
      }).then(r=>{ if(r.isConfirmed) delVenta(id); });
    });

    // Reportes
    repInitDt();
    const hoy = todayYmd();
    if(!$('#repDesde').val()) $('#repDesde').val(hoy);
    if(!$('#repHasta').val()) $('#repHasta').val(hoy);

    repCargarResumen();
    $('#btnRepBuscar').on('click', repCargarResumen);

    $('#cardRepVentas').on('click', ()=> repAbrirDetalle('ventas'));
    $('#cardRepPagos').on('click',  ()=> repAbrirDetalle('pagos'));
  });
  </script>

</body>
</html>