<?php
// views/pages/raspadita/admin.php  — UI ADMIN (sin backend aquí, todo por APIs)
declare(strict_types=1);

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

require_once __DIR__ . '/../conex.php';
$db = $conn ?? null;
if (!$db instanceof mysqli) { http_response_code(500); die("Sin conexión BD"); }
mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone = '-05:00'");

// ==== Seguridad / sesión ====
if (!isset($_SESSION['idusuario'], $_SESSION['usuario'])) {
  header("Location: ../raspadita/login.php"); exit;
}
$idusuario = (int)$_SESSION['idusuario'];
$usuario   = htmlspecialchars((string)$_SESSION['usuario'], ENT_QUOTES, 'UTF-8');

// ==== Permisos: tbr_usuario(raspadita) ====
$raspPerm = 0;
$stmt = mysqli_prepare($db, "SELECT COALESCE(raspadita,0) raspadita FROM tbr_usuario WHERE idusuario=? LIMIT 1");
mysqli_stmt_bind_param($stmt, "i", $idusuario);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($res)) $raspPerm = (int)$row['raspadita'];
mysqli_stmt_close($stmt);
if ($raspPerm !== 1) { http_response_code(403); die("Acceso denegado"); }

// (opcional) CSRF
if (!isset($_SESSION['csrf'])) {
  $_SESSION['csrf'] = bin2hex(random_bytes(16));
}
$csrf = (string)$_SESSION['csrf'];
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>ADMIN · Raspaditas</title>

  <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">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@1.5.2/dist/select2-bootstrap4.min.css" rel="stylesheet">

  <style>
    body{background:#f4f6f9;}
    .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;}}
    .scan-input{font-size:1.6rem;font-weight:700;letter-spacing:.5px;}
    .badge-soft{background:rgba(23,162,184,.15);color:#0b7285;border:1px solid rgba(23,162,184,.35);}
    .kpi{border-radius:14px;}
    .kpi .num{font-size:1.4rem;font-weight:800;}
    .table-sm th,.table-sm td{padding:.45rem .5rem;}
  </style>
</head>
<body>

<nav class="sidebar" id="sidebar">
  <?php $active = 'admin'; include __DIR__ . '/menu_raspadita.php'; ?>
</nav>

<div class="main-content p-2 p-md-3">
  <nav class="navbar navbar-expand-lg navbar-light bg-light rounded-3 mb-3">
    <div class="container-fluid">
      <button class="navbar-toggler" type="button" onclick="document.getElementById('sidebar').classList.toggle('show')">
        <span class="navbar-toggler-icon"></span>
      </button>
      <span class="navbar-brand"><i class="fa-solid fa-user-shield"></i> ADMIN Raspaditas</span>
      <div class="ms-auto d-flex gap-2 align-items-center">
        <span class="badge badge-soft px-3 py-2"><i class="fa fa-user"></i> <?= $usuario ?></span>
        <span class="badge badge-soft px-3 py-2"><i class="fa fa-clock"></i> <span id="hora"></span></span>
      </div>
    </div>
  </nav>

  <!-- ✅ Tabs -->
  <ul class="nav nav-tabs" id="adminTabs" role="tablist">

    <!-- ✅ ASIGNAR A COORDINADOR -->
    <li class="nav-item" role="presentation">
      <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-coordinador" type="button">
        <i class="fa-solid fa-user-tie"></i> Asignar a Coordinador
      </button>
    </li>

    <!-- ASIGNAR A PUNTO -->
    <li class="nav-item" role="presentation">
      <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-asignar" type="button">
        <i class="fa-solid fa-location-dot"></i> Asignar a punto
      </button>
    </li>

    <!-- ENTREGAR -->
    <li class="nav-item" role="presentation">
      <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-entregar" type="button">
        <i class="fa-solid fa-people-carry-box"></i> Entrega a canillitas
      </button>
    </li>

    <!-- ROBO -->
    <li class="nav-item" role="presentation">
      <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-robo" type="button">
        <i class="fa-solid fa-ban"></i> Robo / Bloqueo
      </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>


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

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

    <!-- ✅ ASIGNAR A COORDINADOR -->
    <div class="tab-pane fade show active" id="tab-coordinador">
      <div class="row g-3">

        <div class="col-12 col-lg-4">
          <div class="card kpi">
            <div class="card-body">
              <h6 class="mb-2"><i class="fa-solid fa-user-tie"></i> Asignar por escaneo</h6>

              <label class="form-label">Coordinador</label>
              <select id="selCoordinador" class="form-select mb-2"></select>

              <div class="row g-2 align-items-end">
                <div class="col-md-9">
                  <label class="form-label">Escanee código de serie</label>
                  <input id="coordSerie" class="form-control scan-input" placeholder="Escanee aquí…" autocomplete="off">
                </div>

                <div class="col-md-3">
                  <label class="form-label">Premio ($)</label>
                  <input id="ganPremio" type="number" step="0.01" min="0" class="form-control scan-input" placeholder="0.00">
                </div>
              </div>

              <div class="d-grid mt-3">
                <button class="btn btn-dark" id="btnCoordSave" onclick="asignarCoordinador()">
                  <i class="fa-solid fa-floppy-disk"></i> Registrar asignación
                </button>
              </div>

              <small class="text-muted d-block mt-2">
                Se mantiene Coordinador seleccionado; solo se limpia el código de serie.
              </small>
            </div>
          </div>
        </div>

        <div class="col-12 col-lg-8">
          <div class="card">
            <div class="card-body">
              <h6 class="mb-3"><i class="fa-solid fa-list-check"></i> Últimas asignaciones (sesión)</h6>

              <div class="table-responsive">
                <table id="tbCoord" class="table table-sm table-striped w-100">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>Serie</th>
                      <th>Coordinador</th>
                      <th>Resultado</th>
                      <th>Hora</th>
                      <th class="text-end">Acción</th>
                    </tr>
                  </thead>
                  <tbody></tbody>
                </table>
              </div>

              <!-- ✅ RESUMEN (COORDINADOR) + DESCUENTO -->
              <div class="row g-2 mt-2">
                <div class="col-6 col-md-3">
                  <div class="alert alert-secondary kpi mb-0 py-2 px-3">
                    <div class="text-muted" style="font-size:12px;">Total raspaditas (OK)</div>
                    <div class="num" id="kCoordCant">0</div>
                  </div>
                </div>

                <div class="col-6 col-md-3">
                  <div class="alert alert-light kpi mb-0 py-2 px-3 border">
                    <div class="text-muted" style="font-size:12px;">Subtotal</div>
                    <div class="num" id="kCoordSub">$0.00</div>
                  </div>
                </div>

                <div class="col-6 col-md-3">
                  <label class="form-label mb-1 fw-bold">Descuento (%)</label>
                  <input type="number" id="coordDesc" class="form-control text-end" value="0" min="0" max="100" step="0.01">
                  <small class="text-muted">0 a 100</small>
                </div>

                <div class="col-6 col-md-3">
                  <div class="alert alert-success kpi mb-0 py-2 px-3">
                    <div class="text-muted" style="font-size:12px;">Total a pagar</div>
                    <div class="num" id="kCoordTotal">$0.00</div>
                    <small class="text-muted d-block" id="kCoordDescMoney">Descuento: $0.00</small>
                    <!-- botón cobro se inyecta por JS -->
                  </div>
                </div>
              </div>
              <!-- ✅ FIN RESUMEN -->

              <div class="text-end mt-2">
                <button class="btn btn-outline-secondary btn-sm" onclick="clearCoordLog()">
                  <i class="fa-solid fa-eraser"></i> Limpiar lista
                </button>
              </div>

              <small class="text-muted d-block mt-2">
                Eliminar asignación llama a: <b>api/raspadita_delete_coord.php</b> (POST: id/codigo/id_coordinador)
              </small>
            </div>
          </div>
        </div>

      </div>
    </div>

    <!-- ASIGNAR A PUNTO VENTA-->
    <div class="tab-pane fade" id="tab-asignar">
      <div class="row g-3">
        <div class="col-12 col-lg-4">
          <div class="card kpi">
            <div class="card-body">
              <h6 class="mb-2"><i class="fa-solid fa-location-dot"></i> Asignar por escaneo</h6>

              <label class="form-label">Punto de venta</label>
              <select id="asigPunto" class="form-select mb-2"></select>

              <div class="row g-2 align-items-end">
                <div class="col-md-9">
                  <label class="form-label">Escanee código de serie</label>
                  <input id="asigSerie" class="form-control scan-input" placeholder="Escanee aquí…" autocomplete="off">
                </div>

                <div class="col-md-3">
                  <label class="form-label">Premio ($)</label>
                  <input id="ganPremio_p" type="number" step="0.01" min="0" class="form-control scan-input" placeholder="0.00" value="0.00">
                </div>
              </div>

              <div class="d-grid mt-3">
                <button class="btn btn-primary" onclick="asignarSerie()">
                  <i class="fa-solid fa-floppy-disk"></i> Registrar asignación
                </button>
              </div>

              <small class="text-muted d-block mt-2">
                Se mantiene Punto seleccionado; solo se limpia el código de serie.
              </small>
            </div>
          </div>
        </div>

        <div class="col-12 col-lg-8">
          <div class="card">
            <div class="card-body">
              <h6 class="mb-3"><i class="fa-solid fa-list-check"></i> Últimas asignaciones (sesión)</h6>
              <div class="table-responsive">
                <table id="tbAsig" class="table table-sm table-striped w-100">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>Serie</th>
                      <th>Punto</th>
                      <th>Resultado</th>
                      <th>Hora</th>
                      <th class="text-end">Acción</th>
                    </tr>
                  </thead>
                  <tbody></tbody>
                </table>
              </div>

              <!-- ✅ RESUMEN (PUNTO DE VENTA) + DESCUENTO -->
              <div class="row g-2 mt-2">
                <div class="col-6 col-md-3">
                  <div class="alert alert-secondary kpi mb-0 py-2 px-3">
                    <div class="text-muted" style="font-size:12px;">Total raspaditas (OK)</div>
                    <div class="num" id="kpvCant">0</div>
                  </div>
                </div>

                <div class="col-6 col-md-3">
                  <div class="alert alert-light kpi mb-0 py-2 px-3 border">
                    <div class="text-muted" style="font-size:12px;">Subtotal</div>
                    <div class="num" id="kpvSub">$0.00</div>
                  </div>
                </div>

                <div class="col-6 col-md-3">
                  <label class="form-label mb-1 fw-bold">Descuento (%)</label>
                  <input type="number" id="pvDesc" class="form-control text-end" value="0" min="0" max="100" step="0.01">
                  <small class="text-muted">0 a 100</small>
                </div>

                <div class="col-6 col-md-3">
                  <div class="alert alert-success kpi mb-0 py-2 px-3">
                    <div class="text-muted" style="font-size:12px;">Total a pagar</div>
                    <div class="num" id="kpvTotal">$0.00</div>
                    <small class="text-muted d-block" id="kpvDescMoney">Descuento: $0.00</small>

                    <!-- Cobro Punto -->
                    <button id="btnPVCobro" type="button" class="btn btn-dark btn-sm mt-2 w-100 d-none" onclick="abrirVentanaCobroPV()">
                      <i class="fa-solid fa-cash-register"></i> Cobro <span class="ms-1" id="btnPVCobroTotal">$0.00</span>
                    </button>
                  </div>
                </div>
              </div>
              <!-- ✅ FIN RESUMEN -->

              <div class="text-end mt-2">
                <button class="btn btn-outline-secondary btn-sm" onclick="clearLog('asig')">
                  <i class="fa-solid fa-eraser"></i> Limpiar lista
                </button>
              </div>

            </div>
          </div>
        </div>

      </div>
    </div>

    <!-- ENTREGAR -->
    <div class="tab-pane fade" id="tab-entregar">
      <div class="row g-3">
        <div class="col-12 col-lg-4">
          <div class="card kpi">
            <div class="card-body">
              <h6 class="mb-2"><i class="fa-solid fa-people-carry-box"></i> Entregar por escaneo</h6>

              <label class="form-label">Canillita</label>
              <select id="entCan" class="form-select mb-2"></select>

              <div class="row g-2 align-items-end">
                <div class="col-md-9">
                  <label class="form-label">Escanee código de serie</label>
                  <input id="entSerie" class="form-control scan-input" placeholder="Escanee aquí…" autocomplete="off">
                </div>

                <div class="col-md-3">
                  <label class="form-label">Premio ($)</label>
                  <input id="entPremio" type="number" step="0.01" min="0" class="form-control scan-input" placeholder="0.00" value="0.00">
                </div>
              </div>

              <div class="d-grid mt-3">
                <button class="btn btn-success" onclick="entregarSerie()">
                  <i class="fa-solid fa-check"></i> Registrar entrega
                </button>
              </div>

              <div class="alert alert-info mt-3 mb-0">
                <b>Total entregadas (sesión):</b> <span id="totEntregadas">0</span>
              </div>
            </div>
          </div>
        </div>

        <div class="col-12 col-lg-8">
          <div class="card">
            <div class="card-body">
              <h6 class="mb-3"><i class="fa-solid fa-list-check"></i> Últimas entregas (sesión)</h6>

              <div class="table-responsive">
                <table id="tbEnt" class="table table-sm table-striped w-100">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>Serie</th>
                      <th>Canillita</th>
                      <th>Resultado</th>
                      <th>Hora</th>
                      <th class="text-end">Acción</th>
                    </tr>
                  </thead>
                  <tbody></tbody>
                </table>
              </div>

              <!-- ✅ RESUMEN (ENTREGA) + DESCUENTO -->
              <div class="row g-2 mt-2">
                <div class="col-6 col-md-3">
                  <div class="alert alert-secondary kpi mb-0 py-2 px-3">
                    <div class="text-muted" style="font-size:12px;">Total raspaditas (OK)</div>
                    <div class="num" id="entCant">0</div>
                  </div>
                </div>

                <div class="col-6 col-md-3">
                  <div class="alert alert-light kpi mb-0 py-2 px-3 border">
                    <div class="text-muted" style="font-size:12px;">Subtotal</div>
                    <div class="num" id="entSub">$0.00</div>
                  </div>
                </div>

                <div class="col-6 col-md-3">
                  <label class="form-label mb-1 fw-bold">Descuento (%)</label>
                  <input type="number" id="entDesc" class="form-control text-end" value="0" min="0" max="100" step="0.01">
                  <small class="text-muted">0 a 100</small>
                </div>

                <div class="col-6 col-md-3">
                  <div class="alert alert-success kpi mb-0 py-2 px-3">
                    <div class="text-muted" style="font-size:12px;">Total a pagar</div>
                    <div class="num" id="entTotal">$0.00</div>
                    <small class="text-muted d-block" id="entDescMoney">Descuento: $0.00</small>
                    <!-- botón cobro se inyecta por JS -->
                  </div>
                </div>
              </div>
              <!-- ✅ FIN RESUMEN -->

              <div class="text-end mt-2">
                <button class="btn btn-outline-secondary btn-sm" onclick="clearLog('ent')">
                  <i class="fa-solid fa-eraser"></i> Limpiar lista
                </button>
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ROBO -->
    <div class="tab-pane fade" id="tab-robo">
      <!-- (tu bloque ROBO queda igual, abajo en scripts) -->
      <div class="row g-3">
        <div class="col-12 col-lg-12">
          <div class="card">
            <div class="card-body">
              <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                <h6 class="mb-0"><i class="fa-solid fa-table"></i> Registros (estado=1, anulado=0)</h6>

                <div class="alert alert-secondary kpi mb-0 py-2 px-3">
                  <div class="text-muted" style="font-size:12px;">Registros</div>
                  <div class="num" id="kRob">0</div>
                </div>
              </div>

              <div class="row g-2 align-items-end mt-2">
                <div class="col-6 col-md-1">
                  <label class="form-label">Fecha inicio</label>
                  <input type="date" id="robIni" class="form-control">
                </div>

                <div class="col-6 col-md-1">
                  <label class="form-label">Fecha fin</label>
                  <input type="date" id="robFin" class="form-control">
                </div>

                <div class="col-12 col-md-3">
                  <label class="form-label">Coordinador</label>
                  <select id="robcoodinador" class="form-select"></select>
                </div>

                <div class="col-12 col-md-3">
                  <label class="form-label">Punto de venta</label>
                  <select id="robPunto" class="form-select"></select>
                </div>

                <div class="col-12 col-md-3">
                  <label class="form-label">Canillita</label>
                  <select id="robCan" class="form-select"></select>
                </div>

                <div class="col-12 col-md-1 d-grid mt-1">
                  <button class="btn btn-dark rounded-circle" type="button"
                          style="width:40px;height:40px"
                          onclick="cargarRobos()" title="Buscar">
                    <i class="fa-solid fa-magnifying-glass"></i>
                  </button>
                </div>
              </div>

              <div class="d-flex align-items-center gap-2 mt-2 flex-wrap">

				  <!-- Anular -->
				  <button 
					type="button"
					class="btn btn-danger btn-sm d-flex align-items-center gap-1"
					onclick="anularSeleccionados()"
					title="Anular seleccionados"
				  >
					<i class="fa-solid fa-circle-xmark"></i>
					<span>Anular</span>
				  </button>

				  <!-- Devolver -->
				  <button 
					type="button"
					class="btn btn-warning btn-sm d-flex align-items-center gap-1"
					onclick="devolverSeleccionados()"
					title="Devolver seleccionados"
				  >
					<i class="fa-solid fa-rotate-left"></i>
					<span>Devolver</span>
				  </button>

				</div>



              <hr class="my-3">

              <div class="table-responsive">
                <table id="tbRob" class="table table-sm table-striped w-100">
                  <thead>
                    <tr>
                      <th class="text-center"><input type="checkbox" id="robCheckAll" /></th>
                      <th>#</th>
                      <th>Fecha/Hora</th>
                      <th>Código</th>
                      <th>Responsable</th>
                    </tr>
                  </thead>
                  <tbody></tbody>
                </table>
              </div>

              <small class="text-muted d-block mt-2">
                Filtros por <b>DATE(fecha_hora)</b>, coordinador, punto (<b>id_usuario</b>) y canillita (<b>id_canillita</b>).
              </small>
            </div>
          </div>
        </div>
      </div>
    </div>
	<!-- PAGOS -->
	<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="tab-reportes">
      <!-- (tu bloque REPORTES queda igual, abajo en scripts) -->
      <div class="row g-3">

        <div class="col-12">
          <div class="card">
            <div class="card-body">

              <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-2">
                <h6 class="mb-0">
                  <i class="fa-solid fa-chart-column"></i> Reportes
                </h6>

                <div class="d-flex gap-2">
                  <button class="btn btn-dark rounded-circle" type="button"
                          style="width:40px;height:40px"
                          onclick="cargarReporte()" title="Buscar">
                    <i class="fa-solid fa-magnifying-glass"></i>
                  </button>
                </div>
              </div>

              <div class="row g-2 align-items-end">
                <div class="col-6 col-md-2">
                  <label class="form-label">Inicio</label>
                  <input type="date" id="repIni" class="form-control">
                </div>
                <div class="col-6 col-md-2">
                  <label class="form-label">Fin</label>
                  <input type="date" id="repFin" class="form-control">
                </div>
                <div class="col-12 col-md-4">
                  <label class="form-label">Punto</label>
                  <select id="repPunto" class="form-select"></select>
                </div>

                <div class="col-12 col-md-4">
                  <label class="form-label">Estado</label>
                  <select id="repEstado" class="form-select">
                    <option value="">— Todos —</option>
                    <option value="1">1 (Asignado/Activo)</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                  </select>
                </div>
              </div>

              <hr class="my-3">

              <div class="row g-2">
                <div class="col-6 col-md-2">
                  <div class="alert alert-secondary kpi mb-0">
                    <div class="text-muted">Registros</div>
                    <div class="num" id="kReg">0</div>
                  </div>
                </div>
                <div class="col-6 col-md-2">
                  <div class="alert alert-primary kpi mb-0">
                    <div class="text-muted">Asignadas</div>
                    <div class="num" id="kAsi">0</div>
                  </div>
                </div>
                <div class="col-6 col-md-2">
                  <div class="alert alert-info kpi mb-0">
                    <div class="text-muted">Entregadas</div>
                    <div class="num" id="kEnt">0</div>
                  </div>
                </div>
                <div class="col-6 col-md-2">
                  <div class="alert alert-success kpi mb-0">
                    <div class="text-muted">Vendidas</div>
                    <div class="num" id="kVen">0</div>
                  </div>
                </div>
                <div class="col-6 col-md-2">
                  <div class="alert alert-warning kpi mb-0">
                    <div class="text-muted">Ganadoras</div>
                    <div class="num" id="kGan">0</div>
                  </div>
                </div>
                <div class="col-6 col-md-2">
                  <div class="alert alert-danger kpi mb-0">
                    <div class="text-muted">Bloqueadas</div>
                    <div class="num" id="kBlo">0</div>
                  </div>
                </div>
              </div>

              <small class="text-muted d-block mt-2">
                El reporte se basa en <b>fecha_hora</b> (tbr_raspadita).
              </small>

            </div>
          </div>
        </div>

        <div class="col-12">
          <div class="card">
            <div class="card-body">
              <h6 class="mb-3"><i class="fa-solid fa-table"></i> Detalle</h6>

              <div class="table-responsive">
                <table id="tbRep" class="table table-sm table-striped w-100">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>Serie</th>
                      <th>Estado</th>
                      <th>Responsable</th>
                      <th class="text-end">Valor</th>
                      <th>Ganadora</th>
                      <th class="text-end">Premio</th>
                      <th>Bloqueada</th>
                      <th>Fecha</th>
                    </tr>
                  </thead>
                  <tbody></tbody>
                </table>
              </div>

            </div>
          </div>
        </div>

      </div>
    </div>

  </div>
</div>

<script>
  window.ID_ADMIN = <?= (int)$idusuario ?>;
  window.CSRF = <?= json_encode($csrf, JSON_UNESCAPED_UNICODE) ?>;
</script>

<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.jsdelivr.net/npm/sweetalert2@11"></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/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
  // Hora EC
  (function(){
    function pad2(n){return String(n).padStart(2,'0');}
    function tick(){
      const now = new Date();
      const ec  = new Date(now.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
      const el = document.getElementById('hora');
      if (el) el.textContent = pad2(ec.getHours())+":"+pad2(ec.getMinutes());
    }
    tick(); setInterval(tick, 30000);
  })();

  async function postJson(url, payload){
    const r = await fetch(url, {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type':'application/json' },
      body: JSON.stringify(payload || {})
    });
    const txt = await r.text();
    let j=null; try{ j=JSON.parse(txt); }catch(e){}
    if(!r.ok){
      const msg = (j && (j.message || j.error)) ? (j.message || j.error) : (txt.slice(0,200) || `HTTP ${r.status}`);
      throw new Error(msg);
    }
    if(!j || j.success !== true){
      throw new Error(j?.message || 'Error');
    }
    return j;
  }

  function escapeHtml(s){
    s = String(s ?? '');
    return s.replace(/[&<>"']/g, m => ({
      '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'
    }[m]));
  }

  function nowHHMM(){
    const d = new Date();
    const ec = new Date(d.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
    return String(ec.getHours()).padStart(2,'0')+":"+String(ec.getMinutes()).padStart(2,'0');
  }

  function bindEnter(id, fn){
    const el = document.getElementById(id);
    if(!el) return;
    el.addEventListener('keydown', (ev)=>{
      if(ev.key === 'Enter'){
        ev.preventDefault();
        fn();
      }
    });
  }
</script>

<script>
  // ============================================================
  // ✅ CARGAR PUNTOS
  // ============================================================
  async function cargarPuntos(){
    const apiUrl = 'api/usuario_sucursal_concat.php?sep=' + encodeURIComponent(' - ');

    async function fill(selectId, firstText){
      const sel = document.getElementById(selectId);
      if(!sel) return;

      sel.innerHTML = '<option value="">Cargando...</option>';
      sel.disabled = true;

      try{
        const resp = await fetch(apiUrl, { cache:'no-store', headers:{'Accept':'application/json'} });
        if(!resp.ok) throw new Error(`HTTP ${resp.status}`);

        const json = await resp.json();
        if(!json || json.success !== true) throw new Error(json?.message || 'No se pudo cargar');

        const opts = [`<option value="">${escapeHtml(firstText || 'Seleccione')}</option>`];
        (json.results || []).forEach(item=>{
          const id = String(item.id ?? '');
          const text = String(item.text ?? '');
          if(id && text) opts.push(`<option value="${escapeHtml(id)}">${escapeHtml(text)}</option>`);
        });

        sel.innerHTML = opts.join('');
      }catch(e){
        console.error('cargarPuntos:', e);
        sel.innerHTML = '<option value="">No se pudo cargar</option>';
      }finally{
        sel.disabled = false;
      }
    }

    await Promise.all([
      fill('asigPunto', 'Seleccione un punto de venta'),
      fill('repPunto',  '— Todos los puntos —'),
      fill('robPunto',  '— Todos los puntos —')
    ]);
  }

  // ============================================================
  // ✅ CARGAR COORDINADORES
  // ============================================================
  async function cargarCoordinadores(){
    const selectIds = ['selCoordinador'];
    const selects = selectIds.map(id => document.getElementById(id)).filter(Boolean);
    if(!selects.length) return;

    selects.forEach(sel => {
      sel.innerHTML = '<option value="">Cargando...</option>';
      sel.disabled = true;
    });

    try{
      const r = await fetch('api/coordinadores_select.php', { cache:'no-store' });
      const j = await r.json();
      if(!j || j.success !== true) throw new Error(j?.message || 'No se pudo cargar');

      const opts = ['<option value="">— Seleccione coordinador —</option>'];
      (j.results || []).forEach(x=>{
        const id = String(x.id ?? '');
        const text = String(x.text ?? '');
        if(id && text) opts.push(`<option value="${escapeHtml(id)}">${escapeHtml(text)}</option>`);
      });

      const html = opts.join('');
      selects.forEach(sel => { sel.innerHTML = html; });

    }catch(e){
      console.error('cargarCoordinadores:', e);
      selects.forEach(sel => { sel.innerHTML = '<option value="">No se pudo cargar</option>'; });
    }finally{
      selects.forEach(sel => { sel.disabled = false; });
    }
  }

  // ✅ Select2 AJAX Canillitas (entCan)
  function initCanillitasSelectAjax(){
    const $sel = $('#entCan');
    if(!$sel.length) return;

    if ($sel.hasClass('select2-hidden-accessible')) $sel.select2('destroy');
    $sel.html('<option value=""></option>');

    $sel.select2({
      theme: "bootstrap4",
      width: "100%",
      placeholder: "— Seleccione canillita —",
      allowClear: true,
      minimumInputLength: 1,
      ajax: {
        url: 'api/canillitas_select2.php',
        dataType: 'json',
        delay: 250,
        cache: false,
        data: function (params) {
          return { q: params.term || '', page: params.page || 1 };
        },
        processResults: function (data, params) {
          params.page = params.page || 1;
          return {
            results: (data && data.results) ? data.results : [],
            pagination: { more: !!(data && data.pagination && data.pagination.more) }
          };
        }
      }
    });
  }
</script>

<script>
  // ============================================================
  // ✅ LOGS (UN SOLO logs PARA TODO)
  // ============================================================
  const logs = { asig: [], ent: [] };

  function addLog(tipo, serie, msg, ok, punto='', canillita='', canillita_id=0){
    // ok siempre boolean real
    const okBool = (ok === true || ok === 1 || ok === '1' || ok === 'true');
    logs[tipo].unshift({ serie, punto, canillita, canillita_id, msg, ok: okBool, hora: nowHHMM() });
    if (logs[tipo].length > 50) logs[tipo].pop();
    renderLog(tipo);
  }

  function clearLog(tipo){
    logs[tipo] = [];
    renderLog(tipo);
  }

  function renderLog(tipo){
    const tb = document.querySelector(tipo==='asig' ? '#tbAsig tbody' : '#tbEnt tbody');
    if (!tb) return;

    tb.innerHTML = logs[tipo].map((x,i)=>`
      <tr>
        <td>${i+1}</td>
        <td><b>${escapeHtml(x.serie)}</b></td>

        ${tipo==='asig' ? `<td>${escapeHtml(x.punto || '')}</td>` : ``}
        ${tipo==='ent'  ? `<td>${escapeHtml(x.canillita || '')}</td>` : ``}

        <td>
          ${x.ok ? '<span class="badge bg-success">OK</span>' : '<span class="badge bg-danger">ERROR</span>'}
          ${escapeHtml(x.msg)}
        </td>

        <td>${escapeHtml(x.hora)}</td>

        ${tipo==='asig' ? `
          <td class="text-end">
            <button class="btn btn-outline-danger btn-sm" type="button"
              title="Eliminar asignación"
              onclick='eliminarAsignacion(${JSON.stringify(String(x.serie||""))})'>
              <i class="fa-solid fa-trash"></i>
            </button>
          </td>
        ` : ``}

        ${tipo==='ent' ? `
          <td class="text-end">
            <button class="btn btn-outline-danger btn-sm" type="button"
              title="Eliminar entrega"
              onclick='eliminarEntrega(${JSON.stringify(String(x.serie||""))}, ${parseInt(x.canillita_id||0,10)})'>
              <i class="fa-solid fa-trash"></i>
            </button>
          </td>
        ` : ``}
      </tr>
    `).join('');

    // ✅ recalcular solo lo que corresponde
    if(tipo === 'asig') calcPVTotales();
    if(tipo === 'ent')  calcEntTotales();
  }
</script>

<script>
  // ============================================================
  // ✅ CONSTANTES / VALOR
  // ============================================================
  const VALOR_RASPADITA = 0.50; // si cambia, edítalo aquí
</script>

<script>
  // ============================================================
  // ✅ PUNTO VENTA: TOTALES + DESCUENTO + COBRO
  // ============================================================
  function moneyPV(n){
    const v = Number(n || 0);
    return '$' + v.toFixed(2);
  }

  function getPVDescuento(){
    const el = document.getElementById('pvDesc');
    let d = parseFloat((el?.value || '0').toString().replace(',', '.'));
    if (isNaN(d)) d = 0;
    if (d < 0) d = 0;
    if (d > 100) d = 100;
    if (el) el.value = String(d);
    return d;
  }

  function calcPVTotales(){
    const cant = (logs.asig || []).filter(x => x && x.ok === true).length;

    const descPct = getPVDescuento();
    const subtotal = cant * VALOR_RASPADITA;
    const descMoney = subtotal * (descPct / 100);
    const total = subtotal - descMoney;

    document.getElementById('kpvCant') && (document.getElementById('kpvCant').textContent = String(cant));
    document.getElementById('kpvSub')  && (document.getElementById('kpvSub').textContent  = moneyPV(subtotal));
    document.getElementById('kpvTotal')&& (document.getElementById('kpvTotal').textContent= moneyPV(total));
    document.getElementById('kpvDescMoney') && (document.getElementById('kpvDescMoney').textContent = 'Descuento: ' + moneyPV(descMoney));

    const btn = document.getElementById('btnPVCobro');
    const btnT = document.getElementById('btnPVCobroTotal');
    if (btnT) btnT.textContent = moneyPV(total);

    if (btn){
      btn.classList.toggle('d-none', !(cant > 0));
    }

    return { cant, subtotal, descPct, descMoney, total };
  }

  document.addEventListener('DOMContentLoaded', ()=>{
    document.getElementById('pvDesc')?.addEventListener('input', ()=> calcPVTotales());
    calcPVTotales();
  });

  // ✅ API COBRO PV
  const API_COBRO_PV = 'api/punto_saldo_insert.php';

  async function registrarCobroPV(tipo_pago){
    const sel = document.getElementById('asigPunto');
    const id_usuario = parseInt(sel?.value || '0', 10) || 0;
    const puntoTxt = sel?.options?.[sel.selectedIndex]?.text || '';

    if(!id_usuario) return Swal.fire('Atención','Seleccione un punto de venta.','warning');

    const t = calcPVTotales();
    if(t.cant <= 0) return Swal.fire('Atención','No hay asignaciones OK para cobrar.','warning');

    try{
      const j = await postJson(API_COBRO_PV, {
        id_usuario,
        num_raspaditas: t.cant,
        subtotal: t.subtotal,
        descuento: t.descMoney,
        total_pagar: t.total,
        tipo_pago: tipo_pago, // "EFECTIVO" | "CREDITO"
        observacion: `COBRO PV ${tipo_pago} | ${puntoTxt} | DESC ${t.descPct.toFixed(2)}%`,
        id_admin: (window.ID_ADMIN || 0)
      });

      let extra = '';
      if(tipo_pago === 'CREDITO'){
        extra = `<br><small class="text-muted">Saldo nuevo del punto: <b>$${Number(j.saldo_nuevo||0).toFixed(2)}</b></small>`;
      }

      Swal.fire('OK', (j.message || 'Cobro registrado') + extra, 'success');
    }catch(e){
      console.error('registrarCobroPV:', e);
      Swal.fire('Error', e.message || 'No se pudo registrar el cobro', 'error');
    }
  }

  function abrirVentanaCobroPV(){
    const sel = document.getElementById('asigPunto');
    const id_usuario = parseInt(sel?.value || '0', 10) || 0;
    const puntoTxt = sel?.options?.[sel.selectedIndex]?.text || '';

    if(!id_usuario) return Swal.fire('Atención','Seleccione un punto de venta.','warning');

    const t = calcPVTotales();
    if(t.cant <= 0) return Swal.fire('Atención','No hay asignaciones OK para cobrar.','warning');

    Swal.fire({
      title: 'Cobro Punto de Venta',
      html: `
        <div class="text-start">
          <div><b>Punto:</b> ${escapeHtml(puntoTxt)}</div>
          <div><b>Raspaditas:</b> ${t.cant}</div>
          <div><b>Subtotal:</b> ${moneyPV(t.subtotal)}</div>
          <div><b>Descuento:</b> ${moneyPV(t.descMoney)} (${t.descPct.toFixed(2)}%)</div>
          <div><b>Total a pagar:</b> ${moneyPV(t.total)}</div>
        </div>
        <hr class="my-2">
        <div class="d-grid gap-2">
          <button id="btnCobEfPV" class="btn btn-success btn-lg">
            <i class="fa-solid fa-money-bill-wave"></i> EFECTIVO
          </button>
          <button id="btnCobCrPV" class="btn btn-primary btn-lg">
            <i class="fa-solid fa-credit-card"></i> CRÉDITO
          </button>
        </div>
      `,
      showConfirmButton: false,
      showCancelButton: true,
      cancelButtonText: 'Cerrar',
      didOpen: () => {
        document.getElementById('btnCobEfPV')?.addEventListener('click', ()=>{ Swal.close(); registrarCobroPV('EFECTIVO'); });
        document.getElementById('btnCobCrPV')?.addEventListener('click', ()=>{ Swal.close(); registrarCobroPV('CREDITO'); });
      }
    });
  }
</script>

<script>
  // ============================================================
  // ✅ ENTREGA (CANILLITA): TOTALES + DESCUENTO + COBRO (SIN DUPLICAR LOGS)
  // ============================================================
  const API_COBRO_CAN = 'api/cobro_canillita_insert.php';

  function moneyEnt(n){
    const v = Number(n || 0);
    return '$' + v.toFixed(2);
  }

  function getEntDescuento(){
    const el = document.getElementById('entDesc');
    let d = parseFloat((el?.value || '0').toString().replace(',', '.'));
    if (isNaN(d)) d = 0;
    if (d < 0) d = 0;
    if (d > 100) d = 100;
    if (el) el.value = String(d);
    return d;
  }

  function ensureBtnCobroEnt(){
    if (document.getElementById('btnEntCobro')) return;
    const box = document.getElementById('entTotal')?.closest('.alert');
    if(!box) return;

    const btn = document.createElement('button');
    btn.id = 'btnEntCobro';
    btn.type = 'button';
    btn.className = 'btn btn-dark btn-sm mt-2 w-100 d-none';
    btn.innerHTML = '<i class="fa-solid fa-cash-register"></i> Cobro';
    btn.addEventListener('click', abrirVentanaCobroEnt);
    box.appendChild(btn);
  }

  function calcEntTotales(){
    const cant = (logs.ent || []).filter(x => x && x.ok === true).length;

    const descPct  = getEntDescuento();
    const subtotal = cant * VALOR_RASPADITA;
    const descMoney = subtotal * (descPct / 100);
    const total = subtotal - descMoney;

    document.getElementById('entCant') && (document.getElementById('entCant').textContent = String(cant));
    document.getElementById('entSub')  && (document.getElementById('entSub').textContent  = moneyEnt(subtotal));
    document.getElementById('entTotal')&& (document.getElementById('entTotal').textContent= moneyEnt(total));
    document.getElementById('entDescMoney') && (document.getElementById('entDescMoney').textContent = 'Descuento: ' + moneyEnt(descMoney));
    document.getElementById('totEntregadas') && (document.getElementById('totEntregadas').textContent = String(cant));

    ensureBtnCobroEnt();
    const btn = document.getElementById('btnEntCobro');
    if(btn) btn.classList.toggle('d-none', !(cant > 0));

    return { cant, subtotal, descPct, descMoney, total };
  }

  function abrirVentanaCobroEnt(){
    const val = ($('#entCan').val() || '').toString();
    const id_canillita = parseInt(val || '0', 10) || 0;

    const dataSel = $('#entCan').select2('data')[0] || {};
    const canTxt = (dataSel.text || '').toString();

    if(!id_canillita) return Swal.fire('Atención','Seleccione un canillita.','warning');

    const t = calcEntTotales();
    if(t.cant <= 0) return Swal.fire('Atención','No hay entregas OK para cobrar.','warning');

    Swal.fire({
      title: 'Cobro Canillita',
      html: `
        <div class="text-start">
          <div><b>Canillita:</b> ${escapeHtml(canTxt)}</div>
          <div><b>Raspaditas:</b> ${t.cant}</div>
          <div><b>Subtotal:</b> ${moneyEnt(t.subtotal)}</div>
          <div><b>Descuento:</b> ${moneyEnt(t.descMoney)} (${t.descPct.toFixed(2)}%)</div>
          <div><b>Total a pagar:</b> ${moneyEnt(t.total)}</div>
        </div>
        <hr class="my-2">
        <div class="d-grid gap-2">
          <button id="btnCobEfENT" class="btn btn-success btn-lg">
            <i class="fa-solid fa-money-bill-wave"></i> EFECTIVO
          </button>
          <button id="btnCobCrENT" class="btn btn-primary btn-lg">
            <i class="fa-solid fa-credit-card"></i> CRÉDITO
          </button>
        </div>
      `,
      showConfirmButton: false,
      showCancelButton: true,
      cancelButtonText: 'Cerrar',
      didOpen: () => {
        document.getElementById('btnCobEfENT')?.addEventListener('click', ()=>{ Swal.close(); registrarCobroEnt('EFECTIVO'); });
        document.getElementById('btnCobCrENT')?.addEventListener('click', ()=>{ Swal.close(); registrarCobroEnt('CREDITO'); });
      }
    });
  }

  async function registrarCobroEnt(tipo_pago){
    const val = ($('#entCan').val() || '').toString();
    const id_canillita = parseInt(val || '0', 10) || 0;

    const dataSel = $('#entCan').select2('data')[0] || {};
    const canTxt = (dataSel.text || '').toString();

    if(!id_canillita) return Swal.fire('Atención','Seleccione un canillita.','warning');

    const t = calcEntTotales();
    if(t.cant <= 0) return Swal.fire('Atención','No hay entregas OK para cobrar.','warning');

    try{
      const j = await postJson(API_COBRO_CAN, {
        id_canillita: id_canillita,
        num_raspaditas: t.cant,
        subtotal: t.subtotal,
        descuento: t.descMoney,
        total_pagar: t.total,
        tipo_pago: tipo_pago,
        observacion: `COBRO CANILLITA ${tipo_pago} | ${canTxt} | DESC ${t.descPct.toFixed(2)}%`,
        id_admin: (window.ID_ADMIN || 0)
      });

      Swal.fire('OK', j.message || `Cobro registrado (${tipo_pago})`, 'success');
    }catch(e){
      console.error('registrarCobroEnt:', e);
      Swal.fire('Error', e.message || 'No se pudo registrar el cobro', 'error');
    }finally{
      calcEntTotales();
    }
  }

  // ✅ ENTREGAR / ELIMINAR (usa logs.ent real)
  window.entregarSerie = async function entregarSerie(){
    const val = ($('#entCan').val() || '').toString();
    const id_canillita = parseInt(val || '0', 10) || 0;

    const serie = (document.getElementById('entSerie')?.value || '').trim().replace(/\s+/g,'');
    const premioInp = document.getElementById('entPremio');
    const premio = parseFloat((premioInp?.value || '0').toString().replace(',', '.')) || 0;

    const dataSel = $('#entCan').select2('data')[0] || {};
    const canTxt = (dataSel.text || '').toString();

    if(!id_canillita) return Swal.fire('Atención','Seleccione un canillita.','warning');
    if(!serie) return Swal.fire('Atención','Escanee una serie.','warning');
    if(premio < 0) return Swal.fire('Atención','El premio no puede ser negativo.','warning');

    try{
      const j = await postJson('api/raspadita_insert.php', {
        codigo: serie,
        anulado: 0,
        id_admin: (window.ID_ADMIN || 0),
        id_canillita: id_canillita,
        premio: premio
      });

      addLog('ent', serie, j.message || 'Entregada', true, '', canTxt, id_canillita);
    }catch(e){
      addLog('ent', serie, e.message || 'Error', false, '', canTxt, id_canillita);
      Swal.fire('Error', e.message || 'Error', 'error');
    }finally{
      const inp = document.getElementById('entSerie');
      if (inp){ inp.value=''; inp.focus(); }
      if (premioInp) premioInp.value = '0.00';
      calcEntTotales();
    }
  };

  window.eliminarEntrega = async function eliminarEntrega(serie, id_canillita){
    serie = (serie || '').trim().replace(/\s+/g,'');
    id_canillita = parseInt(id_canillita || '0', 10) || 0;
    if(!serie || !id_canillita) return;

    const r = await Swal.fire({
      title: 'Eliminar entrega',
      html: `¿Deseas eliminar la entrega de la serie:<br><b>${escapeHtml(serie)}</b>?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Sí, eliminar',
      cancelButtonText: 'Cancelar'
    });
    if(!r.isConfirmed) return;

    try{
      const j = await postJson('api/raspadita_delete.php', {
        codigo: serie,
        id_canillita: id_canillita,
        id_admin: (window.ID_ADMIN || 0)
      });

      logs.ent = (logs.ent || []).filter(x => String(x.serie) !== String(serie));
      renderLog('ent');

      Swal.fire('OK', j.message || 'Eliminado', 'success');
    }catch(e){
      Swal.fire('Error', e.message || 'Error', 'error');
    }finally{
      calcEntTotales();
    }
  };

  document.addEventListener('DOMContentLoaded', ()=>{
    document.getElementById('entDesc')?.addEventListener('input', ()=> calcEntTotales());
    ensureBtnCobroEnt();
    calcEntTotales();
  });

  document.addEventListener('shown.bs.tab', (event)=>{
    const target = event?.target?.getAttribute('data-bs-target') || '';
    if(target === '#tab-entregar'){
      ensureBtnCobroEnt();
      setTimeout(()=> calcEntTotales(), 150);
    }
  });
</script>

<script>
  // ============================================================
  // ✅ COORDINADOR (CON ELIMINAR) + TOTALES + DESCUENTO + COBRO
  // ============================================================
  const coordLogs = []; // {id, serie, id_coordinador, coordinador, msg, ok, hora}

  function money2(n){
    const v = Number(n || 0);
    return '$' + v.toFixed(2);
  }

  function getCoordDescuento(){
    const el = document.getElementById('coordDesc');
    let d = parseFloat((el?.value || '0').toString().replace(',', '.'));
    if (isNaN(d)) d = 0;
    if (d < 0) d = 0;
    if (d > 100) d = 100;
    if (el) el.value = String(d);
    return d;
  }

  function calcCoordTotales(){
    const cant = coordLogs.filter(x => x && x.ok === true).length;
    const descPct = getCoordDescuento();
    const subtotal = cant * VALOR_RASPADITA;
    const descMoney = subtotal * (descPct / 100);
    const total = subtotal - descMoney;

    document.getElementById('kCoordCant') && (document.getElementById('kCoordCant').textContent = String(cant));
    document.getElementById('kCoordSub')  && (document.getElementById('kCoordSub').textContent  = money2(subtotal));
    document.getElementById('kCoordTotal')&& (document.getElementById('kCoordTotal').textContent= money2(total));
    document.getElementById('kCoordDescMoney') && (document.getElementById('kCoordDescMoney').textContent = 'Descuento: ' + money2(descMoney));

    const btn = document.getElementById('btnCoordCobro');
    if(btn) btn.classList.toggle('d-none', !(cant > 0));

    return { cant, subtotal, descPct, descMoney, total };
  }

  function renderCoordLog(){
    const tb = document.querySelector('#tbCoord tbody');
    if(!tb) return;

    tb.innerHTML = coordLogs.map((x,i)=>`
      <tr>
        <td>${i+1}</td>
        <td><b>${escapeHtml(x.serie)}</b></td>
        <td>${escapeHtml(x.coordinador)}</td>
        <td>
          ${x.ok ? '<span class="badge bg-success">OK</span>' : '<span class="badge bg-danger">ERROR</span>'}
          ${escapeHtml(x.msg)}
        </td>
        <td>${escapeHtml(x.hora)}</td>
        <td class="text-end">
          <button class="btn btn-outline-danger btn-sm" type="button"
            title="Eliminar asignación"
            onclick='eliminarAsignacionCoord(${parseInt(x.id||0,10)}, ${JSON.stringify(String(x.serie||""))}, ${parseInt(x.id_coordinador||0,10)})'>
            <i class="fa-solid fa-trash"></i>
          </button>
        </td>
      </tr>
    `).join('');

    calcCoordTotales();
  }

  function addCoordLog(id, serie, id_coordinador, coordinador, msg, ok){
    coordLogs.unshift({ id, serie, id_coordinador, coordinador, msg, ok: (ok === true), hora: nowHHMM() });
    if(coordLogs.length > 50) coordLogs.pop();
    renderCoordLog();
  }

  function clearCoordLog(){
    coordLogs.length = 0;
    renderCoordLog();
  }

  async function asignarCoordinador(){
    const sel = document.getElementById('selCoordinador');
    const id_coordinador = parseInt(sel?.value || '0', 10);
    const coordTxt = sel?.options?.[sel.selectedIndex]?.text || '';
    const serie = (document.getElementById('coordSerie')?.value || '').trim().replace(/\s+/g,'');

    const premioInp = document.getElementById('ganPremio');
    const premio = parseFloat((premioInp?.value || '0').toString().replace(',', '.')) || 0;

    if(!id_coordinador) return Swal.fire('Atención','Seleccione un coordinador.','warning');
    if(!serie) return Swal.fire('Atención','Escanee una serie.','warning');
    if(premio < 0) return Swal.fire('Atención','El premio no puede ser negativo.','warning');

    const btn = document.getElementById('btnCoordSave');
    if(btn) btn.disabled = true;

    try{
      const r = await fetch('api/raspadita_insert_coord.php', {
        method:'POST',
        headers:{ 'Content-Type':'application/json' },
        body: JSON.stringify({ id_coordinador, codigo: serie, premio })
      });

      const txt = await r.text();
      let j=null; try{ j=JSON.parse(txt); }catch(e){}
      if(!r.ok) throw new Error(j?.message || txt.slice(0,200) || `HTTP ${r.status}`);
      if(!j || j.success !== true) throw new Error(j?.message || 'No se pudo guardar');

      addCoordLog(parseInt(j.id||0,10), serie, id_coordinador, coordTxt, j.message || 'Asignado', true);
    }catch(e){
      addCoordLog(0, serie, id_coordinador, coordTxt, e.message || 'Error', false);
      Swal.fire('Error', e.message || 'No se pudo asignar', 'error');
    }finally{
      const inp = document.getElementById('coordSerie');
      if(inp){ inp.value=''; inp.focus(); }
      if(premioInp){ premioInp.value=''; }
      if(btn) btn.disabled = false;
    }
  }

  async function eliminarAsignacionCoord(id, serie, id_coordinador){
    id = parseInt(id||0,10);
    serie = String(serie ?? '').replace(/\s+/g,'').trim();
    id_coordinador = parseInt(id_coordinador||0,10);

    if(!serie) return;

    const r = await Swal.fire({
      title: 'Eliminar asignación',
      html: `¿Deseas eliminar la asignación del coordinador para la serie:<br><b>${escapeHtml(serie)}</b>?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Sí, eliminar',
      cancelButtonText: 'Cancelar'
    });
    if(!r.isConfirmed) return;

    try{
      const j = await postJson('api/raspadita_delete_coord.php', {
        id: id,
        codigo: serie,
        id_coordinador: id_coordinador,
        id_admin: (window.ID_ADMIN || 0)
      });

      const idx = coordLogs.findIndex(x => String(x.serie)===String(serie));
      if(idx >= 0) coordLogs.splice(idx, 1);
      renderCoordLog();

      Swal.fire('OK', j.message || 'Asignación eliminada', 'success');
    }catch(e){
      Swal.fire('Error', e.message || 'No se pudo eliminar', 'error');
    }
  }

  // ✅ Cobro Coordinador (inyecta botón + modal)
  const API_COBRO_COORD = 'api/coordinador_saldo_insert.php';

  function ensureBtnCobroCoord(){
    if (document.getElementById('btnCoordCobro')) return;

    const box = document.getElementById('kCoordTotal')?.closest('.alert');
    if(!box) return;

    const btn = document.createElement('button');
    btn.id = 'btnCoordCobro';
    btn.type = 'button';
    btn.className = 'btn btn-dark btn-sm mt-2 w-100 d-none';
    btn.innerHTML = '<i class="fa-solid fa-cash-register"></i> Cobro';
    btn.addEventListener('click', abrirVentanaCobroCoord);

    box.appendChild(btn);
    calcCoordTotales();
  }

  function abrirVentanaCobroCoord(){
    const sel = document.getElementById('selCoordinador');
    const id_coordinador = parseInt(sel?.value || '0', 10) || 0;
    const coordTxt = sel?.options?.[sel.selectedIndex]?.text || '';

    if(!id_coordinador) return Swal.fire('Atención','Seleccione un coordinador.','warning');

    const t = calcCoordTotales();
    if(t.cant <= 0) return Swal.fire('Atención','No hay asignaciones OK para cobrar.','warning');

    Swal.fire({
      title: 'Cobro Coordinador',
      html: `
        <div class="text-start">
          <div><b>Coordinador:</b> ${escapeHtml(coordTxt)}</div>
          <div><b>Raspaditas:</b> ${t.cant}</div>
          <div><b>Subtotal:</b> ${money2(t.subtotal)}</div>
          <div><b>Descuento:</b> ${money2(t.descMoney)} (${t.descPct.toFixed(2)}%)</div>
          <div><b>Total a pagar:</b> ${money2(t.total)}</div>
        </div>
        <hr class="my-2">
        <div class="d-grid gap-2">
          <button id="btnCobEfC" class="btn btn-success btn-lg">
            <i class="fa-solid fa-money-bill-wave"></i> EFECTIVO
          </button>
          <button id="btnCobCrC" class="btn btn-primary btn-lg">
            <i class="fa-solid fa-credit-card"></i> CRÉDITO
          </button>
        </div>
      `,
      showConfirmButton: false,
      showCancelButton: true,
      cancelButtonText: 'Cerrar',
      didOpen: () => {
        document.getElementById('btnCobEfC')?.addEventListener('click', ()=>{ Swal.close(); registrarCobroCoord('EFECTIVO'); });
        document.getElementById('btnCobCrC')?.addEventListener('click', ()=>{ Swal.close(); registrarCobroCoord('CREDITO'); });
      }
    });
  }

  async function registrarCobroCoord(metodo){
    const sel = document.getElementById('selCoordinador');
    const id_coordinador = parseInt(sel?.value || '0', 10) || 0;
    const coordTxt = sel?.options?.[sel.selectedIndex]?.text || '';

    if(!id_coordinador) return Swal.fire('Atención','Seleccione un coordinador.','warning');

    const t = calcCoordTotales();
    if(t.cant <= 0) return Swal.fire('Atención','No hay asignaciones OK para cobrar.','warning');

    try{
      const j = await postJson(API_COBRO_COORD, {
        id_coordinador: id_coordinador,
        fecha_hora: new Date().toISOString().slice(0,19).replace('T',' '),
        num_raspaditas: t.cant,
        subtotal: t.subtotal,
        descuento: t.descMoney,
        total_pagar: t.total,
        metodo: metodo,
        observacion: `COBRO ${metodo} | ${coordTxt} | DESC ${t.descPct.toFixed(2)}%`,
        id_admin: (window.ID_ADMIN || 0)
      });

      Swal.fire('OK', j.message || `Cobro registrado (${metodo})`, 'success');
    }catch(e){
      console.error('registrarCobroCoord:', e);
      Swal.fire('Error', e.message || 'No se pudo registrar el cobro', 'error');
    }
  }

  document.addEventListener('DOMContentLoaded', ()=>{
    document.getElementById('coordDesc')?.addEventListener('input', ()=> calcCoordTotales());
    ensureBtnCobroCoord();
    calcCoordTotales();
  });

  document.addEventListener('shown.bs.tab', (event)=>{
    const target = event?.target?.getAttribute('data-bs-target') || '';
    if(target === '#tab-coordinador'){
      ensureBtnCobroCoord();
      setTimeout(()=>document.getElementById('coordSerie')?.focus(), 80);
    }
  });
</script>

<script>
  // ============================================================
  // ✅ ASIGNAR (API externa) — con PREMIO
  // ============================================================
  async function guardarAsignacion(payload){
    const r = await fetch('api/raspadita_asignar.php', {
      method:'POST',
      headers:{ 'Content-Type':'application/json' },
      body: JSON.stringify(payload)
    });
    const txt = await r.text();
    let j=null; try{ j = JSON.parse(txt); }catch(e){}
    if(!r.ok) throw new Error(j?.message || txt.slice(0,200) || `HTTP ${r.status}`);
    if(!j) throw new Error('Respuesta inválida del servidor');
    if(!j.success) throw new Error(j.message || 'Error');
    return j;
  }

  async function asignarSerie(){
    const sel = document.getElementById('asigPunto');
    const id_usuario = parseInt(sel?.value || '0', 10);
    const puntoTxt = sel?.options?.[sel.selectedIndex]?.text || '';
    const codigo = (document.getElementById('asigSerie')?.value || '').trim().replace(/\s+/g,'');

    const premioInp = document.getElementById('ganPremio_p');
    const premio = parseFloat((premioInp?.value || '0').toString().replace(',', '.')) || 0;

    if(!id_usuario) return Swal.fire('Atención','Seleccione un punto de venta.','warning');
    if(!codigo) return Swal.fire('Atención','Escanee una serie.','warning');
    if(premio < 0) return Swal.fire('Atención','El premio no puede ser negativo.','warning');

    try{
      const j = await guardarAsignacion({ id_usuario, codigo, premio });
      addLog('asig', codigo, j.message || 'Asignación guardada', true, puntoTxt);
    }catch(e){
      console.error(e);
      addLog('asig', codigo, e.message || 'Error', false, puntoTxt);
      Swal.fire('Error', e.message || 'No se pudo guardar', 'error');
    }finally{
      const inp = document.getElementById('asigSerie');
      if (inp){ inp.value=''; inp.focus(); }
      if (premioInp) premioInp.value = '0.00';
    }
  }

  async function eliminarAsignacion(serie){
    serie = (serie || '').trim().replace(/\s+/g,'');
    if(!serie) return;

    const r = await Swal.fire({
      title: 'Eliminar asignación',
      html: `¿Deseas eliminar la asignación de la serie:<br><b>${escapeHtml(serie)}</b>?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Sí, eliminar',
      cancelButtonText: 'Cancelar'
    });
    if(!r.isConfirmed) return;

    try{
      const resp = await fetch('api/raspadita_asignacion_delete.php', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ codigo: serie })
      });
      const j = await resp.json().catch(()=>null);
      if(!j || j.success !== true) throw new Error(j?.message || 'No se pudo eliminar');

      logs.asig = logs.asig.filter(x => String(x.serie) !== String(serie));
      renderLog('asig');

      Swal.fire('OK', j.message || 'Asignación anulada correctamente', 'success');
    }catch(e){
      Swal.fire('Error', e.message || 'Error', 'error');
    }
  }
</script>

<script>
  // ============================================================
  // ✅ INIT GENERAL (IMPORTANTE: bindEnter DESPUÉS de definir entregarSerie)
  // ============================================================
  document.addEventListener('DOMContentLoaded', ()=>{
    cargarPuntos();
    initCanillitasSelectAjax();
    cargarCoordinadores();

    // binds
    bindEnter('coordSerie', asignarCoordinador);
    bindEnter('asigSerie', asignarSerie);
    bindEnter('entSerie',  ()=> window.entregarSerie && window.entregarSerie());
  });

  document.addEventListener('shown.bs.tab', function (event) {
    const target = event?.target?.getAttribute('data-bs-target') || '';
    if (target === '#tab-entregar') {
      initCanillitasSelectAjax();
      setTimeout(()=>$('#entCan').trigger('change.select2'), 50);
    }
    if (target === '#tab-coordinador') {
      cargarCoordinadores();
    }
  });
</script>
<script>
/* ===================== ROBO (JS COMPLETO) ===================== */
let dtRob = null;

const ROBO_URL_LIST        = 'api/raspadita_robo_list.php';
const ROBO_URL_ANULAR      = 'api/raspadita_robo_anular.php';
const ROBO_URL_DEVOLVER    = 'api/raspadita_robo_devolver.php';

const ROBO_URL_CAN         = 'api/canillitas_select2.php';
const ROBO_URL_COORD_LIST  = 'api/coordinador_list.php';
const ROBO_URL_PUNTO_LIST  = 'api/punto_venta_list.php';

/* ========= helpers ========= */
async function postJson(url, payload){
  const r = await fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'Content-Type':'application/json' },
    body: JSON.stringify(payload || {})
  });

  const txt = await r.text();
  let j = null;
  try { j = JSON.parse(txt); } catch(_) {}

  // Si devolvió HTML (login/warnings), muéstralo
  if(!j){
    const isHtml = /<!doctype|<html|<br\s*\/?>|<b>Warning|<b>Fatal/i.test(txt);
    const msg = isHtml
      ? ('La API devolvió HTML (login/warning). Revisa Network → Response.\n' + txt.slice(0, 250))
      : ('Respuesta no JSON: ' + txt.slice(0, 250));
    throw new Error(msg);
  }

  if(!r.ok){
    throw new Error(j.message || j.error || `HTTP ${r.status}`);
  }

  if(j.success !== true){
    throw new Error(j.message || 'La API respondió success=false sin message');
  }

  return j;
}

function escapeHtml(s){
  s = String(s ?? '');
  return s.replace(/[&<>"']/g, m => ({
    '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'
  }[m]));
}

function enableSelectTypeSearch(selectId){
  const sel = document.getElementById(selectId);
  if(!sel || sel.dataset.typeSearch === '1') return;
  sel.dataset.typeSearch = '1';

  let buffer = '';
  let lastAt = 0;

  sel.addEventListener('keydown', (e)=>{
    if (e.ctrlKey || e.metaKey || e.altKey) return;
    if (e.key.length !== 1) return;

    const now = Date.now();
    if (now - lastAt > 900) buffer = '';
    lastAt = now;

    buffer += e.key.toLowerCase();

    const opts = Array.from(sel.options);
    if (!opts.length) return;

    let match = opts.find(o => (o.textContent||'').toLowerCase().startsWith(buffer));
    if(!match) match = opts.find(o => (o.textContent||'').toLowerCase().includes(buffer));

    if(match){
      sel.value = match.value;
      sel.dispatchEvent(new Event('change', { bubbles:true }));
    }
  });
}

async function loadSimpleSelect(url, selectId, placeholderText){
  const sel = document.getElementById(selectId);
  if(!sel) return;

  sel.innerHTML = `<option value="0">${placeholderText || '— Todos —'}</option>`;

  const r = await fetch(url, { credentials: 'same-origin' });
  const txt = await r.text();
  let j = null;
  try { j = JSON.parse(txt); } catch(_) {}

  if(!j){
    console.error('Select API NO-JSON:', txt);
    return;
  }
  if(j.success !== true){
    console.error('loadSimpleSelect error:', j);
    return;
  }

  (j.data || []).forEach(it=>{
    const opt = document.createElement('option');
    opt.value = String(it.id ?? 0);
    opt.textContent = String(it.text ?? '');
    sel.appendChild(opt);
  });
}

function initRobTable(){
  if(dtRob) return;

  dtRob = $('#tbRob').DataTable({
    searching:true,
    lengthChange:false,
    paging: false,
    responsive:true,
    ordering:false,
    language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"},
    columnDefs: [
      { targets: 0, orderable: false, searchable: false, className: "text-center", width: "28px" }
    ]
  });

  // Check All
  const all = document.getElementById('robCheckAll');
  if(all){
    all.addEventListener('change', ()=>{
      const checked = all.checked;
      document.querySelectorAll('.rob-check').forEach(cb=>{ cb.checked = checked; });
    });
  }

  // Si desmarco 1, apago "CheckAll"
  document.addEventListener('change', (e)=>{
    if(!(e.target && e.target.classList && e.target.classList.contains('rob-check'))) return;
    const all = document.getElementById('robCheckAll');
    if(!all) return;
    if(!e.target.checked) all.checked = false;
  });
}

function getSelectedCodigos(){
  const codigos = [];
  document.querySelectorAll('.rob-check:checked').forEach(cb=>{
    const codigo = (cb.getAttribute('data-codigo') || '').trim();
    if(codigo) codigos.push(codigo);
  });
  return codigos;
}

function setFechasRoboHoy(){
  const now = new Date();
  const ec  = new Date(now.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
  const y = ec.getFullYear(), m=String(ec.getMonth()+1).padStart(2,'0'), d=String(ec.getDate()).padStart(2,'0');
  const hoy = `${y}-${m}-${d}`;
  const ini = document.getElementById('robIni');
  const fin = document.getElementById('robFin');
  if(ini && !ini.value) ini.value = hoy;
  if(fin && !fin.value) fin.value = hoy;
}

/* ========= Select2 Canillitas ========= */
function initRobCanillitasSelect2(){
  const $sel = $('#robCan');
  if(!$sel.length) return;

  if ($sel.hasClass('select2-hidden-accessible')) $sel.select2('destroy');
  $sel.html('<option value=""></option>');

  $sel.select2({
    theme: "bootstrap4",
    width: "100%",
    placeholder: "— Todos los canillitas —",
    allowClear: true,
    minimumInputLength: 1,
    ajax: {
      url: ROBO_URL_CAN,
      dataType: 'json',
      delay: 250,
      cache: false,
      data: function(params){
        return { q: params.term || '', page: params.page || 1 };
      },
      processResults: function(data, params){
        params.page = params.page || 1;
        return {
          results: (data && data.results) ? data.results : [],
          pagination: { more: !!(data && data.pagination && data.pagination.more) }
        };
      }
    }
  });
}

/* ===================== CARGAR ROBO ===================== */
window.cargarRobos = async function cargarRobos(){
  initRobTable();

  const fecha_ini = (document.getElementById('robIni')?.value || '').trim();
  const fecha_fin = (document.getElementById('robFin')?.value || '').trim();

  const id_coordinador = parseInt((document.getElementById('robcoodinador')?.value || '0'), 10) || 0;
  const id_punto  = parseInt((document.getElementById('robPunto')?.value || '0'), 10) || 0;
  const id_canillita = parseInt((($('#robCan').val() || '0').toString()), 10) || 0;

  try{
    const j = await postJson(ROBO_URL_LIST, { fecha_ini, fecha_fin, id_coordinador, id_punto, id_canillita });

    const total = parseInt(j.total || 0, 10) || 0;
    document.getElementById('kRob') && (document.getElementById('kRob').textContent = total);

    const all = document.getElementById('robCheckAll');
    if(all) all.checked = false;

    dtRob.clear();

    (j.data || []).forEach((r, idx)=>{
      const codigo = String(r.codigo || '');
      dtRob.row.add([
        `<input type="checkbox" class="rob-check" data-codigo="${escapeHtml(codigo)}">`,
        (idx + 1),
        escapeHtml(r.fecha_hora || ''),
        `<b>${escapeHtml(codigo)}</b>`,
        escapeHtml(r.responsable || '')
      ]);
    });

    dtRob.draw(false);

  }catch(e){
    console.error('cargarRobos:', e);
    Swal.fire('Error', e.message || 'No se pudo cargar', 'error');
  }
};

/* ===================== ANULAR ===================== */
window.anularSeleccionados = async function anularSeleccionados(){
  try{
    const codigos = getSelectedCodigos();
    if(!codigos.length){
      return Swal.fire('Atención','Seleccione uno o más registros para anular.','warning');
    }

    const r = await Swal.fire({
      title: 'Anular registros',
      html: `Vas a anular <b>${codigos.length}</b> registro(s).<br><small class="text-muted">Esta acción no se puede deshacer.</small>`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Sí, anular',
      cancelButtonText: 'Cancelar'
    });
    if(!r.isConfirmed) return;

    const j = await postJson(ROBO_URL_ANULAR, { codigos, id_admin: (window.ID_ADMIN||0) });

    Swal.fire('OK', j.message || 'Registros anulados', 'success');

    document.getElementById('robCheckAll') && (document.getElementById('robCheckAll').checked = false);
    await window.cargarRobos();

  }catch(e){
    console.error('anularSeleccionados:', e);
    Swal.fire('Error', e.message || 'No se pudo anular', 'error');
  }
};

/* ===================== DEVOLVER ===================== */
window.devolverSeleccionados = async function devolverSeleccionados(){
  try{
    const codigos = getSelectedCodigos();
    if(!codigos.length){
      return Swal.fire('Atención','Seleccione uno o más registros para devolver.','warning');
    }

    const r = await Swal.fire({
      title: 'Devolver registros',
      html: `Vas a devolver <b>${codigos.length}</b> raspadita(s).`,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Sí, devolver',
      cancelButtonText: 'Cancelar'
    });
    if(!r.isConfirmed) return;

    const j = await postJson(ROBO_URL_DEVOLVER, {
      codigos,
      id_admin: (window.ID_ADMIN||0)
    });

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

    document.getElementById('robCheckAll') && (document.getElementById('robCheckAll').checked = false);
    await window.cargarRobos();

  }catch(e){
    console.error('devolverSeleccionados:', e);
    Swal.fire('Error', e.message || 'No se pudo devolver', 'error');
  }
};

/* ===================== INIT TAB ROBO ===================== */
document.addEventListener('shown.bs.tab', async function (event) {
  const target = event?.target?.getAttribute('data-bs-target') || '';
  if (target === '#tab-robo') {

    setFechasRoboHoy();
    initRobCanillitasSelect2();

    try{ await loadSimpleSelect(ROBO_URL_COORD_LIST, 'robcoodinador', '— Todos los coordinadores —'); }catch(e){ console.error(e); }
    try{ await loadSimpleSelect(ROBO_URL_PUNTO_LIST, 'robPunto', '— Todos los puntos —'); }catch(e){ console.error(e); }

    enableSelectTypeSearch('robcoodinador');
    enableSelectTypeSearch('robPunto');

    setTimeout(()=>$('#robCan').trigger('change.select2'), 50);
    setTimeout(()=>window.cargarRobos(), 150);
  }
});
</script>

<!-- ===================== PAGOS (TU MISMO BLOQUE) ===================== -->
<script>
const API_PREMIO_INFO = 'api/raspadita_premio_info.php';
const API_PREMIO_PAGAR = 'api/raspadita_premio_pagar.php';

let premioActual = null; // guarda data del último consultado

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){
    setPayInfo(`<b>Error:</b> ${escapeHtml(e.message || 'No se pudo validar')}`, false);
    if(btn) btn.disabled = true;
  }
}

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');

    // refresca panel y limpia input
    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;
  }
};

// eventos
document.addEventListener('DOMContentLoaded', ()=>{
  const inp = document.getElementById('paySerie');
  if(inp){
    inp.addEventListener('input', ()=>{
      // consulta “suave” cuando ya hay algo escaneado
      if(inp.value.trim().length >= 3) consultarPremiada();
    });
    inp.addEventListener('keydown', (ev)=>{
      if(ev.key === 'Enter'){
        ev.preventDefault();
        consultarPremiada();
      }
    });
  }
});
</script>

<!-- ===================== REPORTES (TU MISMO BLOQUE) ===================== -->
<script>
let dtRep = null;

const REP_URL_REPORTE = 'api/raspadita_reporte.php';
const REP_URL_PUNTOS  = 'api/punto_venta_list.php';

function money(v){
  const n = Number.parseFloat(v || 0);
  return '$' + (Number.isFinite(n) ? n : 0).toFixed(2);
}
function badgeYes(v){
  return (parseInt(v||0,10)===1)
    ? '<span class="badge bg-warning text-dark">Sí</span>'
    : '<span class="badge bg-secondary">No</span>';
}
function badgeBloq(v){
  return (parseInt(v||0,10)===1)
    ? '<span class="badge bg-danger">Sí</span>'
    : '<span class="badge bg-secondary">No</span>';
}
function getResponsable(r){
  const resp = (r && (r.responsable || r.punto)) ? String(r.responsable || r.punto).trim() : '';
  return resp !== '' ? resp : 'SIN RESPONSABLE';
}
function setText(id, v){
  const el = document.getElementById(id);
  if(el) el.textContent = String(v ?? 0);
}
async function loadSimpleSelectRep(url, selectId, placeholderText){
  const sel = document.getElementById(selectId);
  if(!sel) return;

  sel.innerHTML = `<option value="0">${placeholderText || '— Todos —'}</option>`;

  const r = await fetch(url, { credentials: 'same-origin' });
  const text = await r.text();

  let j = null;
  try { j = JSON.parse(text); } catch(_) {}

  if(!j){
    console.error('Select API NO-JSON:', text);
    throw new Error('La API del select devolvió HTML. Revisa consola/Network.');
  }
  if(j.success !== true){
    throw new Error(j.message || 'No se pudo cargar select');
  }

  (j.data || []).forEach(it=>{
    const opt = document.createElement('option');
    opt.value = String(it.id ?? 0);
    opt.textContent = String(it.text ?? '');
    sel.appendChild(opt);
  });
}
function setFechasRepHoy(){
  const now = new Date();
  const ec  = new Date(now.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
  const y = ec.getFullYear(), m=String(ec.getMonth()+1).padStart(2,'0'), d=String(ec.getDate()).padStart(2,'0');
  const hoy = `${y}-${m}-${d}`;

  const ini = document.getElementById('repIni');
  const fin = document.getElementById('repFin');
  if(ini && !ini.value) ini.value = hoy;
  if(fin && !fin.value) fin.value = hoy;
}
function initRepTable(){
  if(dtRep) return;

  dtRep = $('#tbRep').DataTable({
    searching:true,
    lengthChange:false,
    pageLength:100,
    responsive:true,
    ordering:false,
    language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"},
    columnDefs: [
      { targets: 0, orderable:false, searchable:false, className:"text-center", width:"28px" },
      { targets: [4,6], className:"text-end" }
    ]
  });
}
window.cargarReporte = async function cargarReporte(){
  initRepTable();

  const fecha_ini = (document.getElementById('repIni')?.value || '').trim();
  const fecha_fin = (document.getElementById('repFin')?.value || '').trim();
  const id_punto  = parseInt((document.getElementById('repPunto')?.value || '0'), 10) || 0;
  const estado    = (document.getElementById('repEstado')?.value || '').trim();

  try{
    const j = await postJson(REP_URL_REPORTE, { fecha_ini, fecha_fin, id_punto, estado });

    const t = j.totales || {};
    setText('kReg', t.registros || 0);
    setText('kAsi', t.asignadas || 0);
    setText('kEnt', t.entregadas || 0);
    setText('kVen', t.vendidas || 0);
    setText('kGan', t.ganadoras || 0);
    setText('kBlo', t.bloqueadas || 0);

    dtRep.clear();
    (j.data || []).forEach((r, idx)=>{
      dtRep.row.add([
        idx + 1,
        `<b>${escapeHtml(r.serie || '')}</b>`,
        escapeHtml(r.estado || ''),
        escapeHtml(getResponsable(r)),
        money(r.valor),
        badgeYes(r.ganador),
        money(r.premio),
        badgeBloq(r.bloqueado),
        escapeHtml(r.updated_at || r.fecha_hora || '')
      ]);
    });
    dtRep.draw(false);

  }catch(e){
    console.error('cargarReporte:', e);
    Swal.fire('Error', e.message || 'No se pudo cargar', 'error');
  }
};

document.addEventListener('shown.bs.tab', async function (event) {
  const target = event?.target?.getAttribute('data-bs-target') || '';
  if (target === '#tab-reportes') {
    setFechasRepHoy();
    initRepTable();

    try{
      await loadSimpleSelectRep(REP_URL_PUNTOS, 'repPunto', '— Todos los puntos —');
    }catch(e){
      console.error('No se pudo cargar puntos:', e);
    }

    setTimeout(()=>window.cargarReporte(), 150);
  }
});

['repIni','repFin','repPunto','repEstado'].forEach(id=>{
  document.getElementById(id)?.addEventListener('change', ()=>{
    if(dtRep) window.cargarReporte();
  });
});
</script>

</body>
</html>
