<?php
set_time_limit(600);
include "conn.php";
include "conn2.php";

// si ya confirmaron pulsando el boton
// ****************************************************************************************************
if(isset($_POST["confirma"])){

$tiempo_inicial = microtime(true);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Make MySQLi throw exceptions.

        try {
            // Try Connect to the DB with new MySqli object - Params {hostname, userid, password, dbname}
            $mysqli = new mysqli($host, $user, $pass, $base);

            if(isset($_GET["conectar"])){

              # no se conecta al servidor de Bruno Corza

            } else {

              $mysqli2 = new mysqli($host2, $user2, $pass2, $base2);

            }

            // Select all records from the db. Keep inside try block incase there an issue with sql query
            $query2 = "SELECT ALMNUM AS Suc,CATDESCR AS Sucursal,CONCAT(ALMNUM,' ',CATTEL2) AS Tienda,CATCOMENTARIO AS TipScursal,SUBSTRING_INDEX(CATCONTACTO,' ',1) AS Zona,LEFT(ICOD,8) AS Raiz,
            LEFT(ICOD,11) AS RC,ICOD AS Codigo,IUPC AS Talla2022,IVARIOS1 AS FINVVARIOS1 ,
            almactivo AS Activo,IDESCR AS Descripcion

            , n.FAMDESCR AS Categoria_uso, l.famdescr AS Linea,

            p.FAMDESCR AS H_o_M,b.FAMDESCR AS Departamento,c.FAMDESCR AS SubLinea, e.FAMDESCR AS Marca
            ,f.FAMDESCR AS Diseno_Tela,g.FAMDESCR AS Composicion,
            i.FAMDESCR AS Silueta,j.FAMDESCR AS TCompra,k.FAMDESCR AS Anio,l.FAMDESCR AS Proveedor,m.FAMDESCR AS Estatus,o.FAMDESCR AS Semana,
            CASE
            WHEN YEAR(IULTCPR)<=2018 THEN '2018 Y ANT'
            WHEN YEAR(IULTCPR)=2019 AND MONTH(IULTCPR)<=6 THEN '2019-1'
            WHEN YEAR(IULTCPR)=2019 AND MONTH(IULTCPR)>6 THEN '2019-2'
            WHEN YEAR(IULTCPR)=2020 AND MONTH(IULTCPR)<=6 THEN '2020-1'
            WHEN YEAR(IULTCPR)=2020 AND MONTH(IULTCPR)>6 THEN '2020-2'
            WHEN YEAR(IULTCPR)=2021 AND MONTH(IULTCPR)<=6 THEN '2021-1'
            WHEN YEAR(IULTCPR)=2021 AND MONTH(IULTCPR)>6 THEN '2021-2'
            WHEN YEAR(IULTCPR)=2022 AND MONTH(IULTCPR)<=6 THEN '2022-1'
            WHEN YEAR(IULTCPR)=2022 AND MONTH(IULTCPR)>6 THEN '2022-2'
            ELSE '' END AS Antiguedad,
            IULTCPR AS Ultima_Compra,IACUMENTRADAS AS Total_Compras,ICOLOREXT AS Color,
            ILISTA1 AS PrecioLinea,ILISTA5 AS Costo,
            ALMALTA AS Alta_Suc,ALMTRANSITO AS Transito,ROUND(ALMCANT,0) AS Existencia, ROUND(ALMCANT,0)+ALMTRANSITO AS Total,
            SUBSTRING(ICOD,9,2) AS Color2
            FROM falm
            LEFT JOIN finv ON falm.ISEQ=finv.ISEQ LEFT JOIN falmcat ON falm.ALMNUM=falmcat.CATALM
            LEFT JOIN ffam a ON IFAM1=a.FAMTNUM LEFT JOIN ffam b ON IFAM2=b.FAMTNUM
            LEFT JOIN ffam c ON IFAM3=c.FAMTNUM LEFT JOIN ffam d ON IFAM4=d.FAMTNUM
            LEFT JOIN ffam e ON IFAM5=e.FAMTNUM LEFT JOIN ffam f ON IFAM6=f.FAMTNUM
            LEFT JOIN ffam g ON IFAM7=g.FAMTNUM LEFT JOIN ffam h ON IFAM8=h.FAMTNUM
            LEFT JOIN ffam i ON IFAM9=i.FAMTNUM LEFT JOIN ffam j ON IFAMA=j.FAMTNUM
            LEFT JOIN ffam k ON IFAMB=k.FAMTNUM LEFT JOIN ffam l ON IFAMl=l.FAMTNUM
            LEFT JOIN ffam m ON IFAMD=m.FAMTNUM LEFT JOIN ffam n ON IFAMn=n.FAMTNUM
            LEFT JOIN ffam o ON IFAMF=o.FAMTNUM LEFT JOIN ffam p ON IFAMh=p.FAMTNUM
            LEFT JOIN finv2 ON FINV.ISEQ=FINV2.I2KEY
            WHERE ICOD NOT LIKE ('Y%') AND ITIPO NOT IN (0) AND ALMNUM>=00 AND ALMNUM<=62 AND ALMNUM<>'' AND CATALM<>''
            AND ICOD NOT IN ('00TALLAS01','00TALLAS29','SSASHAB','*011DO','*012CI','*014ET','*111AM','*112MC','*113CM','*211SM','*212AL','*213CE','A@N','*214OT')
            AND (ALMTRANSITO<>0 OR ALMCANT<>0) and (ALMCANT is not null)
            #and LEFT(ICOD,11)='04105412980'
            ORDER BY ALMNUM, ICOD
            LIMIT 999000
            ";


if(isset($_GET["conectar"])){

  # no hacer conexión al servidor de Bruno Corza

} else {

$mysqli->query("DROP TABLE IF EXISTS inv");
$mysqli->query("create table inv like inv_pol");
            
            if ($result = $mysqli2->query($query2)) {

                // fetch associative array
                while ($row = $result->fetch_assoc()) {
                    
                    $color=$row["Color"];
                    if(substr($row["Color"],0,3)=='CAF'){$color='CAFE';}
                    $query = "insert into inv(suc,codigo,talla,total,tienda,genero,rc,linea,linea2,sucursal,descripcion
                    ,existencia,transito,departamento,anio,alta_suc,costo,precio_linea,ultima_compra,total_compras,color) values(";
                    $query = $query . "
                    '" . $row["Suc"]."'
                    ,'" . $row["Codigo"]."'
                    ,'" . $row["Talla2022"]."'
                    ,'" . $row["Total"]."'
                    ,'" . $row["Tienda"]."'
                    ,'". $row["H_o_M"]."'
                    ,'". $row["RC"]."'
                    ,'". $row["Categoria_uso"]."'
                    ,'". $row["Linea"]."'
                    ,'". $row["Sucursal"]."'
                    ,'". $row["Descripcion"]."'
                    ,'". $row["Existencia"]."'
                    ,'". $row["Transito"]."'
                    ,'". $row["Departamento"]."'
                    ,'". $row["Anio"]."'
                    ,'". $row["Alta_Suc"]."'
                    ,'". $row["Costo"]."'
                    ,'". $row["PrecioLinea"]."'
                    ,'". $row["Ultima_Compra"]."'
                    ,'". $row["Total_Compras"]."'            
                    ,'". $color."')";
                    
                    $mysqli->query("$query");
                    //echo $query."<hr>";
                    //die($query);
                    
                }


                // free the memory associated with this result set
                $result->free();
            }

            // actualiza las tallas de los recientas
            $query_talla="SELECT LEFT(a.icod,11) AS rc,a.ium as unidad,a.iupc AS talla,a.ialta AS fecha_alta 
            FROM finv a 
            WHERE a.itipo=1 AND a.ialta>=DATE_ADD(CURDATE(),INTERVAL -15 DAY) AND a.iupc<>'' AND LENGTH(icod)>=11
            GROUP BY 1,2,3
            LIMIT 999000";

            if ($result_talla = $mysqli2->query($query_talla)) {

              // los guarda en la tabla
              while ($row_talla = $result_talla->fetch_assoc()) {
                $query = "replace into tallas_rc(rc,unidad,talla) values(
                '" . $row_talla["rc"]."'
                ,'" . $row_talla["unidad"]."'
                ,'" . $row_talla["talla"]."')";
                $mysqli->query("$query");  
              }

            }

} // fin de sin conexion

                # borra los de la tienda que ya cerro
                $query = "DELETE FROM inv WHERE tienda='037 PCE'";
                $mysqli->query($query);
                
            # crea la tabla alternativa a la precargada de curvas de porcentajes de tallas
            # esta tabla viene de un número más exacto de tallas por RC pero no existe curva
            # por lo que la tenemos que calcular en base a la tabla de tallas original
            # la tabla tallas_rc se carga directamente de un archivo csv exportado de la base de datos de Bruno Corsa
            # select left(icod,11),ium,iupc from finv where itipo=1

            /* # para ahorrar tiempo solo corremos este proceso una vez
            $query = "delete from tallas_comp";
            $mysqli->query($query); */
            
            $query = "replace into tallas_comp
            SELECT a.rc,a.talla,AVG(b.participacion) AS part,COUNT(*) AS tot_tallas
            FROM tallas_rc a INNER JOIN tallas b ON a.talla=b.talla
            INNER JOIN inv_res c ON c.fecha=date_add(CURDATE(),interval -1 day) AND c.rc=a.rc AND b.`genero`=c.genero
            GROUP BY 1,2";
            $mysqli->query($query);   

            # arregla los que se pasan
            # saca el porcentaje del total y luego ese porcentaje lo toman como la nueva participacion
            # primero necesitamos saber el total de cada rc
            $query = "CREATE TEMPORARY TABLE tot_part
            SELECT rc,SUM(part) AS tot_part
            FROM tallas_comp
            GROUP BY 1";
            $mysqli->query($query);

            $query = "UPDATE tallas_comp a INNER JOIN tot_part b ON a.rc=b.rc
            SET a.part=if(a.part=0,.001,a.part)/if(b.tot_part=0,0.001,b.tot_part)";
            $mysqli->query($query);

            $query = "DROP TABLE IF EXISTS tot_part";
            $mysqli->query($query);

            $query = "CREATE TEMPORARY TABLE tot
SELECT rc,COUNT(*) AS tot_tallas FROM tallas_comp GROUP BY 1";
            $mysqli->query($query);

            $query = "UPDATE tallas_comp a INNER JOIN tot b ON a.rc=b.rc
SET a.tot_tallas=b.tot_tallas";
            $mysqli->query($query);

            $query = "drop table if exists tot";
            $mysqli->query($query);

            

            # genera la tabla de resumen que ya contiene el entallado
            $query = "DELETE FROM inv_res WHERE fecha = DATE_ADD(CURDATE(),INTERVAL -0 DAY)";
            $mysqli->query($query);            
    
            // SOLO FUNCIONA CON EL METODO 2
            //if($_POST["metodo"]=="2"){

              $query = "# metodo tipo==2
              INSERT INTO inv_res(fecha,suc,genero,rc,linea,sucursal,descripcion,existencia,transito,tallas,entallado,departamento,tallatipo,anio,alta_suc,color)
              SELECT DATE_ADD(CURDATE(),INTERVAL -0 DAY) AS fecha,a.tienda,a.genero,a.rc,a.linea,a.sucursal,a.descripcion
              ,SUM(a.existencia) AS existencia
              ,SUM(a.transito) AS transito
              ,b.tot_tallas AS tallas,IFNULL(ROUND(SUM(b.part)*100),0) AS entallado
              ,a.departamento,'' AS tipo,a.anio,a.alta_suc,a.color
              FROM inv a LEFT JOIN tallas_comp b ON b.rc=a.rc AND b.talla=a.talla
              WHERE LEFT(a.linea,5)<>'ACCES'
              #AND a.rc='23200918590'
              #AND b.rc IS NULL
              GROUP BY a.tienda,a.rc
              LIMIT 99000";

          /*} else {

              $query = "INSERT INTO inv_res
              SELECT DATE_ADD(CURDATE(),INTERVAL -0 DAY) AS fecha,a.tienda,a.genero,a.rc,a.linea,a.sucursal,a.descripcion
              ,SUM(a.existencia) AS existencia
              ,SUM(a.transito) AS transito
              ,ifnull(b.tot_tallas,2) AS tallas,ifnull(ROUND(SUM(b.participacion)*100),0) AS entallado
              ,a.departamento,b.tipo,a.anio,a.alta_suc,a.color
              FROM inv a LEFT JOIN tallas b
              ON a.`linea`=b.`linea` 
              AND a.talla=b.`talla`
              AND a.`genero`=b.`genero` AND a.departamento=b.departamento
              WHERE LEFT(a.linea,5)<>'ACCES'
              GROUP BY a.tienda,a.rc,a.genero,a.departamento,b.tipo";

          }*/
          
            // ejecuta query
            $mysqli->query($query);

            # pone fecha de un año de entrada a todas
            $query = "update inv_res set ultima_entrada=date_add(curdate(),interval -360 day),ultima_venta=DATE_ADD(CURDATE(),INTERVAL -360 DAY)
            where fecha=curdate()
            ";
            $mysqli->query($query);

            # actualiza fecha de entrada
            $query = "update inv_res a inner join ultima_entrada b
            on LEFT(a.suc,3) = b.tienda and a.rc=b.rc 
            SET a.`ultima_entrada`=b.`ultima_entrada`,a.`ultima_venta`=b.`ultima_venta`,a.`alta_suc`=b.`alta_suc`
            where a.fecha=curdate() 
            ";
            $mysqli->query($query);


$mysqli->query("DELETE FROM tienda_entallado WHERE fecha=CURDATE()");

$mysqli->query("INSERT INTO tienda_entallado
SELECT fecha,suc,genero,linea
            ,SUM(IF(entallado>=porcentaje_entallado_global AND tallas>1,1,0)) AS articulos_entallados
            ,ROUND( 100* SUM(IF(entallado>=porcentaje_entallado_global AND tallas>1,1,0)) /COUNT(*)) AS parte_entallados
            ,SUM(IF(entallado<porcentaje_entallado_global AND tallas>1,1,0)) AS articulos_picos
            ,ROUND( 100* SUM(IF(entallado<porcentaje_entallado_global AND tallas>1,1,0)) /COUNT(*)) AS parte_picos
            ,SUM(IF(tallas=1,1,0)) AS articulos_unitalla
            ,ROUND( 100* SUM(IF(tallas=1,1,0)) /COUNT(*)) AS parte_unitalla
            ,COUNT(*) AS tot_articulos
            ,SUM(existencia) AS tot_existencia
            ,SUM(transito) AS tot_transito
            FROM inv_res inner join globales
            WHERE fecha=CURDATE() 
            GROUP BY suc,genero,linea");

            # agrega las lineas que tienen venta pero no aparecen en el inventario
            $mysqli->query("INSERT INTO tienda_entallado(`fecha`,`suc`,`genero`,`linea`,`articulos_entallados`,`parte_entallados`,`articulos_picos`,`parte_picos`,
            `articulos_unitalla`,`parte_unitalla`,`tot_articulos`,`tot_existencia`,`tot_transito`)
            SELECT CURDATE() AS fecha,a.tienda AS suc,a.genero,a.linea,0 AS art_ent,0 AS part_ent,0 AS art_pic,0 AS part_pic,0 AS art_uni,0 AS part_uni,0 AS tot_art,0 AS tot_ex,0 AS tot_tra
            FROM ventas_gen a LEFT JOIN tienda_entallado b
            ON a.`tienda`=b.`suc` AND a.`genero`=b.`genero` AND a.`linea`=b.`linea`
            AND b.fecha=CURDATE() 
            WHERE a.periodo=DATE_FORMAT(CURDATE(),'%Y%m') 
            AND b.`linea` IS NULL
            GROUP BY 1,2,3,4");

            # metas que no tienen existencia
            # inserta en tabla de tienda_entallado para que aparezacan en el query que muestra todas las metas 
            # en index.php y detalle metas que no tienen existencia
            # este query también debe de ejecutarse al subirse nuevas metas
            $mysqli->query("INSERT INTO tienda_entallado(fecha,suc,genero,linea,articulos_entallados,parte_entallados,articulos_picos,
            parte_picos,articulos_unitalla,parte_unitalla,tot_articulos,tot_existencia,tot_transito)
            SELECT CURDATE() AS fecha,a.tienda AS suc,a.genero,a.linea,0 AS ent,0 AS pent,0 AS pic,0 AS ppic,0 AS uni,0 AS puni,0 AS arti,0 AS exi,0 AS transi 
            FROM metas a
            LEFT JOIN tienda_entallado b ON b.suc=a.tienda AND b.genero=a.genero AND b.linea=a.linea
            AND b.fecha=CURDATE()
            WHERE b.linea IS NULL
            GROUP BY 1,2,3,4");
            
            $mysqli->query("DELETE FROM tienda_entallado WHERE suc='piezas'");

            $mysqli->query("DROP TABLE if exists linea_inv");

            # para revisar las categorias de inv vs metas
            $mysqli->query("CREATE TABLE linea_inv
            SELECT a.genero,a.linea,COUNT(DISTINCT(a.tienda)) AS tiendas,COUNT(*) AS tallas_modelos
            ,(SUM(a.existencia)) AS existencia
            ,(SUM(a.transito)) AS transito
            ,(SUM(a.total)) AS total
            ,(SUM(a.total*costo)) AS costo_pesos
            ,(SUM(a.total*precio_linea)) AS linea_pesos
            FROM inv a 
            WHERE LEFT(a.linea,5)<>'ACCES'
            GROUP BY 1,2");

            # totales para calcular sugeridos por porcentajes de venta en lotes y pzas
            $query = "REPLACE INTO tot_exist(fecha,suc,genero,tot_lotes,tot_pzas)
            select fecha,suc,genero,sum(articulos_entallados+articulos_picos) as tot_lotes,sum(tot_existencia+tot_transito) as tot_pzas
            from tienda_entallado 
            where fecha=curdate()
            group by 1,2,3";
            $mysqli->query($query);

            $tiempo_final = microtime(true);
            $tiempo = round($tiempo_final - $tiempo_inicial);
            $date = date('m/d/Y h:i:s a', time());
            $mensaje = "se cargargon los datos ".$tie." en ".$tiempo." segundos. ".$date; 

            $mysqli->query("insert into log(tipo,log) values('inv','$mensaje')"); 

        } catch (mysqli_sql_exception $e) { // Failed to connect? Lets see the exception details..
            echo "MySQLi Error Code: " . $e->getCode() . "<br />";
            echo "Exception Msg: " . $e->getMessage();
            echo "<hr>" . $query ."<hr>" .$query2;
            exit; // exit and close connection.
        }

        $mysqli->close(); // finally, close the connection
        if(isset($_GET["conectar"])){
        } else {
          $mysqli2->close(); // finally, close the connection
        }
        
   

 // FIN de ya confirmaron pulsando el boton
// ****************************************************************************************************       
} 
    
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Make MySQLi throw exceptions.

        try {
            // Try Connect to the DB with new MySqli object - Params {hostname, userid, password, dbname}
            $mysqli = new mysqli($host, $user, $pass, $base);


              $tienda = "Inventario";
              
              $titulo = "Resumen";
              if(isset($mensaje)){
                $subtitulo = $mensaje;
              } else {
                $subtitulo = "La actualización del inventario tarda 40 segs. aprox.";
              }

            // # para mostrar antes de actualizar el inventario
            $query = "
            SELECT 'TOTAL',COUNT(DISTINCT(a.tienda)) AS tiendas
            ,COUNT(*) AS tallas_modelos
            ,FORMAT(SUM(a.existencia),0) AS existencia
            ,FORMAT(SUM(a.transito),0) AS transito
            ,FORMAT(SUM(a.total),0) AS total
            ,FORMAT(SUM(a.total*costo),0) AS costo_pesos
            ,FORMAT(SUM(a.total*precio_linea),0) AS linea_pesos
            FROM inv a 
            ";

            //echo $query;
            // RESUMEN DE EXISTENCIAS
            if ($result = $mysqli->query($query)) {

                /* fetch associative array */
                while ($row = $result->fetch_assoc()) {
                    
                    $tabla = $tabla . '<tr>
                    <td>'.$row["tiendas"].'</td>
                    <td>'.$row["existencia"].'</td>
                    <td>'.$row["transito"].'</td>
                    <td>'.$row["total"].'</td>
                    <td>$'.$row["linea_pesos"].'</td>
                  </tr>';
                }

                /* free the memory associated with this result set */
                $result->free();
            }

            // MONITOR DEL LOG
            if ($result = $mysqli->query("select id,fecha,log from log where tipo='inv' order by id desc limit 3")) {

              /* fetch associative array */
              while ($row = $result->fetch_assoc()) {
                  
                  $tabla2 = $tabla2 . '<tr>
                  <td>'.$row["id"].'</td>
                  <td>'.$row["fecha"].'</td>
                  <td>'.$row["log"].'</td>
                </tr>';
              }

              /* free the memory associated with this result set */
              $result->free();
          }

        } catch (mysqli_sql_exception $e) { // Failed to connect? Lets see the exception details..
            echo "MySQLi Error Code: " . $e->getCode() . "<br />";
            echo "Exception Msg: " . $e->getMessage();
            echo "Query: " . $query;
            exit; // exit and close connection.
        }

        $mysqli->close(); // finally, close the connection
    
 ?>  
 
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Start your development with a Dashboard for Bootstrap 4.">
  <meta name="author" content="Creative Tim">
  <title><?php echo $marca;?></title>

  <!-- Fonts -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700">
  <!-- Icons -->
  <link rel="stylesheet" href="../../assets/vendor/nucleo/css/nucleo.css" type="text/css">
  <link rel="stylesheet" href="../../assets/vendor/@fortawesome/fontawesome-free/css/all.min.css" type="text/css">
  <!-- Page plugins -->
  <link rel="stylesheet" href="../../assets/vendor/datatables.net-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="../../assets/vendor/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css">
  <link rel="stylesheet" href="../../assets/vendor/datatables.net-select-bs4/css/select.bootstrap4.min.css">
  <!-- Argon CSS -->
  <link rel="stylesheet" href="../../assets/css/argon.css?v=1.1.0" type="text/css">

</head>

<body>

  <!-- menu lateral -->
  <?php include "menu.php"?>
  
  <!-- Main content -->
  <div class="main-content" id="panel">
    <!-- Topnav -->
    
    <!-- Header -->
    <!-- Header -->
    <div class="header bg-primary pb-6">
      <div class="container-fluid">
        <div class="header-body">
        <div class="row align-items-center py-4">

<div class="col-lg-6 col-7">
  <h6 class="h2 text-white d-inline-block mb-0"><?php echo $tienda;?></h6>
</div>

  <!-- Sidenav toggler -->
  <?php include "toggler.php"?>


</div>
        </div>
      </div>
    </div>
    <!-- Page content -->
    <div class="container-fluid mt--6">
      <!-- Table -->
      <div class="row">
        <div class="col">
          <div class="card">
            <!-- Card header -->
            <div class="card-header">
              <h3 class="mb-0"><?php echo $titulo;?></h3>
              <p class="text-sm mb-0">
              <?php echo $subtitulo;?>
              </p>
            </div>

            <div id="boton" class="card-header bg-transparent border-0">
              <form method="post" name="forma1" id="forma1">
                <input type="hidden" name="confirma" id="confirma">
                <input type="hidden" name="metodo" id="metodo">
                <!-- metodo 1 tabla de curvas-->
                <!--a href="#" class="btn btn-sm btn-neutral" onclick="document.getElementById('confirma').value='si';document.getElementById('boton').style.display='none';document.getElementById('imagen').style.display='inline';document.getElementById('forma1').submit();return false;">Actualizar inventario</a-->
                <!-- metodo 2 tabla de tallas por RC con curvas calculadas -->
                <a href="#" class="btn btn-sm btn-neutral" onclick="document.getElementById('confirma').value='si';document.getElementById('metodo').value='2';document.getElementById('boton').style.display='none';document.getElementById('imagen').style.display='inline';document.getElementById('forma1').submit();return false;">Actualizar inventario tallas por RC</a>
             </form>
            </div>
            <div id="imagen" style="display:none">
                <img src="procesing.gif" width="100" height="100">
            </div>

            <!-- RESUMEN DE EXISTENCIAS -->
            <div class="table-responsive py-4">
              <table class="table table-flush">
                <thead class="thead-light">
                  <tr>
                    <th>Tiendas</th>
                    <th>Existencia</th>
                    <th>Transito</th>
                    <th>Total</th>
                    <th>Total pesos</th>
                  </tr>
                </thead>
                <tbody>
                  <?php echo $tabla;?>
                </tbody>
              </table>
            </div>
          </div>
           
              <!-- LOG -->
              <div>
              <table class="table table-primary">
                <thead class="thead-light">
                  <tr>
                    <th>ID</th>
                    <th>Fecha</th>
                    <th>Log</th>
                  </tr>
                </thead>
                <tbody  class="thead-light">
                  <?php echo $tabla2;?>
                </tbody>
              </table>
            </div>  
         
        </div>
      </div>
       <!-- Footer -->
       <footer class="footer pt-0">
         <div class="row align-items-center justify-content-lg-between">
           <div class="col-lg-6">
             <div class="copyright text-center text-lg-left text-muted">
               &copy; <?php echo $anio;?> <a href="#" class="font-weight-bold ml-1" ><?php echo $marca;?></a>
             </div>
           </div>

         </div>
       </footer>
    </div>
  </div>
  <!-- Argon Scripts -->
  <!-- Core -->
  <script src="../../assets/vendor/jquery/dist/jquery.min.js"></script>
  <script src="../../assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <script src="../../assets/vendor/js-cookie/js.cookie.js"></script>
  <script src="../../assets/vendor/jquery.scrollbar/jquery.scrollbar.min.js"></script>
  <script src="../../assets/vendor/jquery-scroll-lock/dist/jquery-scrollLock.min.js"></script>
  <!-- Optional JS -->
  <script src="../../assets/vendor/datatables.net/js/jquery.dataTables.min.js"></script>
  <script src="../../assets/vendor/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/buttons.html5.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/buttons.flash.min.js"></script>
  <script src="../../assets/vendor/datatables.net-buttons/js/buttons.print.min.js"></script>
  <script src="../../assets/vendor/datatables.net-select/js/dataTables.select.min.js"></script>
  <!-- Argon JS -->
  <script src="../../assets/js/argon.js?v=1.1.0"></script>

</body>

</html>
 