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


include_once('db_config.php');

$Title = "Renumerar Asientos";
$Desde = $_SESSION["inicio"];
$Hasta = $_SESSION["fin"];
$Descripcion = $_SESSION["Descripcion_Ejercicio"];
$asientoNro  = isset($_POST['numero']) ? $_POST["numero"]  : "";
$Ejercicio = $_SESSION["ID_Ejercicio"];

$D = substr( $Desde, 6, 4 ) . "/" . substr( $Desde, 3, 2 ) . "/" . substr( $Desde, 0, 2 );
$H = substr( $Hasta, 6, 4 ) . "/" . substr( $Hasta, 3, 2 ) . "/" . substr( $Hasta, 0, 2 );

if( $asientoNro == "" ) $as = "1";
else $as = $asientoNro;

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:86%" >
    <div style="height: 15px;"></div>
<!--    <div class="col l9 m12 s12"> -->
      <div class="page-content">
 <?php
         echo "<div class='row'>";
         echo "<div class='input-field col s12 right-align  red-text text-darken-4' style='font-size:14pt; text-decoration: underline;'><b>" . $Descripcion . "</b></div>";;
         echo "</div>";
//         echo "<div style='height:20px;'></div>";

         echo "<div class='row'>";
         echo "<div class='input-field col s2'>";
         echo "<label for='desde'>Desde</label>";
         echo "<input id='desde' type='text' disabled class='datepicker' value='" . $Desde . "' onChange='onChange(this);'>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<label for='hasta'>Hasta</label>";
         echo "<input id='hasta' type='text' disabled class='datepicker' value='" . $Hasta . "' onChange='onChange(this);'>";
         echo "</div>";
//       echo "</div>";

         echo "<div class='input-field col s2'>";
         echo "<input id='numero' class=' right-align' type='text' value='" . $as . "' placeholder=' ' onChange='onChange(this);'>";
         echo "<label class='active' for='numero'>N&uacute;mero Inicial</label>";
         echo "</div>";

         echo "<div class='input-field col s2'  style='float: right;  margin-right:2%;'>";
         echo "<button id='go1' onclick='Renumerar();' class='btn waves-effect waves-light btn col s3' style='margin-top:15px; margin-left: 30px; width:170px;' name='action'>Renumerar</button>";
         echo "</div>";

         echo "<div class='input-field col s2' style='float: right;' >";
         echo "<button id='go2' onclick='Submit();' class='btn waves-effect waves-light btn col s3' style='margin-top:15px; margin-left: 30px; width:170px;' name='action'>Previsualizar</button>";

         echo "</div>";
         echo "</div>";
?>
      </div>  <!-- page-content --> 
<style>
th {
 font-weight: normal;
 color: black;
}

.totals {
  color:#0277bd;
  font-weight: bold;
  font-size: 1.1em;
  font-size: 1em;
}
.row {
  line-height: 0.8em; 
}
</style>
<?php

  $ActualAsiento = "";
  $first = true;
  echo "<table id='detail' class='highlight' style='color:grey; font-weight:normal;'><b>";
  echo "<thead>";
  echo "<tr>";
    echo "<div class='row data grey lighten-2' style='padding-top: 10px; padding-bottom:10px;'>";
    echo "<div class='col s1 right-align' style='border-radius:0; text-decoration:underline;'>Asiento</div>"; 
    echo "<div class='col s1' style='border-radius:0; width:7em; text-decoration:underline;'>Fecha</div>";
    echo "<div class='col s1' style='border-radius:0; width:7em; text-decoration:underline;'>Cuenta</div>";
    echo "<div class='col s4' style='border-radius:0; text-decoration:underline;'>Detalle</div>"; 
    echo "<div class='col s2 right-align' style='border-radius:0; text-decoration:underline;'>Debe</div>"; 
    echo "<div class='col s2 right-align' style='border-radius:0; text-decoration:underline;'>Haber</div>"; 
  echo "</div>";
  echo "</tr>"; 
  echo "</thead>"; 
  echo "<tbody /></b>"; 
  echo "</table>"; 

  if( $asientoNro == "" ) $norenumerar = true;
  else $norenumerar = false;

  $sql = "select asientos.fecha as _fecha, asientos.asiento as _asiento, movimientos.movimiento , movimientos.cuenta as c, cuentas.Denominacion as d, concepto, detalle, movimientos.debe as suma_debe, movimientos.haber as suma_haber from movimientos left join asientos on asientos.Id=movimientos.ID_Asiento left join cuentas on cuentas.cuenta=movimientos.Cuenta where movimientos.Empresa=1 and asientos.fecha is not null and asientos.fecha >='" . $D . "' and asientos.Fecha <='" . $H . "' and asientos.ejercicio='" . $Ejercicio . "' order by asientos.fecha, asientos.asiento, movimiento";
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {

    $xor = 0;
    $Total_Debe = $Total_Haber = 0;

    while($row = $result->fetch_assoc()) {

      $cuenta = $row["c"];
      $asiento = $row["_asiento"];

      if( $norenumerar == true ) $asientoNro = $asiento;

      if( $asiento != $ActualAsiento ) $new = true;
      else $new = false;
      $ActualAsiento = $asiento;

      $Debe = $row["suma_debe"];
      $Haber = $row["suma_haber"];
      $Fecha = $row["_fecha"];
      $Fecha = substr( $Fecha, 8, 2 ) . "-" . substr( $Fecha, 5, 2 ) . "-" . substr( $Fecha, 0, 4 ); 

      if( $new == true && $first == false) {
         echo "<div class='row data'>";
         echo "<div class='input-field col s1'></div>"; 
         echo "<div class='input-field col s1' style='width:12%;'></div>"; 
         echo "<div class='input-field col s1' style='width:10%;'></div>"; 
         echo "<div class='input-field col s4'></div>"; 
         echo "<div class='input-field col s2 right-align grey lighten-2' style='padding-top:10px; margin-top:0px; margin-bottom:0px; height:30px;'><b>";
         echo number_format ( $Total_Debe, 2, ',' ,  '.' ); 
         echo "</div>";
         echo "<div class='input-field col s2 right-align grey lighten-2' style='padding-top:10px; margin-top:0px; margin-bottom:0px; height:30px;'>";
         echo number_format ( $Total_Haber, 2, ',' ,  '.' );
         echo "</b></div>";
         echo "</div>";
         echo "<div class='input-field col s12' style='height:30px;'></div>";
         $Total_Debe = 0;
         $Total_Haber = 0;
         $asientoNro += 1;
      }      
      $first = false;

      $Total_Debe += $Debe;
      $Total_Haber += $Haber;
   
      if( $new == true ) {
         $xor = 1;
         echo "<div class='row data grey lighten-3'>";
         echo "<div class='input-field col s1 right-align'><b>" . $asientoNro . "</div>";
         echo "<div class='input-field col s1' style='width:12%;'>" . $Fecha . "</div>"; 
         echo "<div class='input-field col s1' style='width:10%;'></div>";
         echo "<div class='input-field col s4'>" . $row["concepto"] . "</div>";
         echo "<div class='input-field col s2 right-align'></div>";
         echo "<div class='input-field col s2 right-align'></div>";
         echo "</b></div>";
//        if( $xor ^= 1 ) 
//             echo "<div class='row data blue-grey lighten-5'>";
//        else echo "<div class='row data'>";
         echo "<div class='row data'>";

      }
      else {
//        if( $xor ^= 1 ) 
//           echo "<div class='row data blue-grey lighten-5'>";
//        else echo "<div class='row data'>";
         echo "<div class='row data'>";
      }

      echo "<div class='input-field col s1 right-align'></div>";
      echo "<div class='input-field col s1 right-align' style='width:12%;'></div>";
      echo "<div class='input-field col s1' style='width:10%;'>" . $row["c"] . "</div>";
      echo "<div class='input-field col s4'>" . $row["d"] . "</div>";
      echo "<div class='input-field col s2 right-align'>";
      if( $Debe > 0 ) echo number_format ( $Debe, 2, ',' ,  '.' ); 
      echo "</div>";
      echo "<div class='input-field col s2 right-align'>";
      if( $Haber > 0 ) echo number_format ( $Haber, 2, ',' ,  '.' );
      echo "</div>";
      echo "</div>";
    }

   echo "<div class='row data'></div>";
//   echo "<div style='height:100px;'></div>";
   }

   /* --- Total Final --- */
   echo "<div class='row data'>";
   echo "<div class='input-field col s1'></div>"; 
   echo "<div class='input-field col s1' style='width:12%;'></div>"; 
   echo "<div class='input-field col s1' style='width:10%;'></div>"; 
   echo "<div class='input-field col s4'></div>"; 
   echo "<div class='input-field col s2 right-align grey lighten-2' style='padding-top:10px; margin-top:0px; margin-bottom:0px; height:30px;'><b>";
   echo number_format ( $Total_Debe, 2, ',' ,  '.' ); 
   echo "</div>";
   echo "<div class='input-field col s2 right-align grey lighten-2' style='padding-top:10px; margin-top:0px; margin-bottom:0px; height:30px;'>";
   echo number_format ( $Total_Haber, 2, ',' ,  '.' );
   echo "</b></div>";
   echo "</div>";
   echo "<div class='input-field col s12' style='height:30px;'></div>";
   $Total_Debe = 0;
   $Total_Haber = 0;
   $asientoNro++;

   echo "<div class='input-field col s12' style='height:60px;'></div>";
   echo "</div>";            //--  container --> 

   mysqli_close($conn);
   echo "<ul id='dropdownData' class='dropdown-client' style='z-index:10; display:none;'>";
   echo "</ul>";
   echo "</div>";          // -- content -->

   echo "<div id='md1' class='modal' style='width:40%;'>"; 
   echo "<div class='modal-content'>";
       echo "<span style='font-size:14pt; text-align: center; width:100%;'>"; 
       echo "<p>Est&aacute; seguro de renumerar los asientos?</p></span>"; 
   echo "</div>"; 
   echo "<div class='modal-footer'>"; 
       echo "<a class='waves-effect waves-red btn-flat' onclick='Cancel();'>Cancelar</a>"; 
       echo "<a class='waves-effect waves-green btn-flat' id='md1_YesBtn' onclick='GO();'>Si</a>"; 
   echo "</div>"; 
   echo "</div>";

?>        

   <div id="loader" class="preloader-wrapper big">
   <div class="spinner-layer spinner-blue-only">
     <div class="circle-clipper left">
      <div class="circle"></div>
     </div><div class="gap-patch">
     <div class="circle"></div>
     </div><div class="circle-clipper right">
      <div class="circle"></div>
     </div>
   </div>
   </div>

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

    $('.modal').modal({dismissible: false, out_duration: 0, startingTop: '4%', endingTop:'10%' });
      jQuery(function($){
         $("#numero").mask("99999999",{placeholder:" ", autoclear: false});
      });
   });   

   // 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 Submit() {
      var d = $("#numero").val();
      post("contableReordenar.php", {numero:d});
   }

   function normalizeDate( fecha ) {
      var normal = fecha.substr(6,4) + fecha.substr(3,2) + fecha.substr(0,2);
      return normal;
   }

   function onChange(element) {
      var inicio = <?php echo(json_encode($Inicio)); ?>;
      var fin = <?php echo(json_encode($Fin)); ?>;
   
      console.log( element.value);
      switch( element.id ) {
         case "desde":
         case "hasta":
            if( normalizeDate( element.value ) < normalizeDate( inicio ) || normalizeDate( element.value ) > normalizeDate( fin ) ) {
               Materialize.toast('Las fechas deben estar comprendidas dentro del ejercicio activo', 3000, 'rounded') 
            }
            break;

         case "numero":
            console.log( element.value );
            break;

         default:
            break;
      }
   }

   function Renumerar() {
      $('#md1').modal('open');
//      post("reordenar.php", {numero:d});
   }

   function Cancel() {
      $('#md1').modal('close'); 
   }

   function GO() {
      var d = $("#numero").val();
      $('#md1').modal('close'); 

      console.log( d );
//      post("contableRenumerar.php", {numero:d});

//    $('#loader').addClass('active'); 
      $.ajax({
          type: "POST",
          url: "contableRenumerar.php",
          data: { 'numero': d },
              success: function(data){
                  console.log( data );
                  Materialize.toast('Finaliz&oacute; la renumeraci&oacute;n de asientos', 3000, 'rounded') 
                  var timeout = setTimeout(function() {
                     clearInterval(timeout); 
                  },3000);
              }
      });
   }

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

