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

                # borra los que ya existen en el destino
                # se paso al sp_pre_nivela_categorias

                $tie = 0;

                # elimina los que ya se hicieron en lotifica
                $query = "UPDATE cat_movs_rank a 
                INNER JOIN movs_buenos b ON b.fecha=a.fecha AND b.origen=a.`tienda` AND b.rc=a.rc
                SET a.borrado=5,a.elegido=5
                WHERE a.fecha=CURDATE() AND a.borrado=0 AND a.elegido=0";
                $mysqli->query($query);

                $query = "DELETE FROM cat_movs_rank WHERE borrado in (1,5)";
                $mysqli->query($query);
    
            for ($x = 0; $x <= 400; $x++) {



            # eligiendo...
            /*$query = "
            SELECT a.fecha,a.rank,a.previo,a.tienda,a.genero,a.linea,a.lotes_actuales,a.lotes_nivelados,a.dif_lotes,a.rc,a.codigo
            ,a.talla,a.existencia,a.transito,a.tallas,a.descripcion,a.tienda2,a.dif_lotes2,a.borrado,a.elegido
            FROM cat_movs_rank a 
            left join movs_buenos b on b.fecha=a.fecha and b.origen=a.`tienda` and b.rc=a.rc
            WHERE a.fecha=CURDATE() AND a.borrado=0 AND a.elegido=0 
            and b.rc is null
            ORDER BY a.rank
            LIMIT 10";*/

            # eligiendo...
            $query = "
            SELECT fecha,rank,previo,tienda,genero,linea,lotes_actuales,lotes_nivelados,dif_lotes,rc,codigo
            ,talla,existencia,transito,tallas,descripcion,tienda2,dif_lotes2,borrado,elegido
            FROM cat_movs_rank
            WHERE fecha=CURDATE() AND borrado=0 AND elegido=0 
            ORDER BY rank
            LIMIT 10";

            if ($result = $mysqli->query($query)) {

                if($row = $result->fetch_assoc()){

                    $rank = $row["rank"];
                    //die("rank = ".$rank);
                    $query_sp = "CALL sp_nivela_categorias($rank)";
                    $tie++;
                    $mysqli->query($query_sp); 

                }

            }

        } // for

        // genera el resumen de movimientos
        $query = "call sp_nivela_resumen()";
        $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 ".$tie." en ".$tiempo." segundos. ".$date; 

            $mysqli->query("insert into log(tipo,log) values('nivela','$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 = "Nivela categorías";
              
              $titulo = "Resumen";
              if(isset($mensaje)){
                $subtitulo = $mensaje;
              } else {
                $subtitulo = "El nivela categorías toma 10 mins. aprox.";
              }

            // # para mostrar antes de actualizar el inventario
            $query = "# revisa completados salida y entrada
            SELECT IF(a.dif_lotes>0,a.dif_lotes - a.completados,a.completados + a.dif_lotes) AS falta_nivelar
            ,a.tienda,a.genero,a.linea,a.nivel_servicio_actual,a.lotes_actuales,a.nivela_servicio_global
            ,a.lotes_nivelados,a.dif_lotes,a.meta_total,a.completados
            FROM cat_dif_lotes a
            WHERE fecha=CURDATE() AND completados<>0";

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

                /* fetch associative array */
                while ($row = $result->fetch_assoc()) {
                    
                    $tabla = $tabla . '<tr>
                    <td>'.$row["falta_nivelar"].'</td>
                    <td>'.$row["tienda"].'</td>
                    <td>'.$row["genero"].'</td>
                    <td>'.$row["linea"].'</td>
                    <td>'.$row["nivel_servicio_actual"].'%</td>
                    <td>'.$row["lotes_actuales"].'</td>
                    <td>'.$row["nivela_servicio_global"].'%</td>
                    <td>'.$row["lotes_nivelados"].'</td>
                    <td>'.$row["dif_lotes"].'</td>
                    <td>'.$row["meta_total"].'</td>
                    <td>'.$row["completados"].'</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='nivela' 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;">Nivela Categorías</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>falta_nivelar</th>
                    <th>tienda</th>
                    <th>genero</th>
                    <th>linea</th>
                    <th>nivel_servicio_actual</th>
                    <th>lotes_actuales</th>
                    <th>nivela_servicio_global</th>
                    <th>lotes_nivelados</th>
                    <th>dif_lotes</th>
                    <th>meta_total</th>
                    <th>completados</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>
 