<?php include 'sesion_user.php';?>
<!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=utf-8" />
<title>Finalizar Venta - 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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<style>
/* ====== ESTILOS MODERNOS ====== */
body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.container-fluid {
  background: white;
  min-height: 100vh;
}

.item-card {
  background: #fff;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 10px;
  border: 2px solid #e0e0e0;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.item-card:nth-child(even) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.item-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.promo-card {
  background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
  border: 3px solid #28a745;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.2);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.02); }
}

.total-badge {
  position: fixed;
  top: 20px;
  right: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 30px;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
  z-index: 1000;
  font-size: 32px;
  font-weight: bold;
  border: 3px solid #5568d3;
}

.section-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 5px 20px rgba(102, 126, 234, 0.3);
}

.btn-modern {
  border-radius: 10px;
  padding: 12px 24px;
  font-weight: 600;
  border: 2px solid #000;
  margin: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.btn-modern:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0,0,0,0.2);
}

.btn-verde {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
}

.btn-azul {
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  color: white;
}

.btn-rojo {
  background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
  color: white;
}

.btn-amarillo {
  background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);
  color: #000;
}

.btn-morado {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.form-control-modern {
  border: 2px solid #667eea;
  border-radius: 10px;
  padding: 10px 15px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.form-control-modern:focus {
  border-color: #764ba2;
  box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
  outline: none;
}

.movimiento-card {
  background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%);
  border: 2px solid #00acc1;
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.badge-pill-modern {
  display: inline-block;
  padding: 6px 15px;
  border-radius: 20px;
  font-size: 12px;
  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;
}

.badge-aumento {
  background: #00bcd4;
}

.iframe-container {
  background: white;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.1);
  border: 2px solid #e0e0e0;
}

/* Modal Styles */
.modal {
  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);
  backdrop-filter: blur(5px);
}

.modal-content {
  background-color: #fefefe;
  margin: 5% auto;
  padding: 0;
  border: 3px solid #667eea;
  width: 90%;
  max-width: 800px;
  border-radius: 15px;
  box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}

.close {
  color: white;
  float: right;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  line-height: 1;
  transition: transform 0.2s;
}

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

.spinner {
  border: 8px solid #f3f3f3;
  border-top: 8px solid #667eea;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  animation: spin 1s linear infinite;
  margin: 20px auto;
}

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

.spinner-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(102, 126, 234, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.operations-card {
  background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
  border-radius: 15px;
  padding: 25px;
  margin-bottom: 20px;
  border: 2px solid #e0e0e0;
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.operations-card h3 {
  color: #667eea;
  font-weight: 700;
  margin-bottom: 20px;
  border-bottom: 3px solid #667eea;
  padding-bottom: 10px;
}

.form-group-modern {
  margin-bottom: 20px;
}

.form-group-modern label {
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

@media (max-width: 768px) {
  .total-badge {
    position: relative;
    top: 0;
    right: 0;
    margin-bottom: 20px;
    text-align: center;
  }
}

.alert-modern {
  border-radius: 12px;
  padding: 15px 20px;
  border: 2px solid;
  margin-bottom: 15px;
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.alert-info {
  background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
  border-color: #17a2b8;
  color: #0c5460;
}
</style>

</head>

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

<div class="spinner-overlay" id="spinner">
  <div class="spinner"></div>
</div>

<div class="container-fluid">
  <div class="row">
    <div class="col-lg-3 col-md-3 col-sm-12" style="background-color: #dfdfdf;">
      <?php include 'nav.php';?>
    </div>

    <div class="col-lg-9 col-md-9 col-sm-12">
      <?php
      include 'concha.php';
      mysql_connect("$host","$usuario","$contra");
      mysql_select_db ("$basedatos");

      $sql = "SELECT * FROM `caja_cigarrillos` ORDER BY ID desc LIMIT 1";
      $consulta = mysql_query ($sql);
      $monto_descuento_total = 0;
      
      while ($row = mysql_fetch_array($consulta)) {
        $total_caja_cigarrillo  = $row["total_caja"];
      }
      mysql_free_result($consulta);

      $sql = "SELECT * FROM `ID_ventas` LIMIT 1";
      $consulta = mysql_query ($sql);
      
      while ($row = mysql_fetch_array($consulta)) {
        $ID_venta = $row["ID"];
      }
      mysql_free_result($consulta);
      ?>

      <div class="section-header">
        <h2><i class="fa fa-shopping-cart"></i> VENTA Nº <?php echo $ID_venta ?></h2>
      </div>

      <div class="section-header" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
        <h3><i class="fa fa-list"></i> DETALLE DE LA COMPRA</h3>
      </div>

      <?php
      $total = 0;
      mysql_connect("$host","$usuario","$contra");
      mysql_select_db ("$basedatos");

      $sql = "SELECT * FROM `movimientos` WHERE `ID_venta` = '$ID_venta'";
      $consulta = mysql_query($sql);
      $numeroa = mysql_num_rows($consulta);

      $parte2 = '';
      $numerob = 0;
      $nnnn = 0;
      $promo_detectada = false;

      while ($row = mysql_fetch_array($consulta)) {
        $ID_articulo = $row["ID_articulo"];
        $precio = $row["precio"];
        $cantidad = $row["cantidad"];
        $detalle = $row["detalle"];

        if ($multicaja == 1) { mysql_select_db("$basedatos_multicaja"); }

        $sql22 = "SELECT * FROM `articulos` WHERE `ID` = '$ID_articulo' LIMIT 1";
        $consulta22 = mysql_query($sql22);
        $row22 = mysql_fetch_array($consulta22);

        $titulo = $row22["titulo"];
        $foto = $row22["foto"];
        $stock = $row22["stock"];
        $barcode = $row22["barcode"];
        $precio_costo = $row22["precio_costo"];
        $cat = $row22["cat"];
        $limite = $row22["limite"];
        $ID_producto = $row22["ID"];
        
        // Verificar promociones
        $hoy = date('Y-m-d');
        $sql_promo = "SELECT * FROM promociones_scanntech WHERE vigencia_desde <= '$hoy' AND vigencia_hasta >= '$hoy'";
        $result_promo = mysql_query($sql_promo);
        
        while ($promo = mysql_fetch_array($result_promo)) {
          $json = json_decode($promo["detalle"], true);
          if (!isset($json["condiciones"]["items"])) continue;

          foreach ($json["condiciones"]["items"] as $item) {
            if (!isset($item["articulos"])) continue;
            foreach ($item["articulos"] as $articulo) {
              if ($articulo["codigoBarras"] == $barcode) {
                $cantidad_requerida = $item["cantidad"];
                if ($cantidad >= $cantidad_requerida) {
                  $promo_detectada = true;
                  $precio_base = $precio; 
                  $promo_tipo = '';

                  if (isset($json["precio"])) {
                    $promo_tipo = 'Precio fijo $'.number_format($json["precio"], 2);
                    $precio = $json["precio"] / $cantidad_requerida;
                  }
                  elseif (isset($json["descuento"])) {
                    $promo_tipo = $json["descuento"].'% OFF';
                    $precio -= $precio * $json["descuento"] / 100;
                  }
                  elseif (isset($json["paga"])) {
                    $promo_tipo = $cantidad_requerida.'x'.$json["paga"];
                    $precio = ($precio * $json["paga"]) / $cantidad_requerida;
                  }

                  $descuento_linea = ($precio_base - $precio) * $cantidad;
                  $promo_barcode = $barcode;
                  $promo_desc = addslashes($titulo);
                  $promo_descuento = $descuento_linea;
                  $promo_cant = 1;
                  $monto_descuento_total += $descuento_linea;
                  break 2;
                }
              }
            }
          }
        }
        mysql_free_result($result_promo);
        mysql_free_result($consulta22);

        $stock_ahora = $stock - $cantidad;
        $total_c = $precio * $cantidad;
        $precio_costo_total = $precio_costo * $cantidad;

        $numerob++;
        $coma = ($numeroa != $numerob) ? "," : "";

        if ($barcode == 151818 or $barcode == 10000100001) {
          $barcode22 = "";
        } else {
          $barcode22 = $barcode;
        }

        $precio_original = $precio;
        if (strpos($barcode, 'PROMO') !== false) {
          $precio = 0;
          $total_c = 0;
          $promo_detectada = true;
        }

        $parte2 .= '{
          "codigoArticulo": "'.$barcode.'",
          "codigoBarras": "'.$barcode22.'",
          "descripcionArticulo": "'.$titulo.'",
          "cantidad": '.$cantidad.',
          "importeUnitario": '.$precio.',
          "importe": '.$total_c.',
          "descuento": 0.00,
          "recargo": 0.00,
          "clasificacionDescuento": null
        }'.$coma;

        if ($multicaja == 1) { mysql_select_db("$basedatos"); }

        if ($cat == 'CIGARRILLOS') {
          $total_caja_cigarrillo += $total_c;
          $sSQL = "INSERT INTO `caja_cigarrillos` (`ID`, `detalle`, `monto`, `total_caja`, `fecha`) 
                   VALUES (NULL, '$titulo', '$precio', '$total_caja_cigarrillo', CURRENT_TIMESTAMP);";
          mysql_db_query("$basedatos", $sSQL);
        }

        $precio_real = $precio_original * $cantidad;
        $precio_costo_real = $precio_costo * $cantidad;
        $total += $precio_real;
        $total_costo += $precio_costo_real;
        $nnnn++;
      ?>

      <div class="item-card">
        <div class="row">
          <div class="col-lg-8 col-sm-12 col-md-8">
            <i class="fa fa-check-circle" style="color:#28a745;"></i> 
            <span style="font-weight:600;">
              <?php echo ($ID_articulo == 0) ? $detalle : $titulo; ?> - (x <?php echo $cantidad ?>)
            </span>
          </div>
          <div class="col-lg-4 col-sm-12 col-md-4" align="right">
            <span style="color:#28a745;font-size:18px;font-weight:700;">
              $ <?php echo number_format($precio_real, 2); ?>
            </span>
          </div>
        </div>
      </div>

      <?php
        $sSQL = "UPDATE `articulos` SET `stock` = '$stock_ahora' WHERE `articulos`.`ID` = '$ID_producto' LIMIT 1;";
        if ($multicaja == 1) {
          mysql_db_query("$basedatos_multicaja", $sSQL);
        } else {
          mysql_db_query("$basedatos", $sSQL);
        }

        $DDD = date("d"); 
        $MMM = date("m"); 
        $AAA = date("Y"); 
        $texto = "<B>ALARMA DE STOCK</B>: QUEDAN $stock_ahora UNIDADES DE <B>$titulo</B> / $barcode <hr> $DDD / $MMM / $AAA ";

        if ($limite != 0 && $limite == $stock_ahora) {
          $sSQL = "INSERT INTO `avisos` (`ID`, `aviso`) VALUES (NULL, '$texto');";
          mysql_db_query("$basedatos", $sSQL);
          mysql_db_query("$basedatos_mutlicaja", $sSQL);
        }
      }

      if ($promo_detectada) {
        $parte2 .= ',{
          "codigoArticulo": "'.$promo_barcode.'",
          "codigoBarras": "'.$promo_barcode.'",
          "descripcionArticulo": "'.$promo_desc.'",
          "cantidad": '.$promo_cant.',
          "importeUnitario": 0.00,
          "importe": 0.00,
          "descuento": '.number_format($promo_descuento, 2, ".", "").',
          "recargo": 0.00,
          "clasificacionDescuento": null
        }';
      ?>

      <div class="promo-card">
        <div class="row">
          <div class="col-lg-8 col-sm-12 col-md-8">
            <i class="fa fa-gift" style="font-size:24px;color:#28a745;"></i>
            <span style="font-weight:700;">
              ¡Se aplicó una promoción activa!
              <?php if (!empty($promo_tipo)) echo " ($promo_tipo)"; ?>
            </span>
          </div>
          <div class="col-lg-4 col-sm-12 col-md-4" align="right">
            <span style="color:#28a745;font-size:20px;font-weight:700;">
              -$ <?php echo number_format($monto_descuento_total, 2, ',', '.'); ?>
            </span>
          </div>
        </div>
      </div>

      <?php
        // Registro en tabla interna
        if ($promo_detectada) {
          $sql = "SELECT * FROM `movimientos` WHERE `ID_venta` = '$ID_venta'";
          $res = mysql_query($sql);
          while ($r = mysql_fetch_array($res)) {
            $id_articulo = $r["ID_articulo"];
            $cant = $r["cantidad"];
            $precio_unit = $r["precio"];

            $sql2 = "SELECT * FROM `articulos` WHERE ID = '$id_articulo' LIMIT 1";
            $res2 = mysql_query($sql2);
            $art = mysql_fetch_array($res2);
            $barcode = $art["barcode"];
            $titulo = mysql_real_escape_string($art["titulo"]);

            $sql3 = "SELECT * FROM promociones_scanntech WHERE vigencia_desde <= CURDATE() AND vigencia_hasta >= CURDATE()";
            $res3 = mysql_query($sql3);
            while ($promo = mysql_fetch_array($res3)) {
              $detalle = json_decode($promo["detalle"], true);
              if (!isset($detalle["condiciones"]["items"])) continue;

              foreach ($detalle["condiciones"]["items"] as $item) {
                foreach ($item["articulos"] as $a) {
                  if ($a["codigoBarras"] == $barcode && $cant >= $item["cantidad"]) {
                    $promo_nombre = mysql_real_escape_string($detalle["nombre"]);
                    $promo_codigo = isset($detalle["codigo"]) ? mysql_real_escape_string($detalle["codigo"]) : '';
                    $precio_final = $precio_unit;

                    if (isset($detalle["precio"])) {
                      $precio_final = $detalle["precio"] / $item["cantidad"];
                    } elseif (isset($detalle["descuento"])) {
                      $precio_final = $precio_unit - ($precio_unit * $detalle["descuento"] / 100);
                    } elseif (isset($detalle["paga"])) {
                      $precio_final = ($precio_unit * $detalle["paga"]) / $item["cantidad"];
                    }

                    $descuento = ($precio_unit - $precio_final) * $cant;
                    $monto_descuento_total += $descuento;
                    
                    $sqlInsert = "INSERT INTO promos_aplicadas 
                                  (id_venta, codigo_producto, descripcion_producto, precio_sin_promo, precio_con_promo, descuento_aplicado, nombre_promo, barcode_producto, codigo_promo)
                                  VALUES ('$ID_venta', '$id_articulo', '$titulo', '$precio_unit', '$precio_final', '$descuento', '$promo_nombre', '$barcode', '$promo_codigo')";
                    mysql_query($sqlInsert);
                    break 2;
                  }
                }
              }
            }
          }
        }
      }

      mysql_free_result($consulta);

      $masuno = $ID_venta + 1;
      
      $sSQL="UPDATE `ventas` SET `total` = '$total' WHERE `ventas`.`ID` = '$ID_venta';";
      mysql_db_query("$basedatos",$sSQL);

      $sSQL="UPDATE `ventas_costo` SET `total_costo` = '$total_costo' WHERE `ventas_costo`.`ID` = '$ID_venta';";
      mysql_db_query("$basedatos",$sSQL);
      
      $sSQL="UPDATE `ventas_costo` SET `total` = '$total' WHERE `ventas_costo`.`ID` = '$ID_venta';";
      mysql_db_query("$basedatos",$sSQL);

      $total_caja_new = $total_caja + $total;

      $sSQL="INSERT INTO `caja` (`ID`, `detalle`, `monto`, `total_caja`, `fecha`) 
             VALUES (NULL, 'Venta nº $ID_venta', '$total', '$total_caja_new', CURRENT_TIMESTAMP);";
      mysql_db_query("$basedatos",$sSQL);

      $sSQL="INSERT INTO `caja_costo` (`ID`, `detalle`, `monto`, `monto_costo`, `total_caja`, `fecha`) 
             VALUES (NULL, 'Venta nº $ID_venta', '$total',  '$total_costo', '$total_caja_new', CURRENT_TIMESTAMP);";
      mysql_db_query("$basedatos",$sSQL);

      $sSQL="UPDATE `ID_ventas` SET `ID` = '$masuno'";
      mysql_db_query("$basedatos",$sSQL);
      ?>

      <div class="total-badge">
        <i class="fa fa-dollar-sign"></i> Total: $ <b><?php echo number_format($total, 2, ',', '.'); ?></b>
      </div>

      <div class="operations-card">
        <h3><i class="fa fa-cogs"></i> OPERACIONES SOBRE LA VENTA</h3>

        <div class="form-group-modern">
          <form id="form1" name="form1" method="post" action="vuelto.php">
            <input name="total" type="hidden" value="<?php echo $total ?>" />
            <label><i class="fa fa-hand-holding-usd"></i> ¿CON CUÁNTO PAGO?</label>
            <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
              <span style="font-size:20px;font-weight:700;">$</span>
              <input name="cuanto_pago" type="text" id="cuanto_pago" class="form-control-modern" 
                     onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;" 
                     size="10" maxlength="10" style="max-width:150px;">
              <button type="submit" class="btn-modern btn-verde">
                <i class="fa fa-calculator"></i> CALCULAR VUELTO
              </button>
            </div>
          </form>
        </div>

        <hr style="border-top:2px solid #e0e0e0;">

        <div class="form-group-modern">
          <form method="post" action="hacer_descuento.php">
            <input type="hidden" value="<?php echo $ID_venta ?>" name="ID_venta">
            <input name="total" type="hidden" value="<?php echo $total ?>" />
            <label><i class="fa fa-percentage"></i> HACER UN <b>DESCUENTO</b> SOBRE EL TOTAL</label>
            <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
              <input name="descuento_portentaje" type="text" class="form-control-modern" 
                     onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;" 
                     size="3" maxlength="3" placeholder="%" style="max-width:100px;">
              <button type="submit" class="btn-modern btn-amarillo">
                <i class="fa fa-tag"></i> APLICAR DESCUENTO
              </button>
            </div>
          </form>
        </div>

        <hr style="border-top:2px solid #e0e0e0;">

        <div class="form-group-modern">
          <form method="post" action="hacer_aumento.php">
            <input type="hidden" value="<?php echo $ID_venta ?>" name="ID_venta">
            <input name="total" type="hidden" value="<?php echo $total ?>" />
            <label><i class="fa fa-arrow-up"></i> HACER UN <b>AUMENTO</b> SOBRE EL TOTAL</label>
            <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
              <input name="descuento_portentaje" type="text" class="form-control-modern" 
                     onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;" 
                     size="3" maxlength="3" placeholder="%" style="max-width:100px;">
              <button type="submit" class="btn-modern btn-rojo">
                <i class="fa fa-plus"></i> APLICAR AUMENTO
              </button>
            </div>
          </form>
        </div>
      </div>

      <?php
      $sql = "SELECT * FROM `ventas` ORDER BY ID desc LIMIT 1";
      $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);
      ?>

      <div class="movimiento-card">
        <div class="row">
          <div class="col-12">
            <div style="font-size:13px;color:#666;margin-bottom:15px;">
              <i class="fa fa-clock"></i>
              <?php echo "$hora:$min"; ?> | 
              <?php
              $dhoy = date(d);
              $mhoy = date(m);
              if ($dia == $dhoy and $mes == $mhoy) { echo "hoy"; } else { echo "$dia/$mes"; }
              ?>
            </div>

            <div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:15px;">
              <button type="button" class="btn-modern" style="background:white;color:#000;font-size:18px;font-weight:700;">
                $ <?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 ?>">
                <i class="fa fa-eye"></i> Ver Detalle
              </button>

              <button type="button" class="btn-modern btn-azul openModal" data-url="imprimir_ticket_barra_especial.php?ID=<?php echo $ID_venta ?>">
                <i class="fa fa-print"></i> 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 ?>">
                <i class="fa fa-receipt"></i> 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">
                  <i class="fa fa-file-pdf"></i> PDF
                </button>
              </a>

              <?php if ($forma_pago != 'anulado') { ?>
                <button type="button" class="btn-modern btn-rojo openModal" data-url="anular_venta.php?ID=<?php echo $ID_venta ?>">
                  <i class="fa fa-times-circle"></i> Anular Venta
                </button>
              <?php } ?>
            </div>

            <div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
              <?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 badge-aumento">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 } else { ?>
                <form action="pago_con_tarjeta.php?ID=<?php echo $ID_venta ?>" method="POST" style="display:inline-flex;gap:6px;align-items:center;">
                  <input name="ID_venta" type="hidden" value="<?php echo $ID_venta ?>" />
                  <select name="medio_p" class="form-control-modern" style="font-size:13px;padding:8px;max-width:200px;">
                    <option selected="selected">Método de pago</option>
                    <option value="M.P.DEBITO">DÉBITO</option>
                    <option value="M.P.CREDITO">CRÉDITO</option>
                    <option value="M.P.TRANSFERENCIA">TRANSFERENCIA</option>
                    <option value="M.P.QR">QR</option>
                    <option value="M.P.MERCADO.PAGO">MERCADO PAGO</option>
                    <option value="M.P.MODO">MODO</option>
                  </select>
                  <button type="submit" class="btn-modern btn-morado">
                    <i class="fa fa-credit-card"></i> Pagar Total
                  </button>
                </form>
              <?php } ?>

              <?php if ($forma_pago == 'dividido') { ?>
                <span class="badge-pill-modern badge-dividido">PAGO DIVIDIDO</span>
              <?php } else { ?>
                <form action="pago_con_tarjeta_parte.php?ID=<?php echo $ID_venta ?>" method="POST" style="display:inline-flex;gap:6px;align-items:center;">
                  <input name="ID_venta" type="hidden" value="<?php echo $ID_venta ?>" />
                  <input type="text" name="cuanto" placeholder="Monto" class="form-control-modern" style="max-width:100px;padding:8px;font-size:13px;">
                  <select name="medio_p" class="form-control-modern" style="font-size:13px;padding:8px;max-width:200px;">
                    <option selected="selected">Método de pago</option>
                    <option value="M.P.DEBITO">DÉBITO</option>
                    <option value="M.P.CREDITO">CRÉDITO</option>
                    <option value="M.P.TRANSFERENCIA">TRANSFERENCIA</option>
                    <option value="M.P.QR">QR</option>
                    <option value="M.P.MERCADO.PAGO">MERCADO PAGO</option>
                    <option value="M.P.MODO">MODO</option>
                  </select>
                  <button type="submit" class="btn-modern btn-morado">
                    <i class="fa fa-wallet"></i> Pagar Parcial
                  </button>
                </form>
              <?php } ?>

              <?php if ($forma_pago == 'fiado') { ?>
                <span class="badge-pill-modern btn-amarillo">VENTA FIADO</span>
              <?php } else { ?>
                <form action="pago_con_fiado.php" method="POST" style="display:inline-flex;gap:6px;align-items:center;">
                  <input name="ID_venta" type="hidden" value="<?php echo $ID_venta ?>" />
                  <select name="ID_cliente" class="form-control-modern" style="font-size:13px;padding:8px;max-width:200px;">
                    <option selected="selected">Seleccione Cliente</option>
                    <?php
                    $sql4 = "SELECT * FROM `clientes` ORDER BY ID";
                    $consulta4 = mysql_query ($sql4);
                    while ($row4 = mysql_fetch_array($consulta4)) {
                      $ID_cliente = $row4["ID"];
                      $nombre = $row4["nombre"];
                    ?>
                      <option value="<?php echo $ID_cliente ?>"><?php echo $nombre ?></option>
                    <?php
                    }
                    mysql_free_result($consulta4);
                    ?>
                  </select>
                  <button type="submit" class="btn-modern btn-amarillo">
                    <i class="fa fa-user-clock"></i> Pagar con Fiado
                  </button>
                </form>
              <?php } ?>
            </div>
          </div>
        </div>
      </div>

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

      <div class="section-header" style="background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);">
        <h3><i class="fa fa-ticket-alt"></i> TICKET DE COMPRA</h3>
        <p style="margin:0;font-size:14px;margin-top:10px;">
          Presione <b>F2</b> para iniciar una nueva venta o <b>F3</b> y <b>ENTER</b> para imprimir el ticket.
        </p>
      </div>

      <div class="row">
        <div class="col-md-6">
          <div class="iframe-container">
            <iframe id="printf" src="imprimir_ticket_barra_especial.php?ID=<?php echo $ID_venta ?>" 
                    style="width:100%;height:560px;border:none;"></iframe>
          </div>
        </div>
        <div class="col-md-6">
          <div class="iframe-container">
            <iframe src="imprimir_ticket_barra_especial_1.php?ID=<?php echo $ID_venta ?>" 
                    style="width:100%;height:560px;border:none;"></iframe>
          </div>
        </div>
      </div>

      <div class="alert-modern alert-info" style="margin-top:30px;">
        <h4><i class="fa fa-check-circle"></i> VENTA FINALIZADA</h4>
      </div>

      <div style="margin-top:20px;margin-bottom:30px;">
        <h4 style="color:#667eea;"><i class="fa fa-file-invoice"></i> IMPRIMIR FACTURA FISCAL (OPCIONAL)</h4>
        <a href="factura_fiscal.php?p=<?php echo $total ?>" style="text-decoration:none;">
          <button class="btn-modern btn-morado" style="font-size:16px;padding:15px 30px;">
            <i class="fa fa-print"></i> IMPRIMIR FACTURA FISCAL
          </button>
        </a>
      </div>

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

<div id="termino_fin" class="termino_fin" style="display:none;"></div>

<!-- Modal -->
<div id="myModal" class="modal">
  <div class="modal-content">
    <div style="background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);padding:20px;border-radius:12px 12px 0 0;">
      <span class="close">&times;</span>
      <h3 style="color:white;margin:0;"><i class="fa fa-window-maximize"></i> Vista Previa</h3>
    </div>
    <div id="spinner" class="spinner"></div>
    <iframe id="myIframe" src="" style="width: 100%; height: 500px; border:none;"></iframe>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>

<script>
$(document).ready(function () {
  const spinner = $(".spinner-overlay");
  const terminoFin = $("#termino_fin");

  spinner.hide();

  const observer = new MutationObserver(function (mutationsList, observer) {
    if (terminoFin.is(":visible")) {
      spinner.hide();
      observer.disconnect();
    }
  });

  observer.observe(terminoFin[0], { attributes: true, childList: true, subtree: true });
});

// Modal functionality
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";
});

// Keyboard shortcuts
function PulsarTecla(event) {
  tecla = event.keyCode;
  if(tecla==114) {
    document.getElementById("printf").contentWindow.print();
  }
  if(tecla==113) {
    location.href ='nueva_venta.php';
  }
}
window.onkeydown=PulsarTecla;
</script>

<?php
// [TODO EL CÓDIGO PHP DE SCANNTECH Y ACTUALIZACIÓN DE CONFIGURACIÓN SE MANTIENE IGUAL]
$fecha_actual = date('Y-m-d\TH:i:s.000O');
$parte1 = '{
  "fecha": "'.$fecha_actual.'",
  "numero": "'.$ID_venta.'",
  "descuentoTotal": '.number_format($monto_descuento_total, 2, ".", "").',
  "recargoTotal": 0.00,
  "codigoMoneda": "032",
  "cotizacion": 1.00,
  "total": '.$total.',
  "cancelacion": false,
  "documentoCliente": "62167733305",
  "codigoCanalVenta": 1,
  "descripcionCanalVenta": "VENTA EN EL LOCAL",
  "detalles": [';

$parte3 = '],
  "pagos": [{
    "codigoTipoPago": 9,
    "codigoMoneda": "032",
    "importe": '.$total.',
    "cotizacion": 1.00,
    "documentoCliente": null,
    "bin": null,
    "ultimosDigitosTarjeta": null,
    "numeroAutorizacion": null,
    "codigoTarjeta": null
  }]
}';

$data = $parte1 . $parte2 . $parte3;

if ($scan == 1) {
  echo "<pre style='background:#eee;padding:10px;border:1px solid #ccc;'><code>".htmlspecialchars($data)."</code></pre>";
}

$localidad22 = base64_encode("$localidad/$provincia/$rutadom");

if ($scan == 1) {
  $options = array(
    CURLOPT_URL => $url,
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => $data,
    CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
    CURLOPT_USERPWD => "$username:$password",
  );

  $ch = curl_init();
  curl_setopt_array($ch, $options);
  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

  if ($response === false) {
    echo "Error en la solicitud: " . curl_error($ch);
  } else {
    $data_scann = json_decode($response, true);
    if ($httpCode == 200 && !empty($data_scann['promotions'])) {
      foreach ($data_scann['promotions'] as $promo) {
        $promo_desc = htmlspecialchars($promo['description']);
        $promo_descuento = number_format($promo['discount'], 2);
        echo "<div class='promo-card'>
                <div class='row'>
                  <div class='col-lg-8 col-sm-12 col-md-8'>
                    <i class='fa fa-gift'></i> <span>Promo aplicada: <b>{$promo_desc}</b></span>
                  </div>
                  <div class='col-lg-4 col-sm-12 col-md-4' align='right'>
                    <span style='color:#28a745;'><b>Descuento: $ {$promo_descuento}</b></span>
                  </div>
                </div>
              </div>";

        $promo_code = mysql_real_escape_string($promo['code']);
        $promo_desc_sql = mysql_real_escape_string($promo['description']);
        $promo_amount = $promo['discount'];
        $sSQL="INSERT INTO promos_aplicadas (id_venta, nombre_promo, codigo_promo, descuento_aplicado)
               VALUES ('$ID_venta', '$promo_desc_sql', '$promo_code', '$promo_amount');";
        mysql_query($sSQL);
      }
    }
  }
  curl_close($ch);
}

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

$masuno = $opcion29 + 1;
$sSQL="UPDATE `configuracion` SET `opcion29` = '$masuno' LIMIT 1;";
mysql_db_query("$basedatos",$sSQL); 

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

$nuevo_precio_opcion32 = $opcion32 + $total;
$sSQL="UPDATE `configuracion` SET `opcion32` = '$nuevo_precio_opcion32' LIMIT 1;";
mysql_db_query("$basedatos",$sSQL); 
?>

</body>
</html>