<?php
include 'sesion_user.php';
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Sistema Stock</title>
  <!-- Bootstrap CSS -->
  <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 onload="document.forms['form14'] && document.forms['form14']['busqueda'] ? document.forms['form14']['busqueda'].focus() : null">

<div class="container-fluid">
  <div class="row">
    <!-- Panel Izquierdo -->
    <div class="col-lg-3 col-md-3 col-sm-12"
         style="background-color: #C8C8C8; border-right: 1px solid #000;">
      <?php include 'nav.php'; ?>
    </div>

    <!-- Contenido principal -->
    <div class="col-lg-9 col-md-9 col-sm-12">
      <?php include 'inc_buscar.php'; ?>
      <div style="padding-top: 98px;"></div>

      <h3>ESTADÍSTICAS</h3>
      <hr>

      <h2>
        <a href="estadisticas_full_grafico.php">ESTADISTICAS GRAFICAS</a>
      </h2>
      <hr>

      <a href="estadisticas_mes.php">ESTADISTICAS GENERALES POR MES (VENTAS EN BRUTO)</a>
      <hr>

      <!-- NUEVO: selector para ver por MES dentro del mismo archivo -->
      <p>VER ESTADISTICAS POR MES:</p>
      <form action="estadisticas.php" method="get" class="form-inline mb-3">
        <input type="hidden" name="modo" value="mes">

        <label for="mes_sel" class="mr-2">Mes:</label>
        <select id="mes_sel" name="mes" class="form-control mr-2">
          <?php
          $meses = array(
            "01" => "Enero", "02" => "Febrero", "03" => "Marzo", "04" => "Abril",
            "05" => "Mayo", "06" => "Junio", "07" => "Julio", "08" => "Agosto",
            "09" => "Septiembre", "10" => "Octubre", "11" => "Noviembre", "12" => "Diciembre"
          );

          $mes_default = isset($_GET['mes']) ? $_GET['mes'] : date('m');
          if (!isset($meses[$mes_default])) { $mes_default = date('m'); }

          foreach ($meses as $val => $txt) {
            $sel = ($val == $mes_default) ? "selected" : "";
            echo "<option value=\"$val\" $sel>$txt</option>";
          }
          ?>
        </select>

        <label for="anio_sel" class="mr-2">Año:</label>
        <select id="anio_sel" name="anio" class="form-control mr-2">
          <?php
          $anio_default = isset($_GET['anio']) ? (int)$_GET['anio'] : (int)date('Y');
          if ($anio_default < 2001) $anio_default = 2001;
          if ($anio_default > 2060) $anio_default = 2060;

          for ($y = 2001; $y <= 2060; $y++) {
            $sel = ($y == $anio_default) ? "selected" : "";
            echo "<option value=\"$y\" $sel>$y</option>";
          }
          ?>
        </select>

        <button type="submit" class="btn btn-primary">VER POR MES</button>
      </form>
      <hr>

      <!-- EXISTENTE: ver estadísticas diarias del mes (redirige a estadisticas_dia.php) -->
      <p>VER ESTADISTICAS DIARIAS DEL MES DE:</p>
      <form action="estadisticas_dia.php" method="get" class="form-inline">
        <label for="mes" class="mr-2">Selecciona un mes:</label>
        <select id="mes" name="mes" class="form-control mr-2">
          <option value="01">Enero</option>
          <option value="02">Febrero</option>
          <option value="03">Marzo</option>
          <option value="04">Abril</option>
          <option value="05">Mayo</option>
          <option value="06">Junio</option>
          <option value="07">Julio</option>
          <option value="08">Agosto</option>
          <option value="09">Septiembre</option>
          <option value="10">Octubre</option>
          <option value="11">Noviembre</option>
          <option value="12">Diciembre</option>
        </select>
        <button type="submit" class="btn btn-primary">Enviar</button>
      </form>
      <hr>

      <!-- EXISTENTE: ver estadísticas de otro día (por POST) -->
      <p>VER ESTADISTICAS DE OTRO DIA:</p>
      <p>SELECCIONE FECHA A CONSULTAR:</p>
      <form action="estadisticas.php" method="post" class="form-inline mb-3">
        <label for="fecha" class="mr-2">Fecha:</label>
        <input type="date" name="fecha" id="fecha" class="form-control mr-2" required>
        <button type="submit" class="btn btn-success">VER ESTADÍSTICAS</button>
      </form>
      <hr>

      <?php
      include 'concha.php';
      mysql_connect("$host","$usuario","$contra");
      mysql_select_db("$basedatos");

      // MODO: si viene ?modo=mes => muestra acumulado por mes/año
      $modo = (isset($_GET['modo']) && $_GET['modo'] == 'mes') ? 'mes' : 'dia';

      if ($modo == 'mes') {

        $M_a = isset($_GET['mes']) ? $_GET['mes'] : date('m');
        $A_a = isset($_GET['anio']) ? (int)$_GET['anio'] : (int)date('Y');

        // sanitizar
        if (!preg_match('/^(0[1-9]|1[0-2])$/', $M_a)) { $M_a = date('m'); }
        if ($A_a < 2001) $A_a = 2001;
        if ($A_a > 2060) $A_a = 2060;

        echo "<h3>ESTADISTICAS DEL MES: $M_a / $A_a</h3>";

        echo "<table class='table table-bordered table-striped'>";
        echo "<thead class='thead-dark'>";
        echo "  <tr>";
        echo "    <th>PRODUCTO</th>";
        echo "    <th class='text-center'>CANTIDAD VENDIDA EN EL MES $M_a / $A_a</th>";
        echo "  </tr>";
        echo "</thead>";
        echo "<tbody>";

        // OJO: tabla estadisticas tiene d,m,a,cant,barcode
        // Para mes: sumamos cant agrupado por barcode
        $sql = "SELECT barcode, SUM(cant) AS total_cant
                FROM `estadisticas`
                WHERE `m` = ".(int)$M_a."
                  AND `a` = ".$A_a."
                GROUP BY barcode
                ORDER BY total_cant DESC";
        $consulta = mysql_query($sql);

        while ($row = mysql_fetch_array($consulta)) {
          $cant = (int)$row["total_cant"];
          $barcode = $row["barcode"];

          $sql2 = "SELECT * FROM `articulos` WHERE `barcode` = $barcode LIMIT 1";
          $consulta2 = mysql_query($sql2);

          $titulo = '';
          if ($consulta2) {
            while ($row2 = mysql_fetch_array($consulta2)) {
              $titulo = $row2["titulo"];
            }
            mysql_free_result($consulta2);
          }

          if ($titulo == '') { $titulo = 'Sin título'; }

          echo "<tr>";
          echo "  <td>".htmlspecialchars($titulo, ENT_QUOTES, 'UTF-8')." ($barcode)</td>";
          echo "  <td class='text-center'>$cant</td>";
          echo "</tr>";
        }

        if ($consulta) mysql_free_result($consulta);

        echo "</tbody>";
        echo "</table>";

      } else {

        // MODO DIA (igual que tenías)
        if (isset($_POST['fecha']) && !empty($_POST['fecha'])) {
          list($A_a, $M_a, $D_a) = explode('-', $_POST['fecha']);
        } else {
          $D_a = date('d');
          $M_a = date('m');
          $A_a = date('Y');
        }

        $D_a = (int)$D_a;
        $M_a = (int)$M_a;
        $A_a = (int)$A_a;

        echo "<h3>$D_a / $M_a / $A_a</h3>";

        echo "<table class='table table-bordered table-striped'>";
        echo "<thead class='thead-dark'>";
        echo "  <tr>";
        echo "    <th>PRODUCTO</th>";
        echo "    <th class='text-center'>CANTIDAD VENDIDA EL DÍA $D_a / $M_a / $A_a</th>";
        echo "  </tr>";
        echo "</thead>";
        echo "<tbody>";

        $sql = "SELECT * FROM `estadisticas`
                WHERE `d` = $D_a
                  AND `m` = $M_a
                  AND `a` = $A_a
                ORDER BY `estadisticas`.`cant` DESC";
        $consulta = mysql_query($sql);

        while ($row = mysql_fetch_array($consulta)) {
          $cant = (int)$row["cant"];
          $barcode = $row["barcode"];

          $sql2 = "SELECT * FROM `articulos` WHERE `barcode` = $barcode LIMIT 1";
          $consulta2 = mysql_query($sql2);

          $titulo = '';
          if ($consulta2) {
            while ($row2 = mysql_fetch_array($consulta2)) {
              $titulo = $row2["titulo"];
            }
            mysql_free_result($consulta2);
          }

          if ($titulo == '') { $titulo = 'Sin título'; }

          echo "<tr>";
          echo "  <td>".htmlspecialchars($titulo, ENT_QUOTES, 'UTF-8')." ($barcode)</td>";
          echo "  <td class='text-center'>$cant</td>";
          echo "</tr>";
        }

        if ($consulta) mysql_free_result($consulta);

        echo "</tbody>";
        echo "</table>";
      }
      ?>
    </div>
  </div>
</div>

<!-- Scripts de Bootstrap y dependencias -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"
        integrity="sha384-b/U6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
        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(){
    if (typeof $('.grid').isotope === 'function') {
      $('.grid').isotope({ itemSelector: '.grid-item' });
    }
  }, 2000);
</script>

<script>
function ventanaSecundaria56(URL){
   window.open(URL,"ventana1","width=600,height=500,scrollbars=NO");
}
</script>

</body>
</html>
