<?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>Panel</title>
  <script language=javascript>
function ventanaSecundaria56 (URL){
   window.open(URL,"ventana1","width=300,height=400,scrollbars=NO")
}
  </script>

<style>
.caca {
    max-width: 200px;
	max-height:200px;
}</style>



 <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <style>
    .spinner-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(255, 255, 255, 0.7);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 9999;
    }

    .spinner {
      border: 4px solid rgba(0, 0, 0, 0.1);
      border-top: 4px solid #3498db;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      animation: spin 1s linear infinite;
    }

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

    .termino_fin {
      width: 200px;
      height: 200px;
      background-color: #3498db;
    }
  </style>
  <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 });
    });
  </script>




<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">

</head>

<body>
 <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';?>
<label>

</label>
</div>

<div class="col-lg-9 col-md-9 col-sm-12">



<?

$D_a = date(d);
$M_a = date(m);
$A_a = date(Y);

include 'concha.php';

mysql_connect("$host","$usuario","$contra");

mysql_select_db ("$basedatos");


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




// =======================================================
// ABRIR VENTA SI NO ESTA ABIERTA
// (si no existe cabecera en ventas, la crea)
// =======================================================

$venta_existe = 0;

$sqlv = "SELECT ID FROM ventas WHERE ID = '$ID_venta' LIMIT 1";
$rv = mysql_query($sqlv);

if ($rv && mysql_num_rows($rv) > 0) {
    $venta_existe = 1;
}

if ($rv) { mysql_free_result($rv); }

if ($venta_existe == 0) {

    $A = date("Y");
    $M = date("m");
    $D = date("d");
    $HORA = date("H");
    $MIN = date("i");

    $fecha = "$A$M$D$HORA$MIN";

    mysql_db_query("$basedatos",
        "INSERT INTO `ventas`
        (`ID`, `fecha`, `hora`, `total`, `usuario`, `forma_pago`)
        VALUES
        ('$ID_venta', '$fecha', '0', '', '$user_con', '')"
    );

    mysql_db_query("$basedatos",
        "INSERT INTO `ventas_costo`
        (`ID`, `fecha`, `hora`, `total`, `total_costo`, `usuario`, `forma_pago`)
        VALUES
        ('$ID_venta', '$fecha', '0', '', '', '$user_con', '')"
    );
}








$barcode = $_POST['barcode'];

$barcode = str_replace(' ', '',$barcode);

$barcode = trim($barcode);

$cantidad = $_POST['cantidad'];
$varios = $_POST['varios'];

$primeroscuatro = substr($barcode,0,4);

if ($primeroscuatro == '2000') {


$precioaaa = substr($barcode,6,6);
$ultimo = substr($barcode,-1);

$armo = "$precioaaa.$ultimo";



mysql_db_query("$basedatos","


INSERT INTO `movimientos` (`ID`, `ID_venta`, `ID_articulo`, `precio`, `cantidad`, `detalle`) VALUES (NULL, '$ID_venta', '0', '$armo', '1', 'ALMACEN');

");

 };


$precio_varios = $_POST['precio_varios'];



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


$sql = "SELECT * FROM `articulos` WHERE `barcode` = '$barcode' LIMIT 1";

$consulta = mysql_query ($sql);

while ($row = mysql_fetch_array($consulta))

{

$ID_producto = $row["ID"];
$titulo = $row["titulo"];
$foto = $row["foto"];
$precio = $row["precio"];
$stock = $row["stock"];
$barcode = $row["barcode"];
$cat = $row["cat"];
}

mysql_free_result($consulta);


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

 //INSERTO EL PRODUCTO EN LAS ESTADISTICAS
$fechacompuesta = "$A_a$M_a$D_a";
$estadisticas_esta_cargado = 0;


$sql = "SELECT cant FROM `estadisticas` WHERE `barcode` = '$barcode' AND `d` = '$D_a' AND `m` = $M_a AND `a` = $A_a  LIMIT 1";

$consulta = mysql_query ($sql);

while ($row = mysql_fetch_array($consulta))

{
$estadisticas_esta_cargado = 1;
$estadisticas_cant = $row["cant"];
}

mysql_free_result($consulta);


$estadisticas_cant = $estadisticas_cant + $cantidad;

if ($estadisticas_esta_cargado == 1) {

   // esta

   $sSQL="UPDATE `estadisticas` SET `cant` = '$estadisticas_cant' WHERE `barcode` = '$barcode' AND `d` = '$D_a' AND `m` = $M_a AND `a` = $A_a LIMIT 1";

   mysql_db_query("$basedatos",$sSQL);


 } else {

//no esta

$sSQL="INSERT INTO `estadisticas` (`ID`, `fecha`, `barcode`, `cant`, `d`, `m`, `a`) VALUES (NULL, '$fechacompuesta', '$barcode', '1', '$D_a', '$M_a', '$A_a');";

mysql_db_query("$basedatos",$sSQL);


} //cierro if



$sSQL="INSERT INTO `estadisticas` (`ID`, `fecha`, `barcode`, `cant`, `d`, `m`, `a`, `web`) VALUES (NULL, '$fechacompuesta', '$barcode', '1', '$D_a', '$M_a', '$A_a', '$dom');";

mysql_db_query("sistemas_base",$sSQL);







////inserto en POPULARES


$fechacompuesta = "$A_a$M_a$D_a";
$populares_esta_cargado = 0;

mysql_select_db ("$basedatos");
$sql = "SELECT cant FROM `populares` WHERE `barcode` = '$barcode'  LIMIT 1";

$consulta = mysql_query ($sql);

while ($row = mysql_fetch_array($consulta))

{
$populares_esta_cargado = 1;
$cant_popu = $row['cant'];

}

mysql_free_result($consulta);


$cant_popu = $cant_popu + 1;

if ($populares_esta_cargado == 1) {

   // esta

   $sSQL="UPDATE `populares` SET `cant` = '$cant_popu' WHERE `populares`.`barcode` = '$barcode' LIMIT 1";

   mysql_db_query("$basedatos",$sSQL);


 } else {

//no esta

// Lista de colores en formato hexadecimal
$colores = [
    "#E0FFFF", "#98FB98", "#FFDAB9", "#FFE4B5", "#FFC0CB",
    "#FFB6C1", "#F0E68C", "#FFFACD", "#FFF0F5", "#E6E6FA",
    "#FAFAD2", "#FFFFE0", "#FFA07A", "#F0FFF0", "#FFF5EE",
    "#FFE4E1", "#FFDEAD", "#FFEFDB", "#FFEBCD", "#F5F5DC",
    "#FFF8DC", "#FFF8E7", "#FFF9E6", "#FFFAF0", "#FFFAF4",
    "#FFFAFA", "#FDF5E6", "#F5DEB3", "#F5F5F5", "#F5FFFA",
    "#F8F8FF", "#FDF5E6", "#FFFAF0", "#FFFFF0", "#F0F8FF",
    "#FAEBD7", "#FFFAFA", "#FFF5EE", "#FFF8DC", "#F5F5DC",
    "#F0FFF0", "#FFDEAD", "#F0E68C", "#E0FFFF", "#FFDAB9",
    "#FFE4B5", "#FFC0CB", "#FFB6C1", "#E6E6FA", "#FAFAD2"
];

// Seleccionar un índice al azar
$indice_aleatorio = rand(0, count($colores) - 1);

// Asignar el color seleccionado a la variable $colorfondo
$colorfondo = $colores[$indice_aleatorio];


$sSQL="INSERT INTO `populares` (`barcode`, `nombre`, `cant`, `color`) VALUES ('$barcode', '$titulo', '0', '$colorfondo');";

mysql_db_query("$basedatos",$sSQL);


} //cierro if


/*
$sSQL="INSERT INTO `estadisticas` (`ID`, `fecha`, `barcode`, `cant`, `d`, `m`, `a`, `web`) VALUES (NULL, '$fechacompuesta', '$barcode', '1', '$D_a', '$M_a', '$A_a', '$dom');";

mysql_db_query("sistemas_base",$sSQL);

*/





?>



<? if ($cat == 'PROMO') { echo "<H2>PROMO</H2>";



echo "<BR>SE SUMARAN LOS SIGUIENTE PRODUCTOS CORESPONDIENTES A LA PROMOCIÓN.<HR>";

$sql2 = "SELECT * FROM `promociones` WHERE `ID_promo` = '$barcode'";
$consulta2 = mysql_query ($sql2);
while ($row2 = mysql_fetch_array($consulta2))
{
$ID_articulo2 = $row2["ID_articulo"];

$sSQL="INSERT INTO `movimientos` (`ID`, `ID_venta`, `ID_articulo`, `precio`, `cantidad`, `detalle`) VALUES (NULL, '$ID_venta', '$ID_articulo2', '0', '1', 'PROMO');";

mysql_db_query("$basedatos",$sSQL);




?>

<?

}
mysql_free_result($consulta2);



};




if ($cat == 'INDUMENTARIA') { echo "<H2>INDUMENTARIA</H2>";



echo "<BR>ESTE PRODUCTO TIENE SUB DIVISIONES DE TALLE Y COLOR, SELECCIONE CUAL ACABA DE VENDER.<HR>";
?>
<?
  include 'concha.php';

  mysql_connect("$host","$usuario","$contra");

  mysql_select_db ("$basedatos_mutlicaja");

  $sql = "SELECT * FROM `articulos` WHERE `barcode` LIKE '$barcode%' AND `cat` = 'SUB'";


  $consulta = mysql_query ($sql);

  while ($row = mysql_fetch_array($consulta))

  {

  $ID_producto = $row["ID"];
  $titulo = $row["titulo"];
  $foto = $row["foto"];
  $precio = $row["precio"];
  $stock = $row["stock"];
  $barcode = $row["barcode"];
  $cat = $row["cat"];
?>



  <a href="nueva_venta.php?barcode=<? echo "$barcode"; ?>"><? echo "$titulo"; ?></a><HR>


<?

  }

  mysql_free_result($consulta);
  mysql_select_db ("$basedatos");
?>

<br><HR>


<?


exit;
};

?>




<div class="row">
<div class="col-lg-6 col-sm-12 col-md-6">
<button type="button" class="btn btn-info">VENTA Nº <?php echo $ID_venta ?></button> </div>
<div class="col-lg-6 col-sm-12 col-md-6" align="right">
<a href="finalizar_venta.php"><button type="button" class="btn btn-danger">Finalizar Venta (F4)</button></a>
</div>

</div>
<hr />

<?

if($barcode == '' and $varios == '') {} else {


if ($varios == '') {

mysql_db_query("$basedatos","


INSERT INTO `movimientos` (`ID`, `ID_venta`, `ID_articulo`, `precio`, `cantidad`, `detalle`) VALUES (NULL, '$ID_venta', '$ID_producto', '$precio', '$cantidad', '$detalle');

"); } else { mysql_db_query("$basedatos","


INSERT INTO `movimientos` (`ID`, `ID_venta`, `ID_articulo`, `precio`, `cantidad`, `detalle`) VALUES (NULL, '$ID_venta', '0', '$precio_varios', '$cantidad', '$varios');

"); }; }; ?>



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

mysql_select_db ("$basedatos");


$sql = "SELECT * FROM `movimientos` WHERE `ID_venta` = '$ID_venta'";


$consulta = mysql_query ($sql);

while ($row = mysql_fetch_array($consulta))

{
$ID_mov = $row["ID"];
$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);

while ($row22 = mysql_fetch_array($consulta22))

{
$ID_producto = $row22["ID"];
$titulo = $row22["titulo"];
$foto = $row22["foto"];
$stock = $row22["stock"];
$barcode = $row22["barcode"];

}

mysql_free_result($consulta22);

$sqlu = "SELECT MAX(ID) as ult_id FROM movimientos WHERE ID_venta = '$ID_venta'";
$ru = mysql_query($sqlu);
$ult_id = 0;
if ($ru && $rowu = mysql_fetch_array($ru)) {
    $ult_id = $rowu['ult_id'];
}
if ($ru) { mysql_free_result($ru); }


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


$precio = $precio * $cantidad;
$total = $total + $precio;

if ($ID_mov == $ult_id) {
    // ESTE ES EL ULTIMO PRODUCTO
    $backn = "#fff3b0"; // amarillo suave
} else {
    // resto normal alternado
    $nnnn = $nnnn + 1;
    if ($nnnn % 2 == 0) {
        $backn = "#fff";
    } else {
        $backn = "#e6e6e6ab";  
    }
}


?><div class="row" style="background-color:<? echo $backn ?>; border-bottom: solid;  border-width: 1px; padding: 9px;">
<div class="col-lg-6 col-sm-12 col-md-6">
<i class="fa fa-check"></i> <span ><?php if($ID_articulo == 0) { echo $detalle; } else { echo $titulo; }; ?> - (x <?php echo $cantidad ?>) <br />
</span></div>
<div class="col-lg-6 col-sm-12 col-md-6" align="right">
<span style="color:#006600;"><b>$ <?php echo $precio ?> </b></span> /  <a href="borrar_producto_de_venta.php?ID=<?php echo $ID_mov ?>">(X)</a> </div>
 </div>
<?



}

mysql_free_result($consulta);

?> <hr><div align="right"> <h2>Total:</h2> <h1><span style="color:#006600">$ <?php echo $total ?></span></h1></div> <?

?>



<hr />


<div class="row">

<div class="col-lg-6 col-sm-12 col-md-6" style="margin-top: 150px; margin-bottom:25px;">

<form action="agregar_productos.php" method="post">

CANTIDAD x <input name="cantidad" type="text" id="cantidad" onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;" value="1" size="2" maxlength="9" >
<br />

Lea el código de barras del producto con la lectora:<br />
<input autofocus name="barcode" type="text" class="form-control" style="max-width: 299px; border-style: solid;
border-width: 2px;
border-color: red;"   />
<hr />
<input name="varios" type="text" placeholder="Productos Varios..." />  $ <input name="precio_varios" type="text" id="cantidad" onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;" size="4" maxlength="9" placeholder="Precio">
<br /><br />



<input class="btn btn-success" type="submit" name="button" id="button" value="PROCESAR (ENTER)" />
<a href="finalizar_venta.php" class="btn btn-danger">FINALIZAR VENTA (F4)</a>

<hr>

</form>


<div style="">
<form id="form14" name="form14" method="post" action="form_buscar.php">



<div class="row" style="padding: 10px;
margin-bottom: 25px;
border-bottom: solid;
border-width: 1px; background-color: #ffb300;">
<div class="col-8">
<input type="hidden"  name="que" value="2">
<input  name="busqueda" type="text"  style="border: solid;
    border-top-color: currentcolor;
    border-right-color: currentcolor;
    border-bottom-color: currentcolor;
    border-left-color: currentcolor;
border-color: red;"  placeholder="BUSCAR ARTICULO" class="form-control" />
</div>


<div class="col-4">
<input name="button" type="submit"  id="button" value="Buscar " style="border: solid;
    border-top-color: currentcolor;
    border-right-color: currentcolor;
    border-bottom-color: currentcolor;
    border-left-color: currentcolor;
border-color: red;"  class="form-control"/>
</div>



</div>
</form>

</div>













</div>


<div class="col-lg-6 col-sm-12 col-md-6">

<div>ÚLTIMO PRODUCTO PASADO</div>

<div style="background-color: #ffeaac;
border: solid;
padding: 15px;
margin-bottom: 45px;">






<?

mysql_connect("$host","$usuario","$contra");

mysql_select_db ("$basedatos");


$sql = "SELECT * FROM `movimientos` WHERE `ID_venta` = '$ID_venta' ORDER BY ID desc LIMIT 1";


$consulta = mysql_query ($sql);

while ($row = mysql_fetch_array($consulta))

{

$ID_articulo = $row["ID_articulo"];
$precio = $row["precio"];
$cantidad = $row["cantidad"];
$detalle = $row["detalle"];

mysql_select_db ("$basedatos_multicaja");
$sql22 = "SELECT * FROM `articulos` WHERE `ID` = '$ID_articulo' LIMIT 1";

$consulta22 = mysql_query ($sql22);

while ($row22 = mysql_fetch_array($consulta22))

{
$ID_producto = $row22["ID"];
$titulo = $row22["titulo"];
$foto = $row22["foto"];
$stock = $row22["stock"];
$barcode = $row22["barcode"];

$foto = $row22["foto"];

$fotopri = substr($foto,0,14);

if ($fotopri == 'fotos_usuarios') { } else {$foto = "https://img.sistemastock.com/img/$foto"; };

if ($fotopri == '') {$foto = "https://sistemastock.com/PRODUCTOSIN.jpg";}


}

mysql_free_result($consulta22);
mysql_select_db ("$basedatos");

?>

  <img  src="https://sistemastock.com/CARGANDOIMG.jpg" data-src="<? echo $foto ?>" class="img-fluid lazy" style="width:90px;"><br>

<span style="font-size: 31px;"><?php if($ID_articulo == 0) { echo $detalle; } else { echo $titulo; }; ?> - (x <?php echo $cantidad ?>)</span><br>
<span style="color: #FF3300; font-size: 45px;">$ <b><?php echo $precio ?></b></span>

<br>
<span style="color: #FF3300; font-size: 14px;">PRECIO UNITARIO</span>
  
  
<?


}

mysql_free_result($consulta);
?>
</div>




<p>TICKET DE COMPRA</p>
<iframe src="imprimir_ticket_barra.php" height="560px;"></iframe>



</div>

</div>


</div>
</div>

</div>


<div id="termino_fin" class="termino_fin"></div>



  <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 PulsarTecla(event)
    {
        tecla = event.keyCode;
     

        
        
        
            if(tecla==115)
        {
            location.href ='finalizar_venta.php';
        }
        
        
         if (tecla == 119) {
        // Hacer focus en el campo de búsqueda
        document.getElementById('busquedaInput').focus();
    }
      
    }
     
    window.onkeydown=PulsarTecla;
    </script>

  <script>

        // Set the options to make LazyLoad self-initialize
        window.lazyLoadOptions = {
            elements_selector: ".lazy",
            data_sizes: "100"
            // ... more custom settings?
        };
        // Listen to the initialization event and get the instance of LazyLoad
        window.addEventListener('LazyLoad::Initialized', function (event) {
            window.lazyLoadInstance = event.detail.instance;
        }, false);
    </script>
    <script async src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@12.4.0/dist/lazyload.min.js"></script>

</body>
</html>
