<?php
include "conn.php";

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


              $tipo1 = " AND a.linea='".$_GET["tienda"]."' AND a.genero='".$_GET["gen"]."'";


              $tienda = "Por categoría";
              
              $titulo = $_GET["tienda"]." - ".$_GET["gen"];
              $subtitulo = "Artículos entallados que debería tener cada tienda en base a su venta por Categoría";


            // Select all records from the db. Keep inside try block incase there an issue with sql query
            $query = "SELECT a.fecha,a.tienda,a.genero,a.linea
            ,a.`nivel_servicio_porc` AS nivel_servicio_actual
            ,b.`nivel_servicio_porc` AS nivela_servicio_global
            ,ROUND(a.`meta_total` * (b.`nivel_servicio_porc`/100)) AS nivela_lotes
            #,ROUND(100*a.`meta_total` * (b.`nivel_servicio_porc`/100)) / a.meta_total as new_serv
            ,ROUND(a.`meta_total` * (b.`nivel_servicio_porc`/100)) - a.`articulos_entallados` AS dif_lotes
            ,a.`venta_pesos`,a.`venta_piezas`,a.meta_total,a.total AS tot_exist,a.`compra_lotes`
            ,a.`articulos_entallados`
            ,r.existencia,r.transito,r.salidas,r.entradas
            FROM cat_nivel_servicio a INNER JOIN cat_tot_nivel_servicio b
            ON a.fecha=b.fecha AND a.genero=b.genero AND a.linea=b.linea
            left join nivela_resumen r on r.fecha=a.fecha and r.suc=a.tienda
            and r.genero=a.genero and r.linea=a.linea
            WHERE a.fecha=CURDATE() ".$tipo1."
            ";

            //die($tipo1);
            
            if ($result = $mysqli->query($query)) {

                /* fetch associative array */
                while ($row = $result->fetch_assoc()) {
                    
                    if($tienda==''){
                      $tienda = $row["sucursal"];
                    }

                    $tabla = $tabla . '<tr>
                    <td>'.$row["tienda"].'</td>
                    <td><a href="nivela_tienda.php?tienda='.$row["tienda"].'&linea='.$row["linea"].'&gen='.$row["genero"].'">'.$row["linea"].'</a></td>
                    <td>'.$row["meta_total"].'</td>
                    <td>'.$row["nivel_servicio_actual"].'%</td>
                    <td>'.$row["nivela_servicio_global"].'%</td>
                    <td>'.$row["articulos_entallados"].'</td>
                    <td>'.$row["nivela_lotes"].'</td>
                    <td>'.$row["dif_lotes"].'</td>
                    <td>'.$row["existencia"].'</td>
                    <td>'.$row["transito"].'</td>
                    <td>'.$row["entradas"].'</td>
                    <td>'.$row["salidas"].'</td>

                  </tr>';
                }

                // ******** TOTAL **************
                $query = "SELECT a.fecha,'TOTAL' as tienda,a.genero,a.linea
                ,AVG(a.`nivel_servicio_porc`) AS nivel_servicio_actual
                ,AVG(b.`nivel_servicio_porc`) AS nivela_servicio_global
                ,SUM( ROUND(a.`meta_total` * (b.`nivel_servicio_porc`/100)) ) AS nivela_lotes
                ,SUM( ROUND(a.`meta_total` * (b.`nivel_servicio_porc`/100)) - a.`articulos_entallados` ) AS dif_lotes
                ,SUM( a.`venta_pesos` ) AS venta_pesos
                ,SUM( a.`venta_piezas` ) AS venta_piezas
                ,SUM( a.meta_total ) AS meta_total
                ,SUM( a.total ) AS tot_exist
                ,SUM( a.`compra_lotes` ) AS compra_lotes
                ,SUM( a.`articulos_entallados` ) AS articulos_entallados
                ,sum(r.existencia) as existencia,sum(r.transito) as transito,sum(r.salidas) as salidas
                ,sum(r.entradas) as entradas
            FROM cat_nivel_servicio a INNER JOIN cat_tot_nivel_servicio b
            ON a.fecha=b.fecha AND a.genero=b.genero AND a.linea=b.linea
            left join nivela_resumen r on r.fecha=a.fecha and r.suc=a.tienda
            and r.genero=a.genero and r.linea=a.linea
            WHERE a.fecha=CURDATE()  ".$tipo1."
                ";

                if ($result = $mysqli->query($query)) {
    
                  /* fetch associative array */
                  while ($row = $result->fetch_assoc()) {
                      
                      $totales = $totales . '<tr>
                      <th>'.$row["tienda"].'</th>
                      <th><a href="sucursal_detalle.php?suc='.$row["tienda"].'&linea='.$row["linea"].'&gen='.$row["genero"].'">'.$row["linea"].'</a></th>
                      <th>'.$row["meta_total"].'</th>
                      <th>'.$row["nivel_servicio_actual"].'%</th>
                      <th>'.$row["nivela_servicio_global"].'%</th>
                      <th>'.$row["articulos_entallados"].'</th>
                      <th>'.$row["nivela_lotes"].'</th>
                      <th>'.$row["dif_lotes"].'</th>
                      <th>'.$row["existencia"].'</th>
                      <th>'.$row["transito"].'</th>
                      <th>'.$row["entradas"].'</th>
                      <th>'.$row["salidas"].'</th>  
                    </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();
            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 class="card-header bg-transparent border-0">
              <a href="nivela_traspasos.php?gen=<?php echo $_GET["gen"]?>&tienda=<?php echo $_GET["tienda"]?>" class="btn btn-sm btn-neutral">Movimientos</a>
              <a href="cumplimiento.php?gen=<?php echo $_GET["gen"]?>&linea=<?php echo $_GET["tienda"]?>" class="btn btn-sm btn-neutral">Cumplimiento</a>
            </div>

            <div class="table-responsive py-4">
              <table class="table table-flush" id="datatable-basic" data-order='[[ 2, "desc" ]]' data-page-length='100'>
                <thead class="thead-light">
                  <tr>
                    <th>Tienda</th>
                    <th>Linea</th>
                    <th>Meta</th>
                    <th>Nivel actual</th>
                    <th>Nivel global</th>
                    <th>Lotes actuales</th>
                    <th>Lotes nivelados</th>
                    <th>Lotes dif</th>
                    <th>existencia</th>
                      <th>transito</th>
                      <th>entradas</th>
                      <th>salidas</th>                      
                    </tr>  
                </thead>

                <thead class="thead-light">
                <?php echo $totales;?>
                </thead>

                <tfoot>
                <?php echo $totales;?>

                  <tr>
                <th>Tienda</th>
                    <th>Linea</th>
                    <th>Meta</th>
                    <th>Nivel actual</th>
                    <th>Nivel global</th>
                    <th>Lotes actuales</th>
                    <th>Lotes nivelados</th>
                    <th>Lotes dif</th>
                    <th>existencia</th>
                      <th>transito</th>
                      <th>entradas</th>
                      <th>salidas</th>  
                  </tr>
                </tfoot>
                <tbody>
                  <?php echo $tabla;?>
                </tbody>
              </table>
            </div>
          </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>