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



            # procesando...
            # borra curva anterior
            $query = "DELETE FROM tallas_comp";
            $mysqli->query($query);

            # agregar cero a la izquierda
            $query = "# agregar cero a la izquierda
            UPDATE tallas_comp_vta
            SET rc=  CONCAT('0',rc)
            WHERE LENGTH(rc)=10";
            $mysqli->query($query);

            # arreglando los de 1 que no son unitalla
            $query = "# arreglando los de 1 que no son unitalla
            REPLACE INTO tallas_comp
            SELECT a.rc,a.talla,IF( part>=1 AND talla<>'unitalla' , part_vta  , IF(part>0,part,IF(part_prom>0,part_prom,IF(part_vta>0,part_vta,part_compra))) ) AS part_if,IF(a.talla='unitalla',1,2) AS tallas
            FROM tallas_comp_vta a ";
            $mysqli->query($query);

            # regenera la tabla con las nuevas curvas de participación por tallas 
            $query = "# regenera la tabla con las nuevas curcas de participación por tallas 
            DELETE FROM inv_res WHERE fecha = DATE_ADD(CURDATE(),INTERVAL -0 DAY)";
            $mysqli->query($query);

            # metodo tipo==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";
            $mysqli->query($query);

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

            # regenera la tabla tienda_entallado
            $query = "# regenera la tabla tienda_entallado
            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";
            $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 procesaron en ".$tiempo." segundos. ".$date; 

            $mysqli->query("insert into log(tipo,log) values('cambia_curva','$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.
        }


 // 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 = "Curvas de participación por talla";
              
              $titulo = "Tomando las primeras 4 semanas de venta después de la compra";
              if(isset($mensaje)){
                $subtitulo = $mensaje;
              } else {
                $subtitulo = "El cambio de las participaciones toma 10 segs. aprox.";
              }

            // # para mostrar antes de actualizar el inventario
            $query = "SELECT 'TOTAL' AS tienda,a.genero,CONCAT('$',FORMAT(SUM(ROUND(a.mntovta)),0)) AS venta_pesos
            ,SUM(ROUND(100*porc_vta,1)) AS porc_vta
            ,FORMAT(SUM(ROUND(a.piezas)),0) AS venta_piezas
            ,SUM(ROUND(100*porc_pza,1)) AS porc_pza
            ,ROUND(SUM(a.porc_vta)*SUM(meta_piso)) AS entallados_venta
            ,CONCAT(FORMAT(SUM(c.articulos_entallados),0),' --> ',ROUND(100*SUM(c.articulos_entallados)/(SUM(c.articulos_entallados)+SUM(c.articulos_picos))),'%') AS entallados
            ,CONCAT(FORMAT(SUM(c.articulos_picos),0),' --> ',ROUND(100*SUM(c.articulos_picos)/(SUM(c.articulos_entallados)+SUM(c.articulos_picos))),'%') AS picos
            ,FORMAT(SUM(c.articulos_entallados)+SUM(c.articulos_picos),0) AS tot_lotes
            ,FORMAT(SUM(b.meta_piso),0) AS meta_piso
            ,FORMAT(SUM(b.meta_bodega),0) AS meta_bodega
            ,FORMAT(SUM(b.meta_piso)+SUM(b.meta_bodega),0) AS meta_total
              ,SUM(b.meta_piso)+IFNULL(SUM(b.meta_bodega),0)-SUM(c.articulos_entallados) AS compra_lotes
              ,IFNULL(ROUND(10*SUM(c.articulos_entallados) / (SUM(b.meta_piso)+IFNULL(SUM(b.meta_bodega),0)) ),0) AS nivel_servicio
              ,IFNULL(ROUND(100*SUM(c.articulos_entallados) / (SUM(b.meta_piso)+IFNULL(SUM(b.meta_bodega),0)) ),0) AS nivel_servicio_porc
            ,FORMAT(SUM(c.tot_existencia),0) AS existencia
            ,FORMAT(SUM(c.tot_transito),0) AS transito
            ,FORMAT(SUM(c.tot_transito)+SUM(c.tot_existencia),0) AS total
            ,SUM(b.meta_cedis_calc) AS meta_cedis_calc
            FROM ventas_gen a RIGHT JOIN tienda_entallado c
            ON a.tienda=c.suc AND a.genero=c.genero AND a.linea=c.linea
            AND a.periodo = DATE_FORMAT(CURDATE(),'%Y%m') 
            LEFT JOIN metas2 b ON b.tienda=c.suc AND b.genero=c.genero AND b.linea=c.linea
            WHERE c.linea<>'' AND c.fecha=CURDATE()
            GROUP BY 1,2";

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

                /* fetch associative array */
                while ($row = $result->fetch_assoc()) {
                    
                    $tabla = $tabla . '<tr>
                    <td>'.$row["genero"].'</td>
                    <td>'.$row["entallados"].'</td>
                    <td>'.$row["picos"].'</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='cambia_curva' 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;">Cambia curva de tallas</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" id="datatable-basic" data-order='[[ 3, "desc" ]]' data-page-length='100'-->    
            <table class="table table-flush" id="datatable-basic" data-page-length='100'>
                <thead class="thead-light">
                  <tr>
                    <th>GENERO</th>
                    <th>ENTALLADO</th>
                    <th>PICOS</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>
 