<?php
  $Seccion    = 'Reportes';
  $Position   = '../';

  $NameSec      = 'Gráficas';
  $SecLine      = array('Reportes','Gráficas');

  require_once($Position.'config/config.php');
  require_once($Position.'config/conexion.php');
  require_once($Position.'config/user.php');
  require_once($Position.'funciones/acces.php');
  require_once($Position.'funciones/logout.php');
  require_once($Position.'funciones/funciones.php');

  // Function to get all the dates in given range
  function getDatesFromRange($start, $end, $format = 'Y-m-d') {

    // Declare an empty array
    $array = array();

    // Variable that store the date interval
    // of period 1 day
    $interval = new DateInterval('P1D');

    $realEnd = new DateTime($end);
    $realEnd->add($interval);

    $period = new DatePeriod(new DateTime($start), $interval, $realEnd);

    // Use loop to store date into array
    foreach($period as $date) {
      $array[] = $date->format($format);
    }

    // Return the array elements
    return $array;
  }
  // End Function to get all the dates in given range

  if( $_GET['Filtrar'] == 'Ok' ){

    $FechaDesde = CambioFechaCompleta($_GET['Desde']);
    $FechaHasta = CambioFechaCompleta($_GET['Hasta']);

  }else{
    $FechaDesde = date('Y-m-01');
    $FechaHasta = date('Y-m-t');
  }

  $Where = "
    WHERE
     (ven.Fecha BETWEEN '".$FechaDesde." 00:00:00' AND '".$FechaHasta." 23:59:59' )
  ";

  $FilDes = CambioFechaInversa($FechaDesde);
  $FilHas = CambioFechaInversa($FechaHasta);

  // Ventas por Día
  $Query = "
    SELECT
     	DATE(ven.Fecha) AS Fecha,
     	SUM(ven.Total) AS Total
    FROM KB_Ventas ven
    $Where
      AND (ven.FechaCarga IS NULL OR ven.FechaCarga = '')
    GROUP BY DATE(ven.Fecha)
  ";
  $Ventas = $mysqli->query($Query);
  mysqli_data_seek($Ventas, 0);
  while($Ven = mysqli_fetch_array($Ventas)) {
    $Venta[$Ven[Fecha]] = $Ven[Total];
  }
  // End Ventas por Día

  // Ventas por Día
  $Query = "
    SELECT
     	DATE(ven.Fecha) AS Fecha,
     	SUM(ven.Total) AS Total
    FROM KB_Ventas ven
    $Where
      AND (ven.FechaCarga IS NOT NULL AND ven.FechaCarga != '')
    GROUP BY DATE(ven.Fecha)
  ";
  $VentasCargas = $mysqli->query($Query);
  mysqli_data_seek($VentasCargas, 0);
  while($Ven = mysqli_fetch_array($VentasCargas)) {
    $VentaCarga[$Ven[Fecha]] = $Ven[Total];
  }
  // End Ventas por Día

  //Ventas Totales por Producto
  $Query = "
    SELECT
        pro.ProductoClave,
        pr.Nombre,
        SUM(pro.Total) AS Total
       FROM KB_Ventas ven
       LEFT JOIN KB_VentasProductos pro ON pro.Fk_Venta = ven.Id
       LEFT JOIN KB_Productos pr ON pr.Clave = pro.ProductoClave
      $Where
  	GROUP BY pro.ProductoClave
  ";
  $VentasPro = $mysqli->query($Query);
  //Ventas Totales por Producto

  //Ventas Totales por Producto Conteo
  $Query = "
    SELECT
        pro.ProductoClave,
        pr.Nombre,
        COUNT(pro.Id) AS Total
       FROM KB_Ventas ven
       LEFT JOIN KB_VentasProductos pro ON pro.Fk_Venta = ven.Id
       LEFT JOIN KB_Productos pr ON pr.Clave = pro.ProductoClave
      $Where
  	GROUP BY pro.ProductoClave
  ";
  $VentasProCont = $mysqli->query($Query);
  //Ventas Totales por Producto

  $Dates = getDatesFromRange($FechaDesde, $FechaHasta);

  // foreach ($Dates AS $Date) {
  //   echo $Venta[$Date];
  //   echo "<br>";
  // }

?>

<!DOCTYPE html>
<html lang="en">

<?php require_once($Position.'head.php'); ?>

<style>
  /*.ct-bar{
    stroke-width: 30px;
  }
  .ct-series-a .ct-bar, .ct-series-a .ct-line, .ct-series-a .ct-point, .ct-series-a .ct-slice-donu{
    stroke: #007cc6;
  }
  .canvasjs-chart-credit{
    display: none !important;
  }*/

</style>

<body class="fix-sidebar fix-header card-no-border">
    <!-- ============================================================== -->
    <!-- Preloader - style you can find in spinners.css -->
    <!-- ============================================================== -->
    <div class="preloader">
        <svg class="circular" viewBox="25 25 50 50">
            <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" /> </svg>
    </div>
    <!-- ============================================================== -->
    <!-- Main wrapper - style you can find in pages.scss -->
    <!-- ============================================================== -->
    <div id="main-wrapper">
        <?php require_once($Position.'header.php'); ?>
        <?php require_once($Position.'menu.php'); ?>

        <div class="page-wrapper">

          <!-- Container fluid  -->
          <div class="container-fluid">

            <div class="row page-titles page-titles-fixed">

                <?php require_once($Position.'title.php'); ?>

            </div>

            <!-- Inner -->
            <div class="row inner-fixed-content">

              <!-- Buscador -->
              <div class="col-sm-12">
                <form method="get">
                  <div class="card">
                    <div class="card-body">
                      <div class="row">

                        <!-- Desde -->
                        <div class="col-sm-4">
                          <div class="form-group">
                            <label class="control-label">Desde</label>
                            <input name="Desde" value="<?php echo $FilDes; ?>" type="text" class="form-control datepicker" placeholder="">
                          </div>
                        </div>
                        <!-- End Desde -->

                        <!-- Hasta -->
                        <div class="col-sm-4">
                          <div class="form-group">
                            <label class="control-label">Hasta</label>
                            <input name="Hasta" value="<?php echo $FilHas; ?>" type="text" class="form-control datepicker" placeholder="">
                          </div>
                        </div>
                        <!-- End Hasta -->

                        <!-- Filtrar -->
                        <div class="col-sm-4">
                          <div class="form-group">
                            <label class="control-label">.</label>

                            <!-- Btn Filtrar -->
                            <button class="btn btn-success btn-block" type="submit" name="button">
                              Filtrar <i class="fa fa-search mar-l-5"></i>
                            </button>
                            <!-- End Btn Filtrar -->

                            <input type="hidden" name="Filtrar" value="Ok" />
                          </div>
                        </div>
                        <!-- End Filtrar -->

                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <!-- Buscador -->

              <!-- Grafica Ventas --
              <div class="col-sm-12">
                <div class="card">
                  <div class="card-body">
                    <div>
                      <h4>Ventas por día</h4>
                    </div>
                    <div id="chartVentas"
                      style="
                        height: 250px; max-width: 100%; margin: 0px auto;
                      "
                    >
                    </div>
                  </div>
                </div>
              </div>
              <!-- End Grafica Ventas -->

              <!-- Grafica Ventas Cargas -->
              <div class="col-sm-12">
                <div class="card">
                  <div class="card-body">
                    <div>
                      <h4>Ventas por día ( Externas )</h4>
                    </div>
                    <div id="chartVentasCargas"
                      style="
                        height: 250px; max-width: 100%; margin: 0px auto;
                      "
                    >
                    </div>
                  </div>
                </div>
              </div>
              <!-- End Grafica Venta Cargas -->



              <!-- Grafica Ventas por Producto -->
              <div class="col-sm-12">
                <div class="card">
                  <div class="card-body">
                    <h4>Ventas por producto (Ingresos)</h4>
                    <div id="chartVentasProductos"
                      style="
                        height: 250px; max-width: 100%; margin: 0px auto;
                      "
                    >
                    </div>
                  </div>
                </div>
              </div>
              <!-- End Grafica Ventas por Producto -->

              <!-- Grafica Ventas por Producto Conteo -->
              <div class="col-sm-12">
                <div class="card">
                  <div class="card-body">
                    <h4>Ventas por producto</h4>
                    <div id="chartVentasProductosConteo"
                      style="
                        height: 250px; max-width: 100%; margin: 0px auto;
                      "
                    >
                    </div>
                  </div>
                </div>
              </div>
              <!-- End Grafica Ventas por Producto Conteo -->

            </div>
            <!-- End Inner -->

          </div>
          <!-- End Container fluid  -->

          <?php require_once($Position.'footer.php'); ?>

        </div>
        <!-- ============================================================== -->
        <!-- End Page wrapper  -->
        <!-- ============================================================== -->
    </div>
    <!-- ============================================================== -->
    <!-- End Wrapper -->
    <!-- ============================================================== -->
    <!-- ============================================================== -->
    <!-- All Jquery -->
    <!-- ============================================================== -->

    <?php require_once($Position.'scripts.php'); ?>

    <script type="text/javascript" src="../dist/canvasjs.js"></script>

    <script>

      window.onload = function () {


        /*-- Chart Ventas Cargas --*/
        var chartVentas = new CanvasJS.Chart("chartVentasCargas", {

          title:{
            text: ""
          },
          axisX:{
          },
          axisY:{
            interval: 10000
          },
          data: [//array of dataSeries
            { //dataSeries object

              /*** Change type "column" to "bar", "area", "line" or "pie"***/
              type: "line",
              lineColor: "red",
              dataPoints: [
               <?php
                 //Fechas
                 foreach ($Dates AS $Date) {
               ?>
                 { label: "<?php echo $Date; ?>",  y: <?php echo number_format($VentaCarga[$Date],0,'',''); ?>  },
               <?php } ?>
               // { label: "a",  y: 1  },
               // { label: "b",  y: 2  },
               // { label: "c",  y: 3  },
               // { label: "d",  y: 4  }
             ]
           }
           ]
         });

        chartVentas.render();
        /*-- End Chart Ventas Cargas --*/

        /*-- Cart Ventas por Producto --*/
        var chartVentasProductos = new CanvasJS.Chart("chartVentasProductos", {

          title:{
            text: ""
          },
          toolTip:{
        		content: "{info}"
        	},
          axisX:{
          },
          axisY:{
            interval: 5000
          },
          data: [//array of dataSeries
            { //dataSeries object

             /*** Change type "column" to "bar", "area", "line" or "pie"***/
             type: "column",
             dataPoints: [
               <?php
                 //Fechas
                 mysqli_data_seek($VentasPro, 0);
                 while($Venta = mysqli_fetch_array($VentasPro)) {
               ?>
                 {
                   label: "<?php echo $Venta[ProductoClave]; ?>",
                   info: "\
                   <div><?php echo $Venta['Nombre'] ?></div>\
                   <div><strong>Clave:</strong> <?php echo $Venta['ProductoClave'] ?></div>\
                   <div><strong>Total:</strong> $ <?php echo number_format($Venta[Total],2,'.',','); ?></div>\
                   ",
                   y: <?php echo number_format($Venta[Total],0,'',''); ?>
                 },
               <?php } ?>
             ]
           }
           ]
         });

        chartVentasProductos.render();
        /*-- Cart Ventas por Producto --*/

        /*-- Cart Ventas por Producto Conteo --*/
        var chartVentasProductosConteo = new CanvasJS.Chart("chartVentasProductosConteo", {

          title:{
            text: ""
          },
          toolTip:{
        		content: "{info}"
        	},
          axisX:{
          },
          axisY:{
            interval: 10
          },
          data: [//array of dataSeries
            { //dataSeries object

             /*** Change type "column" to "bar", "area", "line" or "pie"***/
             type: "column",
             dataPoints: [
               <?php
                 //Fechas
                 mysqli_data_seek($VentasProCont, 0);
                 while($Ven = mysqli_fetch_array($VentasProCont)) {
               ?>
                 {
                  label: "<?php echo $Ven[ProductoClave]; ?>",
                  info: "\
                  <div><?php echo $Ven['Nombre'] ?></div>\
                  <div><strong>Clave:</strong> <?php echo $Ven['ProductoClave'] ?></div>\
                  <div><strong>Total:</strong> <?php echo number_format($Ven[Total],0,'',''); ?></div>\
                  ",
                  y: <?php echo number_format($Ven[Total],0,'',''); ?>
                },
               <?php } ?>
             ]
           }
           ]
         });

        chartVentasProductosConteo.render();
        /*-- Cart Ventas por Producto Conteo --*/

      }

    </script>

</body>

</html>
