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

$_SESSION["module"] = "Empresas.";


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

$Title = "Empresas";
$admin = false;
include 'contableHeader.php'; 
?>
<style>
.dropdown-content {
  overflow-x: hidden;
}

.btn:hover {
  color: #b0bec5;
}

#claim:hover {
   background-color: #cfd8dc; 
}

.data {
   margin-top: 0; 
   margin-bottom: 0;                       
   padding-left: 5%;
}


.margin {
   margin-top: 0; 
   margin-bottom: 0; 
}

.margin-label {
   margin-top: 5px; 
}

.row {
   padding: 0;
   margin: 0;
}

input[type=select]:disabled + label,
input[type=select]:disabled, 
input[type=textarea]:disabled,
input[type=textarea] + label,
textarea.materialize-textarea:disabled + label, 
input[type=text] + label,
input[type=text]:disabled + label {
   color: #009688;
   color: grey;
}

.select-wrapper input.select-dropdown:disabled {
/*   color: #b71c1c; */
}

textarea.materialize-textarea:disabled,
input[type=text]:disabled {
   color: #303030;
   color: grey;
}

</style>
   <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
   <div id="content">
   <div class="container" style="width:80%" >
   <div style="height: 30px;"></div>
   <div class="col l9 m12 s12">
      <div class="page-content">
<!--        <a onclick='newClient(this);' class='btn-floating btn-large waves-effect waves-light red' style='float:right; margin-top:20px;'><i class='material-icons'>add</i></a> -->
      </div>

<?php
      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='newClient(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;'>";
         echo "<div class='row'>";
         echo "<div class='input-field col s2'>";
         echo "</div>";
         echo "</div>";
         echo "<div class='row'>";
         echo "<div class='input-field col s6'>";
             echo "<input id='empresa' type='text' class='' placeholder=' ' value=''>";
             echo "<label for='empresa'>Empresa</label>";
         echo "</div>";
         echo "</div>";
         echo "<div class='row'>";
         echo "<div class='input-field col s6'>";
             echo "<input id='direccion' type='text' disabled class='' placeholder=' ' value='' onChange='onChange(this);'>";
             echo "<label for='direccion'>Direcci&oacute;n</label>";
         echo "</div>";
         echo "<div class='input-field col s6'>";
             echo "<input id='contacto' type='text' disabled class='' placeholder=' ' value='' onChange='onChange(this);'>";
             echo "<label for='contacto'>Contacto</label>";
         echo "</div>";
         echo "</div>";
         echo "<div class='row'>";
         echo "<div class='input-field col s6'>";
             echo "<input id='correo' type='text' disabled class='' placeholder=' ' value='' onChange='onChange(this);'>";
             echo "<label for='correo'>Correo Electr&oacute;nico</label>";
         echo "</div>";
         echo "<div class='input-field col s6'>";
             echo "<input id='telefonos' type='text' disabled class='' placeholder=' '  value='' onChange='onChange(this);'>";
             echo "<label for='telefonos'>Tel&eacute;fonos</label>";
         echo "</div>";
         echo "</div>";
         echo "<div style='height:5px;'></div>";
         echo "<div class='row'>";
         echo "<div class='input-field col s4'>";
            echo "<select id='condicion' disabled>";
            echo "<option value='0' disabled selected>Seleccione la condicion IVA</option>";
            echo "<option value='1'>Responsable Inscripto</option>";
            echo "<option value='2'>Responsable No Inscripto</option>";
            echo "<option value='3'>Monotributo</option>";
            echo "</select>";
            echo "<label>Condicion IVA</label>";
         echo "</div>";
         echo "<div class='input-field col s4'>";
             echo "<input id='cuit' type='text' disabled class='' placeholder=' ' value='' onChange='onChange(this);'>";
             echo "<label for='cuit'>CUIT</label>";
         echo "</div>";
         echo "<div class='input-field col s4'>";
             echo "<input id='ib' type='text' disabled class='' placeholder=' ' value='' onChange='onChange(this);'>";
             echo "<label for='ib'>Ingresos Brutos</label>";
         echo "</div>";
         echo "</div>";
         echo "<div style='height:5px;'></div>";
         echo "<div class='row'>";
         echo "<div class='input-field col s12' disabled >";
            echo "<textarea id='observaciones' class='materialize-textarea' onChange='onChange(this);'> </textarea>";
            echo "<label for='observaciones'>Observaciones</label>";
         echo "</div>";
         echo "</div>";
         echo "<div class='input-field col s12' style='margin-top: 0;'>";
            echo "<a id='delete' onclick='Delete(this);' class='waves-effect waves-light btn waves-green btn-flat' 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 waves-green btn-flat' 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 waves-green btn-flat' 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>";
?>          
    <ul id='dropdownClient' class='dropdown-client' style='z-index:10; display:none;'>
    </ul>
   </div>
   </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;
   min-height: 3em;
   text-align: left;
   padding: 0px 16px;
}
ul.dropdown-client li:hover {
 background-color:#90a4ae;
}
</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
      });

       $('.modal').modal({dismissible: false, outDuration: 0, startingTop: '4%', endingTop: '10%', 
                     onOpenStart: function(el) { modalOpen(el); }
       });


      $('select').formSelect();

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

      jQuery(function($){
         $("#cuit").mask("99-99999999-9",{placeholder:" ", autoclear: false});
      });

   });   

   function Cancel(e) {

      console.log( "Cancel!" );
      newflag = false;
      searchflag = 0;
      $('#cancel').css("display", "none" );
      $('#delete').css("display", "none" );
      $('#empresa').val(""); 
      $('#direccion').val(""); 
      $('#telefonos').val(""); 
      $('#correo').val(""); 
      $('#contacto').val(""); 
      $('#cuit').val(""); 
      $('#ib').val(""); 
      $('#observaciones').val(""); 
      $("select[id$='condicion'] option[value=0]").attr("selected", true);

//      $('#empresa').attr('disabled'); 
      $('#direccion').attr('disabled','disabled'); 
      $('#contacto').attr('disabled','disabled'); 
      $('#correo').attr('disabled','disabled'); 
      $('#telefonos').attr('disabled','disabled'); 
      $('#condicion').attr('disabled','disabled'); 
      $('#observaciones').attr('disabled','disabled'); 
      $('#cuit').attr('disabled','disabled'); 
      $('#ib').attr('disabled','disabled'); 
      $('#condicion').formSelect();
      $('#empresa').focus(); 
   }

   function newClient(e) {

      hideClients();
      newflag = true;
      $('#cancel').css("display", "" );
      $('#empresa').val(""); 
      $('#direccion').val(""); 
      $('#telefonos').val(""); 
      $('#ecorreo').val(""); 
      $('#contacto').val(""); 
      $('#observaciones').val(""); 
      $('#condicion').val('0');
      $('#cuit').val(""); 
      $('#ib').val(""); 

      $('#direccion').removeAttr('disabled'); 
      $('#empresa').removeAttr('disabled'); 
      $('#contacto').removeAttr('disabled'); 
      $('#correo').removeAttr('disabled'); 
      $('#telefonos').removeAttr('disabled'); 
      $('#condicion').removeAttr('disabled'); 
      $('#observaciones').removeAttr('disabled'); 
      $('#cuit').removeAttr('disabled'); 
      $('#ib').removeAttr('disabled'); 
      $('#condicion').formSelect();
      $('#empresa').focus(); 
   }


   // 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: "contableUpdateEmpresa.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 = $('#id').val();

      var empresa = $('#empresa').val(); 
      var direccion = $('#direccion').val(); 
      var contacto = $('#contacto').val(); 
      var telefonos = $('#telefonos').val(); 
      var correo = $('#correo').val(); 
      var cuit = $('#cuit').val(); 
      var ib = $('#ib').val(); 
      var observa = $('#observaciones').val(); 
      var condicion = $('#condicion').val(); 

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

      if( newflag == true ) {

         mode = "append";
         var msg = "";
         if( empresa.length <= 0 ) {
            msg = 'Ingrese el nombre de la empresa';
            Materialize.toast(msg, 3000, 'rounded') 
         }
      }

      console.log( observa );
      $.ajax({
          type: "POST",
          url: "contableUpdateEmpresa.php",
          data: {'id': id, 'empresa': empresa, 'direccion': direccion, 'contacto': contacto, 'telefonos': telefonos, 'correo': correo, 'cuit': cuit, 'ib': ib, 'observaciones': observa, 'condicion': condicion, 'mode': mode },
              success: function(data){
                             console.log( data );
                              var msg = JSON.parse(data);
                              if( msg.status.length >= 0 ) {
                                 Cancel(e);
                              }    
                       }
      });
//      post("contableUpdateEmpresa.php", {id: id, empresa: empresa, direccion: direccion, contacto: contacto, telefonos: telefonos, correo: correo, cuit: cuit, ib: ib, observaciones: observa, condicion: condicion, mode: mode }); 
   }

   function showClients() {

      $( "#dropdownClient" ).addClass( "active" );
      $( "#dropdownClient" ).css( "opacity", 1 );
      $( "#dropdownClient" ).css( 'display', 'block' );
      $( "#dropdownClient" ).css( "width", "35%" );
      $( "#dropdownClient" ).css( "height", "35%" );
      $( "#dropdownClient" ).css( "color", "#009688" );
      $( "#dropdownClient" ).css( "position", "absolute" );
      $( "#dropdownClient" ).css( "top", "285" );
      $( "#dropdownClient" ).css( "left", "14%" );
      $( "#dropdownClient" ).css( 'margin', '0 0 15px 0' );
      $( "#dropdownClient" ).css( 'line-height', '3em' );
      $( "#empresa" ).removeClass( "invalid" );

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

            found = false;
            var key = $(this).val();
            $('#empresa').val($(this).html()); 
            $('#id').val($(this).val()); 
//            console.log( $(this).val() );

            $.ajax({
                type: "POST",
                url: "getEmpresa.php",
                data: { 'key': key  },
                    success: function(data){
                       var msg = JSON.parse(data);
  
                       $('#empresa').val(msg.nombre); 
                       $('#direccion').val(msg.direccion); 
                       $('#contacto').val(msg.contacto); 
                       $('#telefonos').val(msg.telefonos); 
                       $('#correo').val(msg.mail); 
                       $('#cuit').val(msg.cuit); 
                       $('#ib').val(msg.ib); 
                       $('#observaciones').val(msg.observa); 
                       $("select[id$='condicion'] option[value=" + msg.tipo_iva + "]").attr("selected", true);

                       $('#direccion').removeAttr('disabled'); 
                       $('#empresa').removeAttr('disabled'); 
                       $('#contacto').removeAttr('disabled'); 
                       $('#correo').removeAttr('disabled'); 
                       $('#telefonos').removeAttr('disabled'); 
                       $('#condicion').removeAttr('disabled'); 
                       $('#cuit').removeAttr('disabled'); 
                       $('#ib').removeAttr('disabled'); 
                       $('#observaciones').removeAttr('disabled'); 
                       $('#condicion').formSelect();

                       if( searchflag == 1 )
                        $( "#empresa" ).focus();
                       found = true;

                       $('#cancel').css("display", "" );
                       if( newflag == false ) $('#delete').css("display", "" );
                     }
           });
           hideClients();
      });   
   }

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

   function populateClientes(key) {
      $('#dropdownClient').empty();
      $.ajax({
          type: "POST",
          url: "recvEmpresas.php",
          data: { 'key': key  },
              success: function(data){
                  var msg = JSON.parse(data);
                  console.log(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#dropdownClient").append($("<li></li>").val(msg[i].option).html(msg[i].nombre));
                  }
                  if( msg.length >= 0 ) {
                     showClients();
                     $( "#dropdownClient" ).focus();
                     searchflag = 2;

                  }
                  else {
                     Materialize.toast('No hay clientes que comiencen con ese apellido', 3000, 'rounded') 
                     hideClients();
                     $( "#empresa" ).focus();
                  }
              }
      });
   }

   function populateNroClientes(key) {
      $('#dropdownClient').empty();
      $.ajax({
          type: "POST",
          url: "recvNroClientes.php",
          data: { 'key': key  },
              success: function(data){
                  var msg = JSON.parse(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#dropdownClient").append($("<li></li>").val(msg[i].option).html(msg[i].option + " - " + msg[i].name));
                  }
                  if( msg.length > 0 ) {
                     showClients();
                     $( "#dropdownClient" ).focus();
                     searchflag = 1;
                  }
                  else {
                     Materialize.toast('No hay clientes que comiencen con ese numero', 3000, 'rounded') 
                     hideClients();
                     $( "#clientenro" ).focus();
                  }
              }
      });
   }

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

   function onChange(el) {
      $( "#upd" ).removeClass( "hide" )
      $( "#upd" ).removeClass( "disabled" )
   }

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