<?php
session_start();
if( $_SESSION["user"] == "" || $_SESSION["passwd"] == "" || $_SESSION["admin"] == false ) {
   mysqli_close($conn);
   header("Location: index.php");
}


include_once('db_config.php');

$Title  = "Facturacion.";
$Year   = isset($_POST['dyear']) ? $_POST["dyear"]  : "";
$Month  = isset($_POST['dmonth']) ? $_POST['dmonth'] : "";
$hYear  = isset($_POST['hyear']) ? $_POST["hyear"]  : "";
$hMonth = isset($_POST['hmonth']) ? $_POST['hmonth'] : "";
$Empresa = isset($_POST['empresa']) ? $_POST['empresa'] : "";
$CodeEmpresa = isset($_POST['code_empresa']) ? $_POST['code_empresa'] : "";
$ret = isset($_POST['ret']) ? $_POST['ret'] : "1";
$Fecha  = "";
$YS2011 = "";
$YS2012 = "";
$YS2013 = "";
$YS2014 = "";
$YS2015 = "";
$YS2016 = "";
$YS2017 = "";
$YS2018 = "";
$YS2019 = "";
$YS2020 = "";
$YS2021 = "";
$YS2022 = "";

$hYS2011 = "";
$hYS2012 = "";
$hYS2013 = "";
$hYS2014 = "";
$hYS2015 = "";
$hYS2016 = "";
$hYS2017 = "";
$hYS2018 = "";
$hYS2019 = "";
$hYS2020 = "";
$hYS2021 = "";
$hYS2022 = "";

if( empty($Year) ) {        
   if( $_SESSION["dYear"] != "" ) $Year = $_SESSION["dYear"];
   else {
      $Year = date("Y");
   }
}

if( empty($Month) ) {       
   if( $_SESSION["dMonth"] != "" ) $Month = $_SESSION["dMonth"];
   else {
     $Month = date("n");
   }
}

if( empty($hYear) ) {        
   if( $_SESSION["hYear"] != "" ) $hYear = $_SESSION["hYear"];
   else {
      $hYear = date("Y");
   }
}

if( empty($hMonth) ) {       
//if( $hMonth == "" ) {       
   if( $_SESSION["hMonth"] != "" ) $hMonth = $_SESSION["hMonth"];
   else {
     $hMonth = date("n");
   }
}

//echo $hYear . "<br/>";
//echo $hMonth . "<br/>";


$_SESSION["dYear"]  = $Year;
$_SESSION["dMonth"] = $Month;
$_SESSION["hYear"]  = $hYear;
$_SESSION["hMonth"] = $hMonth;

$sm  = array("", "", "", "", "", "", "", "", "", "", "", "");
$hsm = array("", "", "", "", "", "", "", "", "", "", "", "");
$sm [$Month-1]  = "selected";
$hsm[$hMonth-1] = "selected";

if( $Year == "2011")  $YS2011 = "selected";
if( $Year == "2012")  $YS2012 = "selected";
if( $Year == "2013")  $YS2013 = "selected";
if( $Year == "2014")  $YS2014 = "selected";
if( $Year == "2015")  $YS2015 = "selected";
if( $Year == "2016")  $YS2016 = "selected";
if( $Year == "2017")  $YS2017 = "selected";
if( $Year == "2018")  $YS2018 = "selected";
if( $Year == "2019")  $YS2019 = "selected";
if( $Year == "2020")  $YS2020 = "selected";
if( $Year == "2021")  $YS2021 = "selected";
if( $Year == "2022")  $YS2022 = "selected";

if( $hYear == "2011")  $hYS2011 = "selected";
if( $hYear == "2012")  $hYS2012 = "selected";
if( $hYear == "2013")  $hYS2013 = "selected";
if( $hYear == "2014")  $hYS2014 = "selected";
if( $hYear == "2015")  $hYS2015 = "selected";
if( $hYear == "2016")  $hYS2016 = "selected";
if( $hYear == "2017")  $hYS2017 = "selected";
if( $hYear == "2018")  $hYS2018 = "selected";
if( $hYear == "2019")  $hYS2019 = "selected";
if( $hYear == "2020")  $hYS2020 = "selected";
if( $hYear == "2021")  $hYS2021 = "selected";
if( $hYear == "2022")  $hYS2022 = "selected";

include 'contableHeader.php'; 
?>
  <link type="text/css" rel="stylesheet" href="styles/styles_100.css"  media="screen,projection"/> 
  <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <div id="content">
  <div class="container" style="width:90%" >
    <div style="height: 15px;"></div>
    <div class="col l9 m12 s12">
      <div class="page-content">
        <div style="height:20px;"></div>


        <form id="iva" action="contableFacturacion.php" method="post"> 
        <div class="row">
         <div class="input-field col s2" style='width:15%; padding-top:10px;'>
            <select name="dmonth">
 <?php
            echo "<option value='' disabled>Mes</option>";        
                echo "<option value='1' " . $sm[0] . ">Enero</option>";
                echo "<option value='2' " . $sm[1] . ">Febrero</option>";
                echo "<option value='3' " . $sm[2] . ">Marzo</option>";
                echo "<option value='4' " . $sm[3] . ">Abril</option>";
                echo "<option value='5' " . $sm[4] . ">Mayo</option>";
                echo "<option value='6' " . $sm[5] . ">Junio</option>";
                echo "<option value='7' " . $sm[6] . ">Julio</option>";
                echo "<option value='8' " . $sm[7] . ">Agosto</option>";
                echo "<option value='9' " . $sm[8] . ">Septiembre</option>";
                echo "<option value='10' " . $sm[9] . ">Octubre</option>";
                echo "<option value='11' " . $sm[10] . ">Noviembre</option>";
                echo "<option value='12' " . $sm[11] . ">Diciembre</option>";
?>                
            </select>
            <label>Desde Mes</label>
         </div>      
         <div class="input-field col s1" style="width:10%; padding-top:10px;">
              <select  name="dyear">
              <option value="" disabled selected>A&ntilde;o</option>
<?php
                echo "<option value='2022' " . $YS2022 . ">2022</option>";
                echo "<option value='2021' " . $YS2021 . ">2021</option>";
                echo "<option value='2020' " . $YS2020 . ">2020</option>";
                echo "<option value='2011' " . $YS2011 . ">2011</option>";
                echo "<option value='2012' " . $YS2012 . ">2012</option>";
                echo "<option value='2013' " . $YS2013 . ">2013</option>";
                echo "<option value='2014' " . $YS2014 . ">2014</option>";
                echo "<option value='2015' " . $YS2015 . ">2015</option>";
                echo "<option value='2016' " . $YS2016 . ">2016</option>";
                echo "<option value='2017' " . $YS2017 . ">2017</option>";
                echo "<option value='2018' " . $YS2018 . ">2018</option>";
                echo "<option value='2019' " . $YS2019 . ">2019</option>";
?>              
              </select>
              <label>Desde A&ntilde;o</label>
         </div>    
 <?php
         echo "<div class='row'>";
         echo "<div class='input-field col s2' style='width:15%; padding-top:10px;'>"; 
            echo "<select name='hmonth'>"; 
            echo "<option value='' disabled>Mes</option>";        
                echo "<option value='1' " . $hsm[0] . ">Enero</option>";
                echo "<option value='2' " . $hsm[1] . ">Febrero</option>";
                echo "<option value='3' " . $hsm[2] . ">Marzo</option>";
                echo "<option value='4' " . $hsm[3] . ">Abril</option>";
                echo "<option value='5' " . $hsm[4] . ">Mayo</option>";
                echo "<option value='6' " . $hsm[5] . ">Junio</option>";
                echo "<option value='7' " . $hsm[6] . ">Julio</option>";
                echo "<option value='8' " . $hsm[7] . ">Agosto</option>";
                echo "<option value='9' " . $hsm[8] . ">Septiembre</option>";
                echo "<option value='10' " . $hsm[9] . ">Octubre</option>";
                echo "<option value='11' " . $hsm[10] . ">Noviembre</option>";
                echo "<option value='12' " . $hsm[11] . ">Diciembre</option>";
            echo "</select>"; 
            echo "<label>Hasta Mes</label>"; 
         echo "</div>";       
         echo "<div class='input-field col s1' style='width:10%; padding-top:10px;'>";
              echo "<select  name='hyear'>"; 
              echo "<option value='' disabled selected>A&ntilde;o</option>";
                echo "<option value='2022' " . $hYS2022 . ">2021</option>";
                echo "<option value='2021' " . $hYS2021 . ">2021</option>";
                echo "<option value='2020' " . $hYS2020 . ">2020</option>";
                echo "<option value='2011' " . $hYS2011 . ">2011</option>";
                echo "<option value='2012' " . $hYS2012 . ">2012</option>";
                echo "<option value='2013' " . $hYS2013 . ">2013</option>";
                echo "<option value='2014' " . $hYS2014 . ">2014</option>";
                echo "<option value='2015' " . $hYS2015 . ">2015</option>";
                echo "<option value='2016' " . $hYS2016 . ">2016</option>";
                echo "<option value='2017' " . $hYS2017 . ">2017</option>";
                echo "<option value='2018' " . $hYS2018 . ">2018</option>";
                echo "<option value='2019' " . $hYS2019 . ">2019</option>";
              echo "</select>"; 
              echo "<label>Hasta A&ntilde;o</label>"; 
         echo "</div>";     

         echo "<div class='input-field col s4' style='width:38%; padding-bottom:20px; margin-bottom:20px;'>";
         echo "<input id='empresa' name='empresa' type='text' value='" . $Empresa . "'>";
         echo "<label class='active' for='empresa'>Empresa</label>";
         echo "<input type='hidden' name='code_empresa' id='code_empresa' value='" . $CodeEmpresa . "'>"; 
         echo "</div>";
         echo "<button class='btn waves-effect waves-light btn col s1' style='margin-top:5px; margin-left:20px;' type='submit' name='action' >Go!</button>";
        echo "</row>";
        echo "</form>";
?>              

        <div style="height:70px;"></div>
      </div>  <!-- page-content --> 
<style>
th {
 font-weight: normal;
 color: black;
}
</style>
<?php
   $xor = 0;
   echo "<table id='detail' class='highlight' style='color:grey; font-weight:normal;'>";
   echo "<thead>";
   echo "<tr>";
     echo "<div class='row data grey lighten-2' style='padding-top:10px; padding-bottom:10px;'>";
     echo "<div class='col s1' style='border-radius:0; text-decoration:underline; width:9%;'>Fecha</div>";
     echo "<div class='col s3' style='border-radius:0; text-decoration:underline; width:12%;'>N&uacute;mero</div>";
     echo "<div class='col s3' style='border-radius:0; text-decoration:underline; width:27%; overflow:hidden;'>Nombre</div>";
     echo "<div class='col s1' style='border-radius:0; text-decoration:underline; width:12%;'>CUIT</div>";
     echo "<div class='col s2 right-align' style='border-radius:0; text-decoration:underline; width:10%;'>Imponible</div>";
     echo "<div class='col s2 right-align' style='border-radius:0; text-decoration:underline; width:10%;'>IIBB</div>";
     echo "<div class='col s2 right-align' style='border-radius:0; text-decoration:underline; width:10%;'>Ganancias</div>";
     echo "<div class='col s2 right-align' style='border-radius:0; text-decoration:underline; width:10%;'>IVA</div>";
   echo "</div>";
   echo "</tr>"; 
   echo "</thead>"; 
   echo "<tbody />"; 
   echo "</table>"; 

//   echo $Empresa . "<br/>";
//   echo $CodeEmpresa . "<br/>";
   $fecha1 = sprintf("%d%02d", $Year, $Month);
   $fecha2 = sprintf("%d%02d", $hYear, $hMonth);
   $sql = "select concat(year(fecha),LPAD(month(fecha),2,'0')), fecha, numero, empresas.nombre, cuit, (iva_105+iva_21+iva_27+iva_mt) as imponible, retenciones, Retenciones_Ganancias as ret_gan, retenciones_iva as ret_iva from comprobantes left join empresas on empresas.id = comprobantes.cliente where concat(year(fecha),LPAD(month(fecha),2,'0')) >= '"  . $fecha1 . "' and concat(year(fecha),LPAD(month(fecha),2,'0')) <= '"  . $fecha2 . "' and comprobantes.Borrado=0 and comprobantes.cliente=" . $CodeEmpresa . " order by fecha";
//      echo $sql;
   $result = $conn->query($sql);
   if ($result->num_rows > 0) {

      $TI = $TIB = $TGAN = $TIVA = 0;
      while($row = $result->fetch_assoc()) {

//         if( $row["retenciones"] > 0 && ( $ret == 1 || $ret == 2 ) ||
//             $row["ret_gan"] > 0 && ( $ret == 1 || $ret == 3 ) ||
//             $row["ret_iva"] > 0 && ( $ret == 1 || $ret == 4 )  ) {


            $date = date_create($row["fecha"]);
            $fecha = date_format($date, 'd-m-Y');
            
            $TI += $row["imponible"];   
            $TIB += $row["retenciones"];   
            $TGAN += $row["ret_gan"];   
            $TIVA += $row["ret_iva"];   
            if( $xor ^= 1 ) 
               echo "<div class='row data blue-grey lighten-5'>";
            else echo "<div class='row data'>";
            echo "<div class='input-field col s2' style='width:9%;'>" . $fecha . "</div>";
            echo "<div class='input-field col s1' style='width:12%;'>" . $row["numero"] . "</div>";
            echo "<div class='input-field col s3' style='width:27%;'>" . $row["nombre"] . "</div>";
            echo "<div class='input-field col s1' style='width:12%;'>" . $row["cuit"] . "</div>";
            
            echo "<div class='input-field col s2 right-align' style='width:10%;'>" . number_format( $row["imponible"], 2, ',' ,  '.' ) . "</div>";
            if( $row["retenciones"] > 0 && ( $ret == 1 || $ret == 2 ) ) 
               echo "<div class='input-field col s2 right-align' style='width:10%;'>" . number_format( $row["retenciones"], 2, ',' ,  '.' ) . "</div>";
            else echo "<div class='input-field col s2 right-align' style='width:10%;'></div>";
            
            if( $row["ret_gan"] > 0  && ( $ret == 1 || $ret == 3 ) ) 
               echo "<div class='input-field col s2 right-align' style='width:10%;'>" . number_format( $row["ret_gan"], 2, ',' ,  '.' ) . "</div>";
            else echo "<div class='input-field col s2 right-align' style='width:10%;'></div>";
            
            if( $row["ret_iva"] > 0  && ( $ret == 1 || $ret == 4 ) ) 
               echo "<div class='input-field col s2 right-align' style='width:10%;'>" . number_format( $row["ret_iva"], 2, ',' ,  '.' ) . "</div>";
            else echo "<div class='input-field col s2 right-align' style='width:10%;'></div>";
            echo "</div>";
//         }
      }
   }

   echo "<div class='row data grey lighten-2'><b>";
   echo "<div class='input-field col s1 right-align' style='width:60%;'></div>";
   echo "<div class='input-field col s2 right-align' style='width:10%; margin-bottom:10px;'>" . number_format( $TI, 2, ',' ,  '.' ) . "</div>";
   echo "<div class='input-field col s2 right-align' style='width:10%;'>" . number_format( $TIB, 2, ',' ,  '.' ) . "</div>";
   echo "<div class='input-field col s2 right-align' style='width:10%;'>" . number_format( $TGAN, 2, ',' ,  '.' ) . "</div>";
   echo "<div class='input-field col s2 right-align' style='width:10%;'>" . number_format( $TIVA, 2, ',' ,  '.' ) . "</div>";
   echo "</b></div>";

    mysqli_close($conn);
   echo "<div id='dropEmpresa' style='float: right;'>";
   echo "<ul id='dropdownEmpresa' class='dropdown-client' style='z-index:10; display:none;'>";
   echo "</ul>"; 
   echo "</div>";
?>   
     
   </div>   <!-- column --> 
   <div style="height:100px;"></div>
   </div>            <!-- container --> 
   </div>            <!-- content -->
   <script type="text/javascript" src="js/jquery.min.js"></script>
   <script type="text/javascript" src="js/jquery.form.js"></script> 
   <script type="text/javascript" src="materialize/1.0.0/js/materialize.min.js"></script>
   <script src="js/numeral.min.js"></script>
   <script src="js/jquery.maskedinput.min.js" type="text/javascript"></script>
<script>

   var keyTimeout;

   $(document).ready(function() {

      $('.dropdown-trigger').dropdown({
         "hover": true,
         "constrainWidth": false,
         "coverTrigger": false
      });
      $('select').formSelect();

      $('.datepicker').datepicker({
         selectMonths: true, // Creates a dropdown to control month
         selectYears: 10, // Creates a dropdown of 15 years to control year
         monthsFull: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
         monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
         weekdaysFull: [ 'Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado' ],
         weekdaysShort: [ 'Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab' ],
         weekdaysLetter: [ 'D', 'L', 'M', 'M', 'J', 'V', 'S' ],
         today: 'Hoy',
         clear: 'Borrar',
         close: 'Cerrar',
         format: 'dd-mm-yyyy',
         formatSubmit: 'yyyy-mm-dd'
       });

      $('#month').on('change', function() {
         Month = this.value;
         console.log( this.value )
      });   
      $('#year').on('change', function() {
         Year = this.value;
         console.log( this.value )
      });   


      $('#empresa').on('keyup', function() {

           var cliente  = this.value;
           if( keyTimeout != undefined ) clearInterval(keyTimeout); 
           keyTimeout = setTimeout(function() {
              clearInterval(keyTimeout); 
              if( cliente.length >= 0 ) {
                 populateEmpresas(cliente);
              }
           },2000);
      });   

   });   

   // Post to the provided URL with the specified parameters.
   function post(path, parameters) {
      var form = $('<form></form>');

       form.attr("method", "post");
       form.attr("action", path);

       $.each(parameters, function(key, value) {
           var field = $('<input></input>');
           field.attr("type", "hidden");
           field.attr("name", key);
           field.attr("value", value);
           form.append(field);
       });

       // The form needs to be a part of the document in
       // order for us to be able to submit it.
       $(document.body).append(form);
      form.submit();
   };

   function populateEmpresas(key) {
      $('#dropdownEmpresa').empty();
      $.ajax({
          type: "POST",
          url: "listEmpresas.php",
          data: { 'key': key  },
              success: function(data){
                  var msg = JSON.parse(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#dropdownEmpresa").append($("<li></li>").val(msg[i].option).html(msg[i].name));
                  }

                  if( msg.length > 0 ) {
                     showEmpresas();
                     $( "#dropdownEmpresa" ).focus();
                     searchflag = 2;
                  }
                  else {
                     Materialize.toast('No hay empresas que comiencen con ese nombre', 3000, 'rounded') 
                     hideEmpresa();
                     $( "#empresa" ).focus();
                  }
              }
      });
   }

   function showEmpresas() {
      $( "#dropdownEmpresa" ).addClass( "active" );
      $( "#dropdownEmpresa" ).css( "opacity", 1 );
      $( "#dropdownEmpresa" ).css( 'display', 'inline-block' );
      $( "#dropdownEmpresa" ).css( "width", "40%" );
      $( "#dropdownEmpresa" ).css( "height", "15%" );
      $( "#dropdownEmpresa" ).css( "height", window.innerHeight - 200 );
      $( "#dropdownEmpresa" ).css( "color", "#009688" );
      $( "#dropdownEmpresa" ).css( "position", "absolute" );
      $( "#dropdownEmpresa" ).css( "vertical-align", "top" );

      var size = $(document).scrollTop();
      $( "#dropdownEmpresa" ).css( "top", "90" );
      $( "#dropdownEmpresa" ).css( "left", "51%" );
      $( "#dropdownEmpresa" ).css( 'margin', '0 0 15px 0' );
      $( "#dropdownEmpresa" ).css( 'line-height', '3em' );
      $( "#empresa" ).removeClass( "invalid" );

      $('#dropdownEmpresa li').on('click', function() {

            found = false;
            var key = $(this).val();
            var fieldname = "";
            var btnname = "";

            var name = $(this).html(); 
            $( "#empresa" ).val(name); 

            $.ajax({
                type: "POST",
                url: "getEmpresa.php",
                data: { 'key': key  },
                    success: function(data){
                       var msg = JSON.parse(data);
                       
                       $('#code_empresa').val(msg.id); 
                       $('#empresa').val(msg.nombre); 
                       console.log( msg.id );
                       console.log( msg.nombre );
                       found = true;
                       /*
                       if( recordChange() == true ) {
                          $( "#updateBtn_" + $('#id').val() ).removeClass( "hide" )
                          $( "#updateBtn_" + $('#id').val() ).removeClass( "disabled" )
                       }
                       $('#cancel').css("display", "" );
                       */
                     }
           });
           hideEmpresas();
      });   
   }

   function hideEmpresas() {
      $( "#dropdownEmpresa" ).removeClass( "active" );
      $( "#dropdownEmpresa" ).css( "opacity", 0 );
      $( "#dropdownEmpresa" ).css( 'display', 'none' );
   }



</script>
</body>
</html>

