<?php
/* =========================================================
   AVISOS EN MODAL (sin archivo externo) + FIX borrar aviso
   - Evita pantalla blanca: el DELETE y redirect ocurre
     ANTES de cualquier salida HTML.
   ========================================================= */
ob_start();

if (isset($_GET['del_aviso'])) {
    include 'concha.php';
    mysql_connect("$host","$usuario","$contra");
    mysql_select_db("$basedatos");

    $del_id = intval($_GET['del_aviso']);
    if ($del_id > 0) {
        mysql_query("DELETE FROM avisos WHERE ID = $del_id LIMIT 1");
    }

    // Volver siempre limpio (sin querystring)
    if (!headers_sent()) {
        header("Location: index.php");
        exit;
    }

    // Fallback si por algún motivo ya hubo salida
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body>
          <script>location.href='index.php';</script>
          </body></html>";
    exit;
}
?>

<?php include 'sesion_user.php';?>


<?php
// Construir URL sin protocolo ni barra final
$host = $_SERVER['HTTP_HOST'];
$uri  = $_SERVER['REQUEST_URI'];
$full_url = preg_replace('#/index\.php$#', '', $host . $uri);
$full_url = rtrim($full_url, '/');

// Consultar API
$api_url = 'https://xpace.com.ar/radiosnet/json_deuda_total.php?u=' . urlencode($full_url);
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $api_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 4,
]);
$respuesta = curl_exec($ch);
if (curl_errno($ch)) {
    curl_close($ch);
    return;
}
curl_close($ch);

$data = json_decode($respuesta, true);
$deuda = isset($data['deuda']) ? floatval($data['deuda']) : 0;
$md5   = isset($data['md5']) ? $data['md5'] : '';
$link_pago = ($md5 && ctype_alnum($md5)) ? "http://xpace.com.ar/radiosnet/panel.php?u=$md5" : '#';

// Umbrales
$limite_bloqueo = 66000;
$limite_alerta  = 49500;

/* ───────── BLOQUEO TOTAL (solo log) ───────── */
if ($deuda >= $limite_bloqueo) {
    $deuda_fmt = number_format($deuda, 0, '', '.');
    echo "<script>console.log('$full_url  - -  Sitio bloqueado por deuda: \$$deuda_fmt');</script>";
}

/* ───────── ADVERTENCIA (TOAST) ───────── */
elseif ($deuda >= $limite_alerta) {
    $hoy            = date('j');
    $dias_restantes = max(30 - intval($hoy), 1);
    $deuda_fmt      = number_format($deuda, 0, '', '.');

    echo "<script>console.log('$full_url  - -  Advertencia: deuda elevada \$$deuda_fmt, quedan $dias_restantes días');</script>";
} else {
    echo "<script>console.log('$full_url  - - Sitio habilitado, sin deuda significativa');</script>";
}
?>

<?php
/* =========================================================
   AVISOS: contador para badge (sin listado en pantalla)
   ========================================================= */
$avisos_count = 0;

include 'concha.php';
mysql_connect("$host","$usuario","$contra");
mysql_select_db("$basedatos");

$resCount = mysql_query("SELECT COUNT(*) AS c FROM avisos");
if ($resCount) {
    $rowC = mysql_fetch_assoc($resCount);
    $avisos_count = isset($rowC['c']) ? intval($rowC['c']) : 0;
    mysql_free_result($resCount);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=gb18030">

<title>Sistema Stock</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
/* Estilos del modal */
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 10% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
  max-width: 600px;
}

/* Estilos del botón de cierre */
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

/* Estilos del spinner de carga */
.spinner {
  border: 16px solid #f3f3f3;
  border-top: 16px solid #3498db;
  border-radius: 50%;
  width: 80px;
  height: 80px;
  animation: spin 2s linear infinite;
  margin: 20px auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* ====== NUEVO: layout de botones de pago ====== */
.pay-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-start;margin-top:10px}
.pay-actions form{display:inline-flex;gap:6px;align-items:center;margin-right:8px}
.btn-slim{font-size:11px;padding:4px 8px;border:1px solid #000}
.tag-pill{background:#222;color:#fff;border:1px solid #000;padding:3px 6px;font-size:11px;border-radius:4px}
.is-disabled{opacity:.6;pointer-events:none}

/* ====== NUEVO: Modo cine (overlay global) ====== */
.cine-overlay{position:fixed;inset:0;background:rgba(0,0,0,.88);z-index:99999;display:none}
.cine-box{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:#fff;text-align:center}
.cine-spin{width:70px;height:70px;border:8px solid #fff;border-top-color:transparent;border-radius:50%;
           animation:spin 1s linear infinite;margin:0 auto 12px}

/* ====== AVISOS: botón + badge ====== */
.avisos-wrap{margin-top:10px;margin-bottom:10px}
.btn-avisos{position:relative;border:1px solid #000;padding:6px 12px;font-weight:bold;background:#fff}
.avisos-badge{
  position:absolute; top:-8px; right:-8px;
  background:#d80000; color:#fff;
  font-size:11px; line-height:1;
  padding:4px 6px;
  border-radius:999px;
  border:2px solid #fff;
  min-width:22px;
  text-align:center;
}

/* ====== Modal AVISOS (cine) ====== */
.avisos-modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.88);z-index:99998}
.avisos-box{
  position:absolute;top:50%;left:50%;
  transform:translate(-50%,-50%);
  width:92%;max-width:900px;
  background:#fff;border-radius:10px;
  border:1px solid #111;
  padding:12px;
  max-height:86vh;
  overflow:auto;
}
.avisos-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
.avisos-title{font-size:18px;font-weight:bold}
.avisos-close{
  cursor:pointer;
  font-size:22px;
  font-weight:bold;
  padding:2px 10px;
  border:1px solid #000;
  border-radius:6px;
  background:#f3f3f3;
}
.aviso-card{border:1px solid #e0e0e0;border-radius:8px;padding:12px;margin-bottom:10px;background:#fff}

/* ====== NUEVO: Estilo moderno para movimientos - MÁS SUTIL ====== */
html {
  scroll-behavior: smooth;
}

.movimiento-card {
  background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%);
  border: 1px solid #00acc1;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 12px;
}

.movimiento-card.fiado {
  background: linear-gradient(135deg, #fff9c4 0%, #fff59d 100%);
  border-color: #fbc02d;
}

.movimiento-card.tarjeta {
  background: linear-gradient(135deg, #e1f5fe 0%, #b3e5fc 100%);
  border-color: #03a9f4;
}

.movimiento-card.descuento {
  background: linear-gradient(135deg, #ffe0b2 0%, #ffcc80 100%);
  border-color: #fb8c00;
}

.movimiento-card.anulado {
  background: linear-gradient(135deg, #e0e0e0 0%, #bdbdbd 100%);
  border-color: #757575;
}

.badge-pill-modern {
  display: inline-block;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: bold;
  margin: 3px;
  color: white;
}

.badge-digital {
  background: #000;
}

.badge-dividido {
  background: #000;
}

.badge-mayor {
  background: #4caf50;
}

.badge-descuento {
  background: #ff5722;
}

.badge-anulado {
  background: #f44336;
}

.btn-modern {
  border-radius: 6px;
  padding: 8px 14px;
  font-size: 13px;
  font-weight: 600;
  border: 1px solid #000;
  margin: 3px;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.btn-modern:hover {
  transform: translateY(-1px);
}

.btn-verde {
  background: #4caf50;
  color: white;
}

.btn-azul {
  background: #2196f3;
  color: white;
}

.btn-azul-pdf {
  background: #03a9f4;
  color: white;
}

.btn-rojo {
  background: #f44336;
  color: white;
}

.btn-amarillo {
  background: #ffc107;
  color: #000;
}

.btn-precio {
  background: white;
  color: #000;
  border: 2px solid #000;
  font-size: 16px;
  padding: 10px 18px;
  border-radius: 8px;
}

/* ====== NUEVO: Modal Pago Digital - Estilo Sutil ====== */
.modal-pago-digital {
  display: none;
  position: fixed;
  z-index: 10000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.6);
}

.modal-pago-content {
  background-color: #fff;
  margin: 8% auto;
  padding: 0;
  border: 2px solid #2196f3;
  width: 90%;
  max-width: 500px;
  border-radius: 12px;
}

.modal-pago-header {
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  color: white;
  padding: 18px 22px;
  border-radius: 10px 10px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-pago-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
}

.modal-pago-close {
  color: white;
  font-size: 26px;
  font-weight: bold;
  cursor: pointer;
  line-height: 1;
  transition: transform 0.2s;
}

.modal-pago-close:hover {
  transform: rotate(90deg);
}

.modal-pago-body {
  padding: 22px;
}

.pago-option {
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background: #f5f5f5;
}

.pago-option:hover {
  border-color: #2196f3;
  background: #e3f2fd;
  transform: translateX(3px);
}

.pago-option h4 {
  margin: 0 0 6px 0;
  font-size: 16px;
  color: #1976d2;
  font-weight: 700;
}

.pago-option p {
  margin: 0;
  font-size: 13px;
  color: #666;
}

.payment-methods-section {
  margin-top: 20px;
  padding-top: 18px;
  border-top: 2px solid #e0e0e0;
}

.payment-methods-section h4 {
  margin-bottom: 12px;
  font-size: 15px;
  color: #333;
  font-weight: 700;
}

.payment-methods-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.payment-method-btn {
  padding: 10px;
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  color: white;
  border: 1px solid #1565c0;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 700;
  transition: all 0.2s;
  text-align: center;
}

.payment-method-btn:hover {
  background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%);
  transform: translateY(-2px);
}

/* ====== NUEVO: Modal Fiado ====== */
.modal-fiado {
  display: none;
  position: fixed;
  z-index: 10000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.6);
}

.modal-fiado-content {
  background-color: #fff;
  margin: 10% auto;
  padding: 0;
  border: 2px solid #ffc107;
  width: 90%;
  max-width: 450px;
  border-radius: 12px;
}

.modal-fiado-header {
  background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);
  color: #000;
  padding: 18px 22px;
  border-radius: 10px 10px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-fiado-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
}

.modal-fiado-close {
  color: #000;
  font-size: 26px;
  font-weight: bold;
  cursor: pointer;
  line-height: 1;
  transition: transform 0.2s;
}

.modal-fiado-close:hover {
  transform: rotate(90deg);
}

.modal-fiado-body {
  padding: 22px;
}

.cliente-select {
  width: 100%;
  padding: 12px;
  border: 2px solid #ffc107;
  border-radius: 6px;
  font-size: 14px;
  margin-bottom: 15px;
  background: white;
}

.btn-confirmar-fiado {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);
  color: #000;
  border: 1px solid #ff9800;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-confirmar-fiado:hover {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
  transform: translateY(-2px);
}

@media (max-width: 576px) {
  .payment-methods-grid {
    grid-template-columns: 1fr;
  }
}
</style>

</head>

<body onload="document.forms['form14']['busqueda'].focus()">

<div class="container-fluid">
  <div class="row">
    <div class="col-lg-3 col-md-3 col-sm-12" style="background-color: #C8C8C8; border-right: solid; border-right-width: medium; border-width: 1px;">
      <?php include 'nav.php';?>
    </div>

    <div class="col-lg-9 col-md-9 col-sm-12">
      <?php include 'inc_buscar.php'; ?>
      <div style="padding-top:98px;"></div>

      <!-- ====== BOTÓN AVISOS (nuevo, sin ocupar pantalla) ====== -->
      <div class="avisos-wrap">
        <button type="button" id="btnAvisos" class="btn-avisos">
          AVISOS
          <?php if ($avisos_count > 0) { ?>
            <span class="avisos-badge"><?php echo $avisos_count; ?></span>
          <?php } ?>
        </button>
      </div>

      <? if ($opcion27 == 0) { ?>
        El boton <img src="AYUDAMINI.png" style="width:70px"> brinda ayuda sobre el item que esta encima de el.
        <hr>
        PARA COMENZAR, HAGA CLIC EN <b>NUEVA VENTA</b> (o presione la tecla <b>F2</b>)
      <?  };?>

      <? if ($activado == 'si') {} else {
        echo "<br><B style='color:red'>IMPORTANTE</B> <BR> TODOS LOS PRECIOS Y MOVIMIENTOS QUE REALICE EN ESTA DEMO <B>NO SE PIERDEN</B>. SE CONSERVA TODO TAL CUAL EN CASO DE COMPRAR EL SERVICIO.
<hr>
<b>AYUDA:</b> <a target='_blank' href='https://docs.google.com/document/d/1PxheA-sPM0W3O_KWE3vY-ZNXz74yNOqSMOXh5K2uYb4/edit?usp=sharing'>PRIMEROS PASOS CON EL SISTEMA</a>
<hr>
  ";
      };?>

      <?php
      // ---- FRAGMENTO PARA index.php ----
      // Se ejecutará una vez por hora usando una cookie
      if(!isset($_COOKIE['check_vencimientos']) || ($_COOKIE['check_vencimientos'] + 3600) < time()) {
          setcookie('check_vencimientos', time(), time() + 3600); 
          
          include 'concha.php';
          mysql_connect($host, $usuario, $contra);
          mysql_select_db($basedatos);

          $hoy = date('Ymd');

          $sql = "
            SELECT scv.id, scv.barcode, scv.lote, scv.cantidad_ingresada, scv.fecha_vencimiento,
                   a.titulo
            FROM stock_con_vencimientos scv
            JOIN articulos a ON scv.barcode = a.barcode
            WHERE scv.lote NOT LIKE '(a1)%'
              AND scv.lote NOT LIKE '(v1)%'
          ";
          $result = mysql_query($sql);

          while($row = mysql_fetch_assoc($result)) {
              $id_lote     = $row['id'];
              $lote        = $row['lote'];
              $cant        = $row['cantidad_ingresada'];
              $fecha_venc  = $row['fecha_vencimiento'];
              $titulo_art  = $row['titulo'];

              $fecha_hoy_dt  = DateTime::createFromFormat('Ymd', $hoy);
              $fecha_venc_dt = DateTime::createFromFormat('Ymd', $fecha_venc);
              
              $diff      = $fecha_hoy_dt->diff($fecha_venc_dt);
              $dias_rest = (int)$diff->format('%r%a');

              $imagen_alerta = "<img src='https://sistemastock.com/alertastock.png' "
                             . "alt='Alerta de Stock' width='150' style='float:left; margin-right:10px; margin-bottom:10px;'> <br>";

              if($dias_rest > 0 && $dias_rest <= 5) {
                  $texto_aviso = $imagen_alerta
                               . "ALERTA DE VENCIMIENTO<br>"
                               . "Faltan $dias_rest día(s) para que el lote '$lote' (cantidad: $cant) "
                               . "del producto '$titulo_art' caduque. ¡Apúrate a venderlo!";

                  $sql_insert_avisos = "
                    INSERT INTO avisos (ID, aviso) 
                    VALUES (NULL, '".mysql_real_escape_string($texto_aviso)."')
                  ";
                  mysql_query($sql_insert_avisos);

                  $nuevo_lote = '(a1)'.$lote;
                  $sql_update_lote = "
                    UPDATE stock_con_vencimientos 
                    SET lote = '".mysql_real_escape_string($nuevo_lote)."' 
                    WHERE id = '$id_lote' LIMIT 1
                  ";
                  mysql_query($sql_update_lote);

              } elseif($dias_rest <= 0) {
                  $texto_aviso = $imagen_alerta
                               . "LOTE VENCIDO<br>"
                               . "El lote '$lote' (cantidad: $cant) del producto '$titulo_art' "
                               . "ya está vencido. Si no lo vendiste todo ni lo devolviste a tu proveedor, deberías quitarlo del stock.";

                  $sql_insert_avisos = "
                    INSERT INTO avisos (ID, aviso) 
                    VALUES (NULL, '".mysql_real_escape_string($texto_aviso)."')
                  ";
                  mysql_query($sql_insert_avisos);

                  $nuevo_lote = '(v1)'.$lote;
                  $sql_update_lote = "
                    UPDATE stock_con_vencimientos 
                    SET lote = '".mysql_real_escape_string($nuevo_lote)."' 
                    WHERE id = '$id_lote' LIMIT 1
                  ";
                  mysql_query($sql_update_lote);
              }
          }

          mysql_free_result($result);
      }
      ?>

      <? if($version_bar == "si" ) { ?>
      <br>
      <a target="_blank" href="comandas.php">ABRIR COMADERA (PARA TABLET)</a>
      <br><br>

      <div class="row">
      <?php
      mysql_connect("$host","$usuario","$contra");
      mysql_select_db ("$basedatos");

      $sql = "SELECT * FROM `mesas`";
      $consulta = mysql_query ($sql);

      while ($row = mysql_fetch_array($consulta))
      {
          $ID_mesa = $row["ID"];
          $mesa = $row["mesa"];
          $atendida = mb_strtoupper($row["atendida"]);
      ?>
        <div class="col-lg-3 col-md-4 col-sm-6 col-4">
          <div style="background-color:#ffec83;padding:5px;border:solid;margin-bottom:38px;">
            <b>MESA <? echo $mesa ?></b> |
            <? if ($atendida == ''){echo "<img src=ledrojo.png> CERRADA"; } else { echo "<img src=ledverde.png> ABIERTA <br>ATENDIDA POR <B>$atendida</B>"; }; ?>
            <hr>

            <?php
            $sql3 = "SELECT * FROM `mesas_temp` WHERE `ID_mesa` = $ID_mesa";
            $consulta3 = mysql_query ($sql3);

            while ($row3 = mysql_fetch_array($consulta3))
            {
                $ID_temp = $row3["ID"];
                $barcode = $row3["barcode"];
                $cant = $row3["cant"];
                $ya_salio = $row3["ya_salio"];
            ?>
              <div class="tarjeta" style="border:solid;border-radius:9px;padding:5px;border-width:2px;background:#f0f0f0;margin-bottom:10px;">
                <?php
                $sql33 = "SELECT * FROM `articulos` WHERE `barcode` = $barcode LIMIT 1";
                $consulta33 = mysql_query ($sql33);

                while ($row33 = mysql_fetch_array($consulta33))
                {
                    $titulo = $row33["titulo"];
                    $cat = $row33["cat"];
                ?>
                  <a href="quitar_producto_mesa.php?ID=<? echo $ID_temp ?>"><img src="papelera.png" style="width:20px"></a>
                  <? if ($cat != 'BEBIDAS') { ?>
                    <? if ($ya_salio == 0) { echo "<img src='gorrorojo.png' style='width: 28px;'>"; } else { echo "<img src='gorroverde.png' style='width: 28px;'>"; }; ?>
                  <? };?>
                  <b><? echo $titulo ?></b>
                <?php
                }
                mysql_free_result($consulta33);
                ?>
                x <? echo $cant ?>
              </div>
            <?php
            }
            mysql_free_result($consulta3);
            ?>

            <? if ($atendida == '') {
              echo "<div style='text-align:center;background-color:green;color:white;'><a href='abrir_mesa.php?ID=$ID_mesa' style='color:white'>ABRIR MESA</a></div>";
            } else {
              echo "<div style='text-align:center;background-color:red;color:white;'><a href='cerrar_mesa.php?ID=$ID_mesa' style='color:white'>CERRAR MESA</a></div>";
            }; ?>
          </div>
        </div>
      <?php
      }
      mysql_free_result($consulta);
      ?>
      </div>
      <? };?>

      <hr />

      <?php
      $c = (int)$_GET['c'];
      $c = $c * 20;

      $aa = 0;
      include 'concha.php';
      mysql_connect("$host","$usuario","$contra");
      mysql_select_db ("$basedatos");

      $sql = "SELECT opcion33 FROM `configuracion` LIMIT 1;";
      $consulta = mysql_query ($sql);
      while ($row = mysql_fetch_array($consulta))
      {
          $opcion33  = $row["opcion33"];
      }
      mysql_free_result($consulta);

      if ($opcion33 == 0) {
      ?>

      <B>40 PRODUCTOS MÁS VENDIDOS (HAGA CLIC PARA UNA VENTA RAPIDA)</B><br />
      <? echo "<a href=actualizar_valor.php?opcion=opcion33&valor=1><button class='btn btn-danger'>OCULTAR PRODUCTOS MÁS VENDIDOS</button></a><BR>";?>

      <div style="text-align:center;">
      <?php
      $sql = "SELECT * FROM `populares` ORDER BY `cant` DESC  LIMIT 40";
      $consulta = mysql_query ($sql);

      while ($row = mysql_fetch_array($consulta))
      {
          $nombreb = $row["nombre"];
          $barcodeb = $row["barcode"];
          $colorb = $row["color"];
      ?>
        <a style="color:black;" href="nueva_venta.php?barcode=<? echo $barcodeb ?>">
          <div class="btn" style="background-color: <? echo $colorb ?>; margin: 6px; border-style: solid; border-color: black; font-size: 13px;">
            <b><? echo substr(mb_strtoupper($nombreb), 0, 30); ?></b>
          </div>
        </a>
      <?php
      }
      mysql_free_result($consulta);
      ?>
      </div>
      <hr />

      <?php
      } else {
          echo "<a href=actualizar_valor.php?opcion=opcion33&valor=0><button class='btn btn-success'>MOSTRAR PRODUCTOS MÁS VENDIDOS</button></a><BR>";
      };
      ?>

      <B>ÚLTIMOS 20 MOVIMIENTOS:</B><br />
      Hoy es <?php echo date(d)?>/<?php echo date(m) ?>/<?php echo date(Y) ?><hr />

      <?php
      $sql = "SELECT * FROM `ventas` ORDER BY ID desc LIMIT $c,20";
      $consulta = mysql_query ($sql);

      while ($row = mysql_fetch_array($consulta))
      {
          $ID_venta = $row["ID"];
          $fecha = $row["fecha"];
          $total = $row["total"];
          $usuario = $row["usuario"];
          $forma_pago = $row["forma_pago"];
          $ano = substr($fecha, 0,4);
          $mes = substr($fecha, 4,2);
          $dia = substr($fecha, 6,2);
          $hora = substr($fecha, 8,2);
          $min = substr($fecha, 10,2);
          
          // NUEVO: Determinar si debe mostrar botón Pago Digital
          $mostrar_pago_digital = true;
          if ($forma_pago == 'tarjeta' || $forma_pago == 'dividido' || $forma_pago == 'anulado') {
              $mostrar_pago_digital = false;
          }
      ?>

      <?php
      // NUEVO: Detectar si es MOV. A CAJA DIGITAL, FIADO o ANULADO
      $es_mov_caja_digital = ($forma_pago == 'tarjeta' && $total <= 0);
      $es_fiado = ($forma_pago == 'fiado');
      $es_anulado = ($forma_pago == 'anulado');
      
      if ($es_anulado) {
        // VERSIÓN SIMPLE PARA VENTA ANULADA - Solo recordatorio en rojo
        $monto_anulado = $total;
      ?>
        <div style="background:#ffebee;border:2px solid #f44336;border-radius:10px;padding:12px 18px;margin-bottom:10px;opacity:0.7;">
          <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">
            <div style="display:flex;align-items:center;gap:15px;flex-wrap:wrap;">
              <div style="font-size:12px;color:#999;">
                <img src="ultimaact.png" style="width:13px;vertical-align:middle;filter:grayscale(100%);">
                <?php echo "$hora"; ?>:<?php echo $min ?> |
                <?php
                $dhoy = date(d);
                $mhoy = date(m);
                if ($dia == $dhoy and $mes == $mhoy) { echo "hoy"; } else { echo "$dia/$mes"; };
                ?>
                -  #<?php echo $ID_venta; ?>
              </div>
              
              <div style="font-size:14px;color:#666;font-weight:600;text-decoration:line-through;">
                ❌ Anulada: <span style="color:#f44336;">$<?php echo number_format($monto_anulado, 2); ?></span>
              </div>
            </div>
            
            <span class="badge-pill-modern" style="background:#f44336;font-size:12px;padding:6px 14px;">
              VENTA ANULADA
            </span>
          </div>
        </div>
      <?php
      } elseif ($es_mov_caja_digital) {
        // Calcular monto movido (valor absoluto)
        $monto_movido = abs($total);
        
        // VERSIÓN SIMPLE PARA MOV. A CAJA DIGITAL
      ?>
        <div style="background:#f8f9fa;border:2px solid #dee2e6;border-radius:10px;padding:12px 18px;margin-bottom:10px;">
          <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">
            <div style="display:flex;align-items:center;gap:15px;flex-wrap:wrap;">
              <div style="font-size:12px;color:#666;">
                <img src="ultimaact.png" style="width:13px;vertical-align:middle;">
                <?php echo "$hora"; ?>:<?php echo $min ?> |
                <?php
                $dhoy = date(d);
                $mhoy = date(m);
                if ($dia == $dhoy and $mes == $mhoy) { echo "hoy"; } else { echo "$dia/$mes"; };
                ?>
                -  #<?php echo $ID_venta; ?>
              </div>
              
              <div style="font-size:14px;color:#333;font-weight:600;">
                💰 Movido: <span style="color:#28a745;">$<?php echo number_format($monto_movido, 2); ?></span>
              </div>
              
              <?php
              $venta_origen = null;
              $sql_origen = "SELECT * FROM ventas WHERE ID < $ID_venta AND ABS(total - " . abs($total) . ") < 0.01 ORDER BY ID DESC LIMIT 1";
              $result_origen = mysql_query($sql_origen);
              if ($result_origen && mysql_num_rows($result_origen) > 0) {
                $row_origen = mysql_fetch_assoc($result_origen);
                $venta_origen = $row_origen['ID'];
                mysql_free_result($result_origen);
              }
              
              if ($venta_origen) {
              ?>
                <a href="#venta_<?php echo $venta_origen; ?>" style="text-decoration:none;">
                  <span class="badge-pill-modern" style="background:#17a2b8;font-size:11px;">
                    🔗 Venta #<?php echo $venta_origen; ?>
                  </span>
                </a>
              <?php } ?>
            </div>
            
            <span class="badge-pill-modern" style="background:#dc3545;font-size:12px;padding:6px 14px;">
              MOV. A CAJA DIGITAL
            </span>
          </div>
        </div>
      <?php
      } elseif ($es_fiado) {
        // VERSIÓN SIMPLE PARA FIADO
        $monto_fiado = $total;
        
        // Buscar venta original (la venta con el mismo monto justo antes)
        $venta_origen = null;
        $sql_origen = "SELECT * FROM ventas WHERE ID < $ID_venta AND ABS(total - $total) < 0.01 AND forma_pago != 'fiado' ORDER BY ID DESC LIMIT 1";
        $result_origen = mysql_query($sql_origen);
        if ($result_origen && mysql_num_rows($result_origen) > 0) {
          $row_origen = mysql_fetch_assoc($result_origen);
          $venta_origen = $row_origen['ID'];
          mysql_free_result($result_origen);
        }
      ?>
        <div style="background:#fffef5;border:2px solid #ffc107;border-radius:10px;padding:12px 18px;margin-bottom:10px;">
          <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">
            <div style="display:flex;align-items:center;gap:15px;flex-wrap:wrap;">
              <div style="font-size:12px;color:#666;">
                <img src="ultimaact.png" style="width:13px;vertical-align:middle;">
                <?php echo "$hora"; ?>:<?php echo $min ?> |
                <?php
                $dhoy = date(d);
                $mhoy = date(m);
                if ($dia == $dhoy and $mes == $mhoy) { echo "hoy"; } else { echo "$dia/$mes"; };
                ?>
                -  #<?php echo $ID_venta; ?>
              </div>
              
              <div style="font-size:14px;color:#333;font-weight:600;">
                💰 Fiado: <span style="color:#ff9800;">$<?php echo number_format($monto_fiado, 2); ?></span>
              </div>
              
              <?php if ($venta_origen) { ?>
                <a href="#venta_<?php echo $venta_origen; ?>" style="text-decoration:none;">
                  <span class="badge-pill-modern" style="background:#17a2b8;font-size:11px;">
                    🔗 Venta #<?php echo $venta_origen; ?>
                  </span>
                </a>
              <?php } ?>
            </div>
            
            <span class="badge-pill-modern" style="background:#ffc107;color:#000;font-size:12px;padding:6px 14px;">
              FIADO
            </span>
          </div>
        </div>
      <?php
      } else {
        // VERSIÓN NORMAL CON TODOS LOS BOTONES
      ?>
      <div class="movimiento-card <?php 
        if ($forma_pago == 'fiado') echo 'fiado';
        elseif ($forma_pago == 'tarjeta') echo 'tarjeta';
        elseif ($forma_pago == 'DESCUENTO') echo 'descuento';
        elseif ($forma_pago == 'anulado') echo 'anulado';
      ?>" id="venta_<?php echo $ID_venta; ?>">

        <div class="row">
          <div class="col-12">

            <div style="font-size:12px;color:#666;margin-bottom:10px;">
              <img src="ultimaact.png" style="width:13px">
              <?php echo "$hora"; ?>:<?php echo $min ?> |
              <?php
              $dhoy = date(d);
              $mhoy = date(m);
              if ($dia == $dhoy and $mes == $mhoy) { echo "hoy"; } else { echo "$dia/$mes"; };
              ?>
              -  #<?php echo $ID_venta; ?>
            </div>

            <!-- TODOS LOS BOTONES EN UNA SOLA FILA -->
            <div style="display:flex;flex-wrap:wrap;gap:6px;align-items:center;">
              <button type="button" class="btn-modern btn-precio">
                $ <?php echo round($total, 2); ?>
              </button>

              <button type="button" class="btn-modern btn-verde openModal" data-url="ver_detalle_venta.php?ID=<?php echo $ID_venta ?>">
                <img style="filter:invert();width:16px;" src="https://sistemastock.com/misistema/icons/ver_detalles.png"> Ver Detalle
              </button>

              <button type="button" class="btn-modern btn-azul openModal" data-url="imprimir_ticket_barra_especial.php?ID=<?php echo $ID_venta ?>">
                <img style="filter:invert();width:16px;" src="https://sistemastock.com/misistema/icons/imprimir_boton.png"> Imprimir Ticket
              </button>

              <button type="button" class="btn-modern btn-azul openModal" data-url="imprimir_ticket_barra_especial_1.php?ID=<?php echo $ID_venta ?>">
                <img style="filter:invert();width:16px;" src="https://sistemastock.com/misistema/icons/imprimir_boton.png"> V2
              </button>

              <a href="creapdf.php?ID=<?php echo $ID_venta ?>" target="_blank" style="text-decoration:none;">
                <button type="button" class="btn-modern btn-azul-pdf">
                  <img style="filter:invert();width:16px;" src="https://sistemastock.com/misistema/icons/imprimir_boton.png"> PDF
                </button>
              </a>

              <?php  if ($forma_pago != 'anulado') { ?>
                <?php  if ($forma_pago == 'tarjeta') { ?>
                  <button type="button" class="btn-modern btn-rojo openModal" data-url="anular_venta_tarjeta.php?ID=<?php echo $ID_venta ?>">
                    <img style="filter: invert(); width: 16px;" src="https://sistemastock.com/misistema/icons/anular_venta.png"> Anular Venta Tarjeta
                  </button>
                <?php } else { ?>
                  <button type="button" class="btn-modern btn-rojo openModal" data-url="anular_venta.php?ID=<?php echo $ID_venta ?>">
                    <img style="filter:invert();width:16px;" src="https://sistemastock.com/misistema/icons/anular_venta.png"> Anular Venta
                  </button>
                <?php } ?>
              <?php } ?>

              <!-- BADGES -->
              <?php  if ($forma_pago == 'POR MAYOR') { ?>
                <span class="badge-pill-modern badge-mayor">VENTA POR MAYOR</span>
              <?php } ?>
              
              <?php  if ($forma_pago == 'DESCUENTO') { ?>
                <span class="badge-pill-modern badge-descuento">VENTA CON DESCUENTO</span>
              <?php } ?>
              
              <?php  if ($forma_pago == 'AUMENTO') { ?>
                <span class="badge-pill-modern" style="background:#00bcd4;">VENTA CON AUMENTO</span>
              <?php } ?>
              
              <?php  if ($forma_pago == 'anulado') { ?>
                <span class="badge-pill-modern badge-anulado">VENTA ANULADA</span>
              <?php } ?>

              <?php if ($forma_pago == 'tarjeta') { ?> 
                <span class="badge-pill-modern badge-digital">PAGO DIGITAL</span>
              <?php } ?>
              
              <?php if ($forma_pago == 'dividido') { ?> 
                <span class="badge-pill-modern badge-dividido">PAGO DIVIDIDO</span>
              <?php } ?>

              <!-- BOTÓN PAGO DIGITAL -->
              <?php if ($mostrar_pago_digital) { ?>
                <button type="button" 
                        class="btn-modern openPagoDigitalModal" 
                        data-id="<?php echo $ID_venta ?>" 
                        data-total="<?php echo $total ?>"
                        style="background:linear-gradient(135deg, #2196f3 0%, #1976d2 100%);color:white;border:1px solid #1565c0;font-size:13px;padding:8px 14px;">
                  💳 PAGO DIGITAL
                </button>
              <?php } ?>

              <!-- BOTÓN FIADO -->
              <?php if ($forma_pago == 'fiado') { ?> 
                <span class="badge-pill-modern btn-amarillo">FIADO</span>
              <?php } else { ?>
                <button type="button" 
                        class="btn-modern btn-amarillo openFiadoModal" 
                        data-id="<?php echo $ID_venta ?>">
                  💰 Pagó con Fiado
                </button>
              <?php } ?>
            </div>

          </div>
        </div>
      </div>
      <?php
      } // Fin del if/else es_anulado/es_mov_caja_digital/es_fiado
      ?>

      <?php
      }
      mysql_free_result($consulta);
      ?>

      <HR>

      <div style="font-size:21px;">
      <?php
      function imprimirPaginador($c) {
          $rango = 5;
          $inicio = max(1, $c - $rango);
          $fin = min(200, $c + $rango);
          for ($i = $inicio; $i <= $fin; $i++) {
              if ($i == $c) {
                  echo "($i) ";
                  echo "/ ";
              } else {
                  echo "<a href='index.php?c=$i'>$i</a> / ";
              }
          }
      }

      $c = isset($_GET['c']) ? intval($_GET['c']) : 1;
      imprimirPaginador($c);
      ?>
      </div>

      <HR>
      <? if ($c > 0) { ?>
        <a href="index.php?c=<? $ccc = $c - 1; echo $ccc; ?>" class="btn btn-primary">< ANTERIOR</a>
      <? } ?>
      <a href="index.php?c=<? $cccc = $c + 1; echo $cccc; ?>" class="btn btn-primary">SIGUIENTE ></a>
      <HR>
      PARA VER MÁS MOVIMIENTOS HAGA CLIC EN <B>HACER CAJA</B>
    </div>
  </div>
</div>

<!-- ====== MODAL AVISOS (cine, dentro de index.php) ====== -->
<div id="avisosModal" class="avisos-modal">
  <div class="avisos-box">
    <div class="avisos-head">
      <div class="avisos-title">AVISOS PENDIENTES</div>
      <div id="avisosClose" class="avisos-close">X</div>
    </div>

    <?php
    // Render avisos acá mismo
    include 'concha.php';
    mysql_connect("$host","$usuario","$contra");
    mysql_select_db("$basedatos");

    $resAvisos = mysql_query("SELECT * FROM avisos ORDER BY ID DESC");
    $hayAvisos = 0;

    if ($resAvisos) {
        while ($rowA = mysql_fetch_array($resAvisos)) {
            $hayAvisos = 1;
            $ID_aviso = (int)$rowA["ID"];
            $aviso = $rowA["aviso"];
            ?>
            <div class="aviso-card">
              <div style="font-size:14px;line-height:1.35;">
                <?php echo $aviso; ?>
              </div>
              <div style="margin-top:10px;">
                <a class="btn btn-danger" style="border:1px solid #000;"
                   href="index.php?del_aviso=<?php echo $ID_aviso; ?>">
                   RECIBIDO, BORRAR ESTE AVISO.
                </a>
              </div>
            </div>
            <?php
        }
        mysql_free_result($resAvisos);
    }

    if (!$hayAvisos) {
        echo "<div class='alert alert-success' style='border:1px solid #000;'>No hay avisos pendientes.</div>";
    }
    ?>
  </div>
</div>

<!-- ====== NUEVO: MODAL PAGO DIGITAL ====== -->
<div id="pagoDigitalModal" class="modal-pago-digital">
  <div class="modal-pago-content">
    <div class="modal-pago-header">
      <h3>💳 Opciones de Pago Digital</h3>
      <span class="modal-pago-close" id="closePagoDigital">&times;</span>
    </div>
    <div class="modal-pago-body">
      <div class="pago-option" id="pagoTotal">
        <h4>✅ Pagar el Total</h4>
        <p>Cobrar el monto completo de forma digital</p>
      </div>
      
      <div class="pago-option" id="pagoParcial">
        <h4>➗ Pago Parcial</h4>
        <p>Dividir el pago entre efectivo y digital</p>
      </div>
      
      <div id="paymentMethodsSection" class="payment-methods-section" style="display:none;">
        <h4>Selecciona el método de pago:</h4>
        <div class="payment-methods-grid">
          <button class="payment-method-btn" data-metodo="M.P.DEBITO">💳 DÉBITO</button>
          <button class="payment-method-btn" data-metodo="M.P.CREDITO">💳 CRÉDITO</button>
          <button class="payment-method-btn" data-metodo="M.P.TRANSFERENCIA">🔄 TRANSFERENCIA</button>
          <button class="payment-method-btn" data-metodo="M.P.QR">📱 QR</button>
          <button class="payment-method-btn" data-metodo="M.P.MERCADO.PAGO">🛒 MERCADO PAGO</button>
          <button class="payment-method-btn" data-metodo="M.P.MODO">📲 MODO</button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ====== NUEVO: MODAL FIADO ====== -->
<div id="fiadoModal" class="modal-fiado">
  <div class="modal-fiado-content">
    <div class="modal-fiado-header">
      <h3>💰 Pago con Fiado</h3>
      <span class="modal-fiado-close" id="closeFiado">&times;</span>
    </div>
    <div class="modal-fiado-body">
      <p style="margin-bottom:15px;color:#666;font-size:14px;">Seleccione el cliente para registrar el pago fiado:</p>
      <select id="clienteFiadoSelect" class="cliente-select">
        <option value="">Seleccione un cliente...</option>
        <?php
        mysql_connect("$host","$usuario","$contra");
        mysql_select_db("$basedatos");
        $sql_clientes = "SELECT * FROM `clientes` ORDER BY nombre";
        $consulta_clientes = mysql_query($sql_clientes);
        while ($row_cliente = mysql_fetch_array($consulta_clientes)) {
          echo '<option value="'.$row_cliente["ID"].'">'.$row_cliente["nombre"].'</option>';
        }
        mysql_free_result($consulta_clientes);
        ?>
      </select>
      <button id="btnConfirmarFiado" class="btn-confirmar-fiado">
        Confirmar Pago Fiado
      </button>
    </div>
  </div>
</div>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-146398018-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-146398018-1');
</script>

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

<script type="text/javascript">
window.setInterval(function(){
  $('.grid').isotope({ itemSelector: '.grid-item' });
}, 2000);
</script>

<script language=javascript>
function ventanaSecundaria56 (URL){
   window.open(URL,"ventana1","width:600,height:500,scrollbars=NO")
}
</script>

<script language="javascript">
function PulsarTecla(event)
{
    tecla = event.keyCode;
    if(tecla==113)
    {
        location.href ='nueva_venta.php';
    }
}
window.onkeydown=PulsarTecla;
</script>

<!-- Modal (tu modal de iframe existente para detalle/impresión) -->
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <div id="spinner" class="spinner"></div>
    <iframe id="myIframe" src="" style="width: 100%; height: 400px;"></iframe>
  </div>
</div>

<script>
  var modal = document.getElementById("myModal");
  var btns = document.getElementsByClassName("openModal");
  var closeBtn = document.getElementsByClassName("close")[0];
  var iframe = document.getElementById("myIframe");
  var spinner = document.getElementById("spinner");

  function openModal(url) {
    modal.style.display = "block";
    spinner.style.display = "block";
    iframe.style.display = "none";
    iframe.src = url;
  }

  function closeModal() {
    modal.style.display = "none";
    spinner.style.display = "none";
    iframe.src = "";
  }

  for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function() {
      var url = this.getAttribute("data-url");
      openModal(url);
    });
  }

  closeBtn.addEventListener("click", closeModal);
  window.addEventListener("click", function(event) {
    if (event.target == modal) {
      closeModal();
    }
  });

  iframe.addEventListener("load", function() {
    spinner.style.display = "none";
    iframe.style.display = "block";
  });
</script>

<script>
// ====== AVISOS: abrir/cerrar modal cine ======
(function(){
  var btn = document.getElementById('btnAvisos');
  var modalA = document.getElementById('avisosModal');
  var closeA = document.getElementById('avisosClose');

  function openAvisos(){ modalA.style.display = 'block'; }
  function closeAvisos(){ modalA.style.display = 'none'; }

  if (btn) btn.addEventListener('click', openAvisos);
  if (closeA) closeA.addEventListener('click', closeAvisos);

  window.addEventListener('click', function(e){
    if (e.target === modalA) closeAvisos();
  });

  window.addEventListener('keydown', function(e){
    if (e.keyCode === 27) closeAvisos(); // ESC
  });
})();
</script>

<!-- ====== Scripts ====== -->
<script>
(function(){
  // ===== MODAL PAGO DIGITAL =====
  var modalPago = document.getElementById('pagoDigitalModal');
  var closePago = document.getElementById('closePagoDigital');
  var pagoTotalBtn = document.getElementById('pagoTotal');
  var pagoParcialBtn = document.getElementById('pagoParcial');
  var methodsSection = document.getElementById('paymentMethodsSection');
  var methodBtns = document.querySelectorAll('.payment-method-btn');
  
  var currentIdVenta = null;
  var currentTotal = 0;
  var tipoPago = null;
  var montoPagar = 0;
  
  var openPagoBtns = document.querySelectorAll('.openPagoDigitalModal');
  for (var i = 0; i < openPagoBtns.length; i++) {
    openPagoBtns[i].addEventListener('click', function() {
      currentIdVenta = this.getAttribute('data-id');
      currentTotal = parseFloat(this.getAttribute('data-total'));
      modalPago.style.display = 'block';
      methodsSection.style.display = 'none';
      tipoPago = null;
    });
  }
  
  function cerrarModalPago() {
    modalPago.style.display = 'none';
    currentIdVenta = null;
    currentTotal = 0;
    tipoPago = null;
    montoPagar = 0;
    methodsSection.style.display = 'none';
  }
  
  if (closePago) closePago.addEventListener('click', cerrarModalPago);
  window.addEventListener('click', function(e) {
    if (e.target === modalPago) cerrarModalPago();
  });
  
  if (pagoTotalBtn) {
    pagoTotalBtn.addEventListener('click', function() {
      tipoPago = 'total';
      montoPagar = currentTotal;
      methodsSection.style.display = 'block';
    });
  }
  
  if (pagoParcialBtn) {
    pagoParcialBtn.addEventListener('click', function() {
      var monto = prompt('Ingrese el monto a pagar digitalmente:', currentTotal);
      if (monto && !isNaN(monto) && parseFloat(monto) > 0 && parseFloat(monto) <= currentTotal) {
        tipoPago = 'parcial';
        montoPagar = parseFloat(monto);
        methodsSection.style.display = 'block';
      } else if (monto !== null) {
        alert('Por favor ingrese un monto válido entre 0 y ' + currentTotal);
      }
    });
  }
  
  for (var j = 0; j < methodBtns.length; j++) {
    methodBtns[j].addEventListener('click', function() {
      var metodo = this.getAttribute('data-metodo');
      if (!currentIdVenta || !tipoPago) {
        alert('Error: Datos incompletos');
        return;
      }
      var url = tipoPago === 'total' ? 'pago_con_tarjeta.php?ID=' + currentIdVenta : 'pago_con_tarjeta_parte.php?ID=' + currentIdVenta + '&cuanto=' + montoPagar;
      var form = document.createElement('form');
      form.method = 'POST';
      form.action = url;
      var inputId = document.createElement('input');
      inputId.type = 'hidden';
      inputId.name = 'ID_venta';
      inputId.value = currentIdVenta;
      form.appendChild(inputId);
      var inputMedio = document.createElement('input');
      inputMedio.type = 'hidden';
      inputMedio.name = 'medio_p';
      inputMedio.value = metodo;
      form.appendChild(inputMedio);
      if (tipoPago === 'parcial') {
        var inputCuanto = document.createElement('input');
        inputCuanto.type = 'hidden';
        inputCuanto.name = 'cuanto';
        inputCuanto.value = montoPagar;
        form.appendChild(inputCuanto);
      }
      document.body.appendChild(form);
      form.submit();
    });
  }
  
  // ===== MODAL FIADO =====
  var modalFiado = document.getElementById('fiadoModal');
  var closeFiado = document.getElementById('closeFiado');
  var clienteSelect = document.getElementById('clienteFiadoSelect');
  var btnConfirmar = document.getElementById('btnConfirmarFiado');
  var currentIdVentaFiado = null;
  
  var openFiadoBtns = document.querySelectorAll('.openFiadoModal');
  for (var k = 0; k < openFiadoBtns.length; k++) {
    openFiadoBtns[k].addEventListener('click', function() {
      currentIdVentaFiado = this.getAttribute('data-id');
      modalFiado.style.display = 'block';
      clienteSelect.value = '';
    });
  }
  
  function cerrarModalFiado() {
    modalFiado.style.display = 'none';
    currentIdVentaFiado = null;
    clienteSelect.value = '';
  }
  
  if (closeFiado) closeFiado.addEventListener('click', cerrarModalFiado);
  window.addEventListener('click', function(e) {
    if (e.target === modalFiado) cerrarModalFiado();
  });
  
  if (btnConfirmar) {
    btnConfirmar.addEventListener('click', function() {
      var clienteId = clienteSelect.value;
      if (!clienteId) {
        alert('Por favor seleccione un cliente');
        return;
      }
      if (!currentIdVentaFiado) {
        alert('Error: ID de venta no disponible');
        return;
      }
      var form = document.createElement('form');
      form.method = 'POST';
      form.action = 'pago_con_fiado.php';
      var inputVenta = document.createElement('input');
      inputVenta.type = 'hidden';
      inputVenta.name = 'ID_venta';
      inputVenta.value = currentIdVentaFiado;
      form.appendChild(inputVenta);
      var inputCliente = document.createElement('input');
      inputCliente.type = 'hidden';
      inputCliente.name = 'ID_cliente';
      inputCliente.value = clienteId;
      form.appendChild(inputCliente);
      var inputButton = document.createElement('input');
      inputButton.type = 'hidden';
      inputButton.name = 'button2';
      inputButton.value = 'Pagó con Fiado';
      form.appendChild(inputButton);
      document.body.appendChild(form);
      form.submit();
    });
  }
  
  window.addEventListener('keydown', function(e) {
    if (e.keyCode === 27) {
      cerrarModalPago();
      cerrarModalFiado();
    }
  });
})();
</script>

<script>
(function () {
  function ensureOverlay() {
    var o = document.getElementById('cine');
    if (!o) {
      o = document.createElement('div');
      o.id = 'cine';
      o.className = 'cine-overlay';
      o.innerHTML =
        '<div class="cine-box">' +
          '<div class="cine-spin"></div>' +
          '<div>Procesando…</div>' +
        '</div>';
      document.body.appendChild(o);
    }
    return o;
  }

  function showCine() { ensureOverlay().style.display = 'block'; }

  function armOneClickProtection() {
    var forms = document.querySelectorAll('form.cine-on-submit');
    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function (e) {
        if (this.dataset.sending === '1') {
          e.preventDefault();
          return false;
        }
        this.dataset.sending = '1';

        var btns = this.querySelectorAll('button, input[type="submit"]');
        for (var j = 0; j < btns.length; j++) {
          var b = btns[j];
          b.disabled = true;
          if (b.tagName === 'INPUT' && b.type === 'submit') {
            b.value = (b.value || 'Enviando') + '…';
          } else if (b.tagName === 'BUTTON') {
            b.textContent = (b.textContent || 'Enviando') + '…';
          }
          if (b.classList) b.classList.add('is-disabled');
        }

        showCine();
      }, false);
    }
  }

  document.addEventListener('DOMContentLoaded', armOneClickProtection);
  window.SistemaStockCine = { show: showCine };
})();
</script>

</body>
</html>

<?php
mysql_db_query("sistemas_base","
INSERT INTO `utilizados` (`tabla`, `user`) VALUES ('$basedatos', '$dom');
");
?>