<?php
include 'sesion_user.php';

$d1 = $_POST['d1'];
$d1 = str_pad($d1, 2, "0", STR_PAD_LEFT);
$m1 = $_POST['m1'];
$m1 = str_pad($m1, 2, "0", STR_PAD_LEFT);
$a1 = $_POST['a1'];
$h1 = $_POST['h1'];
$h1 = str_pad($h1, 2, "0", STR_PAD_LEFT);
$min1 = $_POST['min1'];
$min1 = str_pad($min1, 2, "0", STR_PAD_LEFT);
$d2 = $_POST['d2'];
$d2 = str_pad($d2, 2, "0", STR_PAD_LEFT);
$m2 = $_POST['m2'];
$m2 = str_pad($m2, 2, "0", STR_PAD_LEFT);
$a2 = $_POST['a2'];
$h2 = $_POST['h2'];
$h2 = str_pad($h2, 2, "0", STR_PAD_LEFT);
$min2 = $_POST['min2'];
$min2 = str_pad($min2, 2, "0", STR_PAD_LEFT);

$desde ="$a1$m1$d1$h1$min1";
$hasta ="$a2$m2$d2$h2$min2";

// MES y AÑO (por GET) + defaults
$mes = isset($_GET['mes']) && $_GET['mes'] != '' ? $_GET['mes'] : date('m');
$ano = isset($_GET['anio']) && $_GET['anio'] != '' ? $_GET['anio'] : date('Y');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Panel</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
    crossorigin="anonymous">
  <link href="http://radioshosting.com/css/delalora4new.css" rel="stylesheet">
  <link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css" />
  <link rel="stylesheet" href="http://ejemplo.radiosnet.com.ar/css/font-awesome.min.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <style>
    /* Estilos del modal */
    .modal {
      display: none;
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0,0,0,0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 10% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 600px;
    }

    /* Estilos del botón de cierre */
    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }

    /* Estilos del spinner de carga */
    .spinner {
      border: 16px solid #f3f3f3;
      border-top: 16px solid #3498db;
      border-radius: 50%;
      width: 80px;
      height: 80px;
      animation: spin 2s linear infinite;
      margin: 20px auto;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  </style>
</head>

<body onload="document.forms['form14']['busqueda'].focus()">
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-12">
        <?php
          include 'nav.php';
        ?>
      </div>
      <div class="col-lg-9 col-md-9 col-sm-12">
        <?php include 'inc_buscar.php';?>
        <a href="nueva_venta.php"><button type="button" class="btn btn-success">INICIAR UNA VENTA</button></a>
        <hr />

        VER ESTADISTICAS DIARIAS DEL MES DE:

        <form action="estadisticas_dia.php" method="get">
          <label for="mes">Mes:</label>
          <select id="mes" name="mes">
            <option value="01" <?php if($mes=="01") echo "selected"; ?>>Enero</option>
            <option value="02" <?php if($mes=="02") echo "selected"; ?>>Febrero</option>
            <option value="03" <?php if($mes=="03") echo "selected"; ?>>Marzo</option>
            <option value="04" <?php if($mes=="04") echo "selected"; ?>>Abril</option>
            <option value="05" <?php if($mes=="05") echo "selected"; ?>>Mayo</option>
            <option value="06" <?php if($mes=="06") echo "selected"; ?>>Junio</option>
            <option value="07" <?php if($mes=="07") echo "selected"; ?>>Julio</option>
            <option value="08" <?php if($mes=="08") echo "selected"; ?>>Agosto</option>
            <option value="09" <?php if($mes=="09") echo "selected"; ?>>Septiembre</option>
            <option value="10" <?php if($mes=="10") echo "selected"; ?>>Octubre</option>
            <option value="11" <?php if($mes=="11") echo "selected"; ?>>Noviembre</option>
            <option value="12" <?php if($mes=="12") echo "selected"; ?>>Diciembre</option>
          </select>

          &nbsp;&nbsp;

          <label for="anio">Año:</label>
          <select id="anio" name="anio">
            <?php
              $anio_actual = date('Y');
              for($a=2000; $a<=2100; $a++){
                $sel = ($a == $ano) ? 'selected' : '';
                echo "<option value='$a' $sel>$a</option>";
              }
            ?>
          </select>

          &nbsp;&nbsp;
          <button type="submit">Enviar</button>
        </form>

        <hr />
        <div style="background-color:#e4ffe4;">
          <p style="background-color: #28a745; color: white; padding-left: 15px;">
            <b>ESTADÍSTICAS MENSUALES (VENTAS POR DÍA)</b>
          </p>

          <br>
          <b>INGRESOS (VENTAS EN BRUTO) POR DÍA. <br> MES <?php echo $mes; ?> / <?php echo $ano; ?></b>
          <hr><br><br>

          <div id="spinner" class="spinner"></div>

          <style>
            .spinner {
              border: 4px solid rgba(0, 0, 0, 0.1);
              border-top: 4px solid #000;
              border-radius: 50%;
              width: 30px;
              height: 30px;
              animation: spin 1s linear infinite;
              margin: 20px auto;
            }

            @keyframes spin {
              0% { transform: rotate(0deg); }
              100% { transform: rotate(360deg); }
            }
          </style>

          <script>
            document.addEventListener("DOMContentLoaded", function() {
              var spinner = document.getElementById("spinner");
              var termino = document.getElementById("termino");

              function hideSpinner() { spinner.style.display = "none"; }
              function showTermino() { termino.style.display = "block"; }

              var observer = new MutationObserver(function(mutationsList) {
                for (var i = 0; i < mutationsList.length; i++) {
                  var mutation = mutationsList[i];
                  if (mutation.target === termino && mutation.type === "childList") {
                    hideSpinner();
                    showTermino();
                  }
                }
              });

              observer.observe(termino, { childList: true });
            });
          </script>

          <div class="row">
            <?php
              // Fecha de inicio y fin del mes seleccionado
              $fecha_inicio = "$ano-$mes-01";
              $fecha_fin = date("Y-m-t", strtotime($fecha_inicio)); // último día del mes

              // Formatear las fechas en formato legible
              setlocale(LC_TIME, 'es_ES.UTF-8');
              $fecha_inicio_legible = strftime('%d de %B de %Y', strtotime($fecha_inicio));
              $fecha_fin_legible = strftime('%d de %B de %Y', strtotime($fecha_fin));
            ?>

            <div class="alert alert-info text-center">
              <strong>Mostrando estadísticas desde:</strong> <?php echo $fecha_inicio_legible; ?>
              <strong>hasta:</strong> <?php echo $fecha_fin_legible; ?>
            </div>

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

              $i = 1;
              while ($i <= 30) {
            ?>
                <div class="col-12">
                  <?php
                    $i = sprintf('%02d', $i);
                    $i_mas = $i + 1;
                    $i_mas = sprintf('%02d', $i_mas);

                    $desde1 = "".$ano."".$mes."".$i."0500";
                    $hasta1 = "".$ano."".$mes."".$i_mas."0459";

                    $total_tol = 0;
                    $c_ventas = 0;
                    $prom_venta = 0;

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

                    $sql = "SELECT total FROM `ventas`
                            WHERE `fecha` >= '$desde1'
                              AND `fecha` <= '$hasta1'
                              AND `forma_pago` != 'anulado'
                              AND total != 0
                              AND total > 0";

                    $consulta = mysql_query ($sql);
                    while ($row = mysql_fetch_array($consulta)) {
                      $total = $row["total"];
                      $total_tol = $total_tol + $total;
                      $c_ventas = $c_ventas + 1;
                    }
                    mysql_free_result($consulta);

                    $anio_tmp = $ano;
                    $mes_tmp  = $mes;
                    $dia_tmp  = $i;

                    $fecha = "$anio_tmp-$mes_tmp-$dia_tmp";
                    setlocale(LC_TIME, 'es_ES');
                    $diaDeLaSemana = utf8_encode(strftime('%A', strtotime($fecha)));

                    if ($c_ventas == 0 || $c_ventas == '') {
                      // sin ventas
                    } else {
                      $prom_venta = $total_tol / $c_ventas;
                      $prom_venta = sprintf("%01.2f", $prom_venta);
                    }

                    echo "".ucfirst($diaDeLaSemana)." $i / $mes  : <b>$ $total_tol</b> ($c_ventas VENTAS)  <br>
                    VENTA PROMEDIO: $ $prom_venta<hr>";

                    $i = $i + 1;
                  ?>
                </div>
            <?php } ?>

            <div id="termino"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <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/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4"
    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(){
      $('.grid').isotope({
        itemSelector: '.grid-item'
      });
    }, 2000);
  </script>

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

  <!-- Modal -->
  <div id="myModal" class="modal">
    <div class="modal-content">
      <span class="close">&times;</span>
      <div id="spinner" class="spinner"></div>
      <iframe id="myIframe" src="" style="width: 100%; height: 400px;"></iframe>
    </div>
  </div>

  <script>
    // Obtener elementos del DOM
    var modal = document.getElementById("myModal");
    var btns = document.getElementsByClassName("openModal");
    var closeBtn = document.getElementsByClassName("close")[0];
    var iframe = document.getElementById("myIframe");
    var spinner = document.getElementById("spinner");

    // Función para abrir el modal y actualizar el iframe
    function openModal(url) {
      modal.style.display = "block";
      spinner.style.display = "block";
      iframe.style.display = "none";
      iframe.src = url;
    }

    // Función para cerrar el modal
    function closeModal() {
      modal.style.display = "none";
      spinner.style.display = "none";
      iframe.src = "";
    }

    // Asignar eventos a los botones
    for (var i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", function() {
        var url = this.getAttribute("data-url");
        openModal(url);
      });
    }

    closeBtn.addEventListener("click", closeModal);
    window.addEventListener("click", function(event) {
      if (event.target == modal) {
        closeModal();
      }
    });

    // Evento de carga completada del iframe
    iframe.addEventListener("load", function() {
      spinner.style.display = "none";
      iframe.style.display = "block";
    });
  </script>
</body>
</html>
