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

$_SESSION["module"] = "Plan de Cuentas.";


include_once('db_config.php');
ini_set('max_execution_time', 120);

$Title = "Plan de Cuentas";
$admin = false;
include 'contableHeader.php'; 
   echo "<link type='text/css' rel='stylesheet' href='styles/styles_100.css'  media='screen,projection'/>";
   echo "<link href='http://fonts.googleapis.com/icon?family=Material+Icons' rel='stylesheet'>"; 
   echo "<div id='content'>"; 
   echo "<div class='container' style='width:50%' >"; 
   echo "<div style='height: 30px;'></div>"; 
   echo "<div class='col l9 m12 s12' style='padding:2px;'>"; 
      echo "<div class='page-content'>"; 
      echo "</div>"; 
      echo "<div class='col s12 m4 l4' style='padding:2px;'>";
      echo "<div class='card white' style='margin:0px;'>";
      echo "<div class='card-content black-text'>";
      echo "<a onclick='newRecord(this);' class='btn-floating btn-large waves-effect waves-light red' style='float:right; margin-top:20px;'><i class='material-icons'>add</i></a>";

      echo "<div class='row data' style='margin-left:30px; margin-right:30px; margin-top:50px;'>";
         echo "<div class='row'>";
         echo "<div class='input-field col s3'>";
             echo "<input id='cuenta' type='text' class='validate' >";
             echo "<label for='cuenta'>Cuenta</label>";
         echo "</div>";
         echo "</div>";
         echo "<div class='row'>";
         echo "<div class='input-field col s11'>";
             echo "<input id='denominacion' type='text' disabled  value='' onChange='onChange(this);'>";
             echo "<label for='denominacion'>Denominaci&oacute;n</label>";
         echo "</div>";
         echo "</div>";

         echo "<div class='row'>";
         echo "<div class='input-field col s3'>";
             echo "<label><span style='color:red; font-weight:bold;'>SUMARIZA EN CUENTA</span></label>";
         echo "</div>";
         echo "<div class='input-field col s3'>";
             echo "<input id='sumariza' type='checkbox' disabled  class='filled-in' checked='checked' onChange='onChange(this);'>";
             echo "<label for='sumariza' ></label>";
         echo "</div>";
         echo "</div>";

         echo "<div class='row'>";
         echo "<div style='height:40px;'></div>";
         echo "<div class='input-field col s3'>";
             echo "<input id='cuentasuma' type='text' disabled  value='' onChange='onChange(this);'>";
             echo "<label for='cuentasuma'>Cuenta</label>";
         echo "</div>";
         echo "<div class='input-field col s8'>";
             echo "<input id='descripcion' type='text' disabled value='' onChange='onChange(this);' style='color:blue;'>";
             echo "<label for='descripcion'>Descripci&oacute;n</label>";
         echo "</div>";
         echo "</div>";

         echo "<div class='row'>";
         echo "<div class='input-field col s3'>";
             echo "<label><span style='color:red; font-weight:bold;'>RECIBE ASIENTOS</span></label>";
         echo "</div>";
         echo "<div class='input-field col s3'>";
             echo "<input id='recibe' type='checkbox' disabled class='filled-in' checked='checked' onChange='onChange(this);'>";
             echo "<label for='recibe'></label>";
         echo "</div>";
         echo "</div>";

         echo "<div class='row'>";
         echo "<div style='height:40px;'></div>";
         echo "<div class='input-field col s3'>";
            echo "<select id='columna' disabled onChange='onChange(this);'>";
            echo "<option value='0' disabled selected>Numero de columna</option>";
            echo "<option value='1'>1</option>";
            echo "<option value='2'>2</option>";
            echo "<option value='3'>3</option>";
            echo "<option value='4'>4</option>";
            echo "<option value='5'>5</option>";
            echo "<option value='6'>6</option>";
            echo "</select>";
            echo "<label>Columna de Impresion</label>";
         echo "</div>";

         echo "<div class='input-field col s3'>";
            echo "<select id='columnares' disabled onChange='onChange(this);'>";
            echo "<option value='0' disabled selected>Columna Resumen</option>";
            echo "<option value='1'>Activo</option>";
            echo "<option value='2'>Pasivo & Patrimonio Neto</option>";
            echo "<option value='3'>Perdidas</option>";
            echo "<option value='4'>Ganancias</option>";
            echo "</select>";
            echo "<label>Columna Resumen</label>";
         echo "</div>";

         echo "<div class='row'>";
            echo "<div class='input-field col s3' style='margin-left:20px;'>";
                echo "<label>";
                echo "<input id='salto' type='checkbox' disabled class='filled-in' onChange='onChange(this);'>";
                echo "<span>Salto de Hoja</span>";
                echo "</label>";
            echo "</div>";
         echo "</div>";

         echo "<div class='row'>";
         echo "<div style='height:15px;'></div>";
         echo "<div class='input-field col s11' style='margin-left:15px;'>";
            echo "<textarea id='observaciones' disabled class='materialize-textarea' onChange='onChange(this);'> </textarea>";
            echo "<label for='observaciones'>Observaciones</label>";
         echo "</div>";
         echo "</div>";
         echo "<div class='input-field col s11' style='margin-top: 0;'>";
            echo "<a id='upd'    onclick='Update(this);' class='waves-effect waves-light btn green'   style='width:120px; float:right; margin-top: 0; margin-right: 0px; display:none;'>Actualizar</a>";
            echo "<a id='cancel' onclick='Cancel(this);' class='waves-effect waves-light btn'         style='width:120px; float:right; margin-top: 0; display:none; margin-right: 10px;'>Cancelar</a>";
            echo "<a id='delete' onclick='Delete(this);' class='waves-effect waves-light btn red'     style='width:120px; color:white !important; float:right; margin-top:0; margin-right:10px; display:none;'>Borrar</a>";

//            echo "<a id='delete' onclick='Delete(this);' class='waves-effect waves-light btn blue-grey darken-2 text-grey text-darken-1' style='float:right; margin-top: 0;display:none;'><i class='material-icons right'>delete</i>Borrar</a>";
//            echo "<a id='cancel' onclick='Cancel(this);' class='waves-effect waves-light btn blue-grey darken-2 text-grey text-darken-1' style='float:right; margin-top: 0;display:none; margin-right: 10px;'><i class='material-icons right'>cancel</i>Cancelar</a>";
//          echo "<a id='upd' onclick='Update(this);' class='waves-effect waves-light btn hide blue-grey darken-2 text-grey text-darken-1' style='float:right; margin-top: 0; margin-right: 10px;'><i class='material-icons right'>cached</i>Actualizar</a>";


         echo "</div>";
         echo "<div class='input-field col s10' style='height: 5px;'>";
            echo "<input type='hidden' id='id' value=''>"; 
         echo "</div>";
      echo "</div>";
   echo "</div>";
   echo "</div>";
   echo "</div>";
   echo "</div>";
   echo "<ul id='dropdownData' class='dropdown-client' style='z-index:10; display:none;'>"; 
   echo "</ul>"; 
   echo "</div>"; 
   echo "</div>";
?>          
<style>
.dropdown-client {
   background-color: white;
   opacity: 1;
   overflow-y: auto;
   border-bottom: 1px solid #d0d0d0;
   box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}
ul.dropdown-client li {
   line-height:3em;
   height:3em;
   vertical-align: middle;
   color: #009688;
   color: black;
   min-height: 3em;
   text-align: left;
   padding: 0px 16px;
}
ul.dropdown-client li:hover {
 background-color:#90a4ae;
 background-color:#16a2d6;
 color: white;
}
</style>
  <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;
   var newflag = false;
   var searchflag = 0;
   var found = false;

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

       // Busqueda de dropdown de cliente
       $('#cuenta').on('keyup', function() {
            if( newflag == false) {
               var cuenta = this.value;
               var id = this;
               if( keyTimeout != undefined ) clearInterval(keyTimeout); 
               keyTimeout = setTimeout(function() {
                  clearInterval(keyTimeout); 
                  if( cuenta.length > 0 ) {
                     populateCuentas(cuenta, id);
                  }
               },1500);
            }
       });   

       // Busqueda de dropdown de cliente
       $('#cuentasuma').on('keyup', function() {
           
            var cuenta = this.value;
            var id = this;
            if( keyTimeout != undefined ) clearInterval(keyTimeout); 
            keyTimeout = setTimeout(function() {
               clearInterval(keyTimeout); 
               if( cuenta.length > 0 ) {
                  populateCuentas(cuenta,id);
               }
            },1500);
       });   

      jQuery(function($){
         $("#cuenta").mask("99999999",{placeholder:"", autoclear: false});
         $("#cuentasuma").mask("99999999",{placeholder:"", autoclear: false});
      });

   });   

   function Cancel(e) {

      console.log( "Cancel!" );
      newflag = false;
      searchflag = 0;

      $('#upd').css("display", "none" );
      $('#cancel').css("display", "none" );
      $('#delete').css("display", "none" );
      $('#cuenta').val(""); 
      $('#denominacion').val(""); 
      $('#descripcion').val(""); 
      $('#sumariza').val(""); 
      $('#cuentasuma').val(""); 
      $('#recibe').val(""); 
      $('#salto').val(""); 
      $('#observaciones').val(""); 

      $("select[id$='columna'] option[value=0]").attr("selected", true);
      $("select[id$='columnares'] option[value=0]").attr("selected", true);

      $('#denominacion').attr('disabled','disabled'); 
      $('#sumariza').attr('disabled','disabled'); 
      $('#cuentasuma').attr('disabled','disabled'); 
      $('#recibe').attr('disabled','disabled'); 
      $('#salto').attr('disabled','disabled'); 
      $('#observaciones').attr('disabled','disabled'); 
      $('#columna').attr('disabled','disabled'); 
      $('#columnares').attr('disabled','disabled'); 

      $('#columna').formSelect();
      $('#columnares').formSelect();
      $('.input-field label').removeClass('active');
   }

   function newRecord(e) {

      hideClients();
      newflag = true;
      $('#cancel').css("display", "" );

      $('#cuenta').val(""); 
      $('#denominacion').val(""); 
      $('#sumariza').val(""); 
      $('#cuentasuma').val(""); 
      $('#recibe').val(""); 
      $('#salto').removeAttr('checked');  
      $('#observaciones').val(""); 
      $("select[id$='columna'] option[value=0]").attr("selected", true);
      $("select[id$='columnares'] option[value=0]").attr("selected", true);

      $('#denominacion').removeAttr('disabled'); 
      $('#descripcion').val(""); 
      $('#sumariza').removeAttr('disabled'); 
      $('#cuentasuma').removeAttr('disabled'); 
      $('#recibe').removeAttr('disabled'); 
      $('#salto').removeAttr('disabled'); 
      $('#observaciones').removeAttr('disabled'); 
      $('#columna').removeAttr('disabled'); 
      $('#columnares').removeAttr('disabled'); 

      $('#columna').formSelect();
      $('#columnares').formSelect();
      $('.input-field label').removeClass('active');

      $( "#upd" ).removeClass( "hide" )
      $( "#upd" ).removeClass( "disabled" )
      $('#upd').css("display", "block" );

   }



   // 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 Delete(e) {

      var id = $('#id').val();

      $.ajax({
          type: "POST",
          url: "contableUpdateCuenta.php",
          data: {'id': id, 'mode': 'delete' },
              success: function(data){
                              var msg = JSON.parse(data);
                              if( msg.status.length >= 0 ) {
                                 console.log( msg.status );
                              }    
                              Cancel(e);
                       }
      });
   }

   function Update(e) {

      var id = "";
      var mode = "update";

      if( newflag == true ) id ="0";      
      else  id = $('#cuenta').val();  

      var cuenta = $('#cuenta').val(); 
      var denominacion = $('#denominacion').val(); 
      var cuentasuma = $('#cuentasuma').val(); 
      var columna = $('#columna').val(); 
      var columnares = $('#columnares').val(); 
      var observa = $('#observaciones').val(); 

      var sumariza = $("#sumariza").is(":checked")
      var recibe = $("#recibe").is(":checked")
      var salto = $("#salto").is(":checked")

      console.log( sumariza );
      console.log( recibe );
      console.log( salto );

      if( sumariza == true ) sumariza = "1";
      else sumariza = "0";

      if( recibe == true ) recibe = "1";
      else recibe = "0";

      if( salto == true ) salto = "1";
      else salto = "0";

      if( newflag == false && found == false ) {
         Materialize.toast("Seleccione una cuenta", 3000, 'rounded') 
         return;
      }

      if( newflag == true ) {

         mode = "append";
         var msg = "";
         if( cuenta.length <= 0 ) {
            msg = 'Ingrese el codigo de la cuenta';
            Materialize.toast(msg, 3000, 'rounded') 
            return;
         }
         else {
            if( denominacion.length <= 0 ) {
               msg = 'Ingrese la denominacion de la cuenta';
               Materialize.toast(msg, 3000, 'rounded') 
               return;
            }
         }
      }


      $.ajax({
          type: "POST",
          url: "contableUpdateCuenta.php",
          data: {cuenta: cuenta, denominacion: denominacion, cuentasuma: cuentasuma, columna: columna, columnares: columnares, sumariza: sumariza, recibe: recibe, salto: salto, observaciones: observa, mode: mode },
              success: function(data){
                              var msg = JSON.parse(data);
                              if( msg.status.length >= 0 ) {
                                 console.log( msg.status );
                                 Cancel(e);
                              }    
                       }
      });
//      post("contableUpdateCuenta.php", {cuenta: cuenta, denominacion: denominacion, cuentasuma: cuentasuma, columna: columna, columnares: columnares, sumariza: sumariza, recibe: recibe, salto: salto, observaciones: observa, mode: mode }); 
   }

   function showClients(id) {

      $( "#dropdownData" ).addClass( "active" );
      $( "#dropdownData" ).css( "opacity", 1 );
      $( "#dropdownData" ).css( 'display', 'block' );
      $( "#dropdownData" ).css( "width", "30%" );
      $( "#dropdownData" ).css( "height", "30%" );
      $( "#dropdownData" ).css( "color", "#009688" );
      $( "#dropdownData" ).css( "position", "absolute" );
      $( "#dropdownData" ).css( "left", "20%" );
      $( "#dropdownData" ).css( "left", "520" );
      $( "#dropdownData" ).css( 'margin', '0 0 15px 0' );
      $( "#dropdownData" ).css( 'line-height', '3em' );
      $( "#empresa" ).removeClass( "invalid" );

      if( id == "cuenta" )
         $( "#dropdownData" ).css( "top", "250" );
      else $( "#dropdownData" ).css( "top", "445" );


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

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

            if( id == "cuenta" ) 
               $('#cuenta').val(key); 
            else $('#cuentasuma').val(key); 

//          $('#cuenta').val($(this).val()); 
//          $('#cuenta').val($(this).html()); 
            console.log($(this).val());

            $.ajax({
                type: "POST",
                url: "getCuenta.php",
                data: { 'key': key  },
                    success: function(data){
                       var msg = JSON.parse(data);
  
                       if( id == "cuenta" ) {
                           console.log("showClients: " + id);
                           $('#cuenta').val(msg.cuenta); 
                           $('#denominacion').val(msg.denominacion); 

                           if( msg.sumariza == "1" ) $('#sumariza').attr('checked', 'checked');  
                           else $('#sumariza').removeAttr('checked');   

                           if( msg.asientos == "1" ) $('#recibe').attr('checked', 'checked'); 
                           else $('#recibe').removeAttr('checked');   

                           if( msg.salto == "1" ) $('#salto').attr('checked', 'checked');  
                           else $('#salto').removeAttr('checked');  
                           
                           $('#sumariza').val(msg.sumariza); 
                           $("select[id$='columna'] option[value=" + msg.columna + "]").attr("selected", true);
                           $("select[id$='columnares'] option[value=" + msg.columna_sumassaldos + "]").attr("selected", true);
                           $('#cuentasuma').val(msg.cuenta_sumarizacion); 
                           $('#observaciones').val(msg.observa); 
                           $('#descripcion').val(msg.descripcion); 

                           $('#denominacion').removeAttr('disabled'); 
                           $('#sumariza').removeAttr('disabled'); 
                           $('#columna').removeAttr('disabled'); 
                           $('#columnares').removeAttr('disabled'); 
                           $('#cuentasuma').removeAttr('disabled'); 
                           $('#recibe').removeAttr('disabled'); 
                           $('#salto').removeAttr('disabled'); 
                           $('#observaciones').removeAttr('disabled'); 
                           $('#columna').formSelect();
                           $('#columnares').formSelect();

                           $('.input-field label').addClass('active');

                           if( searchflag == 1 ) {
                             $( "#cuenta" ).focus();
                           }
                           found = true;

                           $('#cancel').css("display", "" );
                           $('#upd').css("display", "" );

                           if( newflag == false ) $('#delete').css("display", "" );
                        }
                        else {
                           console.log("showClients: " + id);
                           $('#cuentasuma').val(msg.cuenta); 
                           $('#descripcion').val(msg.denominacion); 
                        }
                     }
           });
           hideClients();
      });   
   }

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

   function populateCuentas(key,el) {
      
      console.log( "Populate: " + el.id + " - " + key );
      key = $.trim(key);
      $('#dropdownData').empty();
      $.ajax({
          type: "POST",
          url: "recvCuentas.php",
          data: { 'key': key  },
              success: function(data){
                  var msg = JSON.parse(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#dropdownData").append($("<li></li>").val(msg[i].option).html(msg[i].option + " " + msg[i].denominacion));
                  }
                  if( msg.length > 0 ) {
                     showClients(el.id);
                     $( "#dropdownData" ).focus();
                     searchflag = 2;
                  }
                  else {
                     Materialize.toast('No hay cuentas que comiencen con ese numero', 3000, 'rounded') 
                     hideClients();
                     $( "#cuenta" ).focus();
                  }
              }
      });
   }

   function selectedStatus(option) {
      $("select[id$='status'] option[value=" + option + "]").attr("selected", true);
      $('#status').formSelect();
   }

   function onChange(el) {
      console.log( el.id );
      switch( el.id ) {

         case "sumariza":
            if( $("#sumariza").attr('checked') == 1 ) {
               $('#cuentasuma').removeAttr('disabled'); 
            }
            else {
               $('#cuentasuma').attr('disabled','disabled'); 
            }
            break;

         default:
            break;

      }
      $( "#upd" ).removeClass( "hide" )
      $( "#upd" ).removeClass( "disabled" )
   }

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