<?php
//ini_set("display_errors",1);
session_start();
date_default_timezone_set('America/Lima');
require_once ("../../config/Cado.php");
require_once ("../ingreso/cIngreso.php");
$oIngreso = new cIngreso();
require_once ("../usuario/cUsuario.php");
$oUsuario = new cUsuario();
require_once("../formatos/formato.php");
if($_POST['action']=="insertar"){
	$fec=date('d-m-Y');
	$est='1';
	
	$caj_id=$_SESSION['caja_id'];
	$mon_id=1;
	$ven_id=0;
	$tra_id=0;
	if($_POST['vista']=='venta_ingreso_tabla'){
		$ven_id 	=$_POST['ven_id'];
		$cue_id 	=$_POST['cue_id'];
		$subcue_id 	=$_POST['subcue_id'];
		$cli_id 	=$_POST['cli_id'];
		$cli_doc 	=$_POST['cli_doc'];
		$cli_nom 	=$_POST['cli_nom'];
		$det 		=$_POST['det'];
		$imp 		=moneda_mysql($_POST['imp']);
		$ing_tot 	=moneda_mysql($_POST['ing_tot']);
		$imp=$imp-$ing_tot;
		$imp_max=$imp;
		$imp=formato_money($imp);
	}
}
if($_POST['action2']=="caja"){
	$fec=$_POST['ven_fec1'];
	$est='CANCELADO';
	
	$des=$_POST['ing_des'];
	$mon=formato_money($_POST['ing_mon']);
	
	$cue_id=22;
	
	if($_SESSION['empresa_id']==1)$subcue_id=157;
	if($_SESSION['empresa_id']==2)$subcue_id=158;
	
	$ref_id=$_POST['ref_id'];
	$caj_id=$_POST['caj_id'];
	$entfin_id=$_POST['entfin_id'];
}
if($_POST['action']=="editar"){
	
	ECHO $_POST['ing_id'];
	
	$dts= $oIngreso->mostrarUno($_POST['ing_id']);
	$numros = mysqli_num_rows($dts);
	echo $numros;
	$dt = mysqli_fetch_array($dts);
	$fecreg		=mostrarFechaHora($dt['tb_ingreso_fecreg']);
	$fecmod		=mostrarFechaHora($dt['tb_ingreso_fecmod']);
	$usureg		=$dt['tb_ingreso_usureg'];
	$usumod		=$dt['tb_ingreso_usumod'];
	$fec		=mostrarFecha($dt['tb_ingreso_fec']);
	$doc_id 	=$dt['tb_documento_id'];
	$numdoc		=$dt['tb_ingreso_numdoc'];
	$det		=$dt['tb_ingreso_det'];
	$cue_id		=$dt['tb_cuenta_id'];
	$subcue_id	=$dt['tb_subcuenta_id'];
	$cli_id		=$dt['tb_cliente_id'];
	$cli_nom 	=$dt['tb_cliente_nom'];
	$cli_doc 	=$dt['tb_cliente_doc'];
	$cli_dir 	=$dt['tb_cliente_dir'];
	$cli_tip 	=$dt['tb_cliente_tip'];
	$imp		=$dt['tb_ingreso_imp'];
	$caj_id		=$dt['tb_caja_id'];		
	$mon_id		=$dt['tb_moneda_id'];
	$ven_id		=$dt['tb_venta_id'];
	mysqli_free_result($dts);
	if($_POST['vista']=='venta_ingreso_tabla'){
		$ven_imp	=moneda_mysql($_POST['imp']);
		$ing_tot 	=moneda_mysql($_POST['ing_tot']);
		$imp_max=$ven_imp-$ing_tot+$imp;
	}
	$imp=formato_money($imp);
}
//usuarios
if($usureg>0)
{
	$dts=$oUsuario->mostrarUno($usureg);
	$dt = mysqli_fetch_array($dts);
	$usugru		=$dt['tb_usuariogrupo_id'];
	$usugru_nom	=$dt['tb_usuariogrupo_nom'];
	$usu_nom	=$dt['tb_usuario_nom'];
	$apepat		=$dt['tb_usuario_apepat'];
	$apemat		=$dt['tb_usuario_apemat'];
	$ema		=$dt['tb_usuario_ema'];
	
	mysqli_free_result($dts);
	
	$usuario_reg="$usu_nom $apepat $apemat";
}
if($usumod>0)
{
	$dts=$oUsuario->mostrarUno($usumod);
	$dt = mysqli_fetch_array($dts);
	$usugru		=$dt['tb_usuariogrupo_id'];
	$usugru_nom	=$dt['tb_usuariogrupo_nom'];
	$usu_nom	=$dt['tb_usuario_nom'];
	$apepat		=$dt['tb_usuario_apepat'];
	$apemat		=$dt['tb_usuario_apemat'];
	$ema		=$dt['tb_usuario_ema'];
	
	mysqli_free_result($dts);
	
	$usuario_mod="$usu_nom $apepat $apemat";
}
?>
<script type="text/javascript">
	$('.moneda2').autoNumeric({
		aSep: ',',
		aDec: '.',
	vMin: '0.00',
	vMax: '99999.00'
	
});
	$('#txt_ing_fec').datepicker({
		format: 'dd-mm-yyyy',
		autoclose:true,
		endDate: '+0d'
	}).on('hide', function () {
		$("#cmb_caj_id").focus();return false;
	})
function cmb_caj_id(ids)
{	
	$.ajax({
		type: "POST",
		url: "../caja/cmb_caj_id.php",
		async:true,
		dataType: "html",                      
		data: ({
			caj_id: ids
		}),
		beforeSend: function() {
			$('#cmb_caj_id').html('<option value="">Cargando...</option>');
		},
		success: function(html){
			$('#cmb_caj_id').html(html);
		}
	});
}
function cmb_mon_id(ids)
{	
	$.ajax({
		type: "POST",
		url: "../moneda/cmb_mon_id.php",
		async:false,
		dataType: "html",                      
		data: ({
			mon_id: ids
		}),
		beforeSend: function() {
			$('#cmb_mon_id').html('<option value="">Cargando...</option>');
		},
		success: function(html){
			$('#cmb_mon_id').html(html);
		}
	});
}
function cmb_doc_id(tipo,docid,vis)
{	
	$.ajax({
		type: "POST",
		url: "../documento/cmb_doc_id.php",
		async:true,
		dataType: "html",                      
		data: ({
			mod_id:	tipo,
			doc_id: 	docid,
			vista:		vis
		}),
		beforeSend: function() {
			$('#cmb_doc_id').html('<option value="">Cargando...</option>');
		},
		success: function(html){			
			$('#cmb_doc_id').html(html);
		},
		complete: function(){
		
		}
	});
}
function ingreso_txt_numdoc(){	
	$.ajax({
		type: "POST",
		url: "../ingreso/ingreso_txt_numdoc.php",
		async:false,
		dataType: "json",                      
		data: ({
			doc_id: $('#cmb_doc_id').val()
		}),
		beforeSend: function() {
			$('#txt_ing_numdoc').val('...');
		},
		success: function(data){			
			$('#txt_ing_numdoc').val(data.correlativo);
		
		},
		complete: function(){
			
		}
	});
}
function cliente_cargar_datos(idf){	
	$.ajax({
		type: "POST",
		url: "../cliente/cliente_reg.php",
		async:true,
		dataType: "json",                      
		data: ({
			action: "obtener_datos",
			cli_id:	idf
		}),
		beforeSend: function() {
			
		},
		success: function(data){
			$('#hdd_cli_id').val(idf);	
			$('#txt_cli_nom').val(data.nombre);	
			$('#txt_cli_doc').val(data.documento);						
			$('#txt_cli_dir').val(data.direccion);
			$("#hdd_cli_tip").val(data.tipo);
		}
	});		
}
function cmb_cue_id()
{	
	$.ajax({
		type: "POST",
		url: "../cuentas/cmb_cue_id.php",
		async:true,
		dataType: "html",                      
		data: ({
			cuetip_id:"1",
			orden: "ord",
			cue_id: "<?php echo $cue_id?>"
		}),
		beforeSend: function() {
			$('#cmb_cue_id').html('<option value="">Cargando...</option>');
		},
		success: function(html){
			$('#cmb_cue_id').html(html);
		}
	});
}
function cmb_subcue_id(cuenta_id)
{	
	$.ajax({
		type: "POST",
		url: "../cuentas/cmb_subcue_id.php",
		async:true,
		dataType: "html",                      
		data: ({
			cue_id: cuenta_id,
			subcue_id: "<?php echo $subcue_id?>"
		}),
		beforeSend: function() {
			$('#cmb_subcue_id').html('<option value="">Cargando...</option>');
		},
		success: function(html){
			$('#cmb_subcue_id').html(html);
		}
	});
}
$(function() {
	$('input').iCheck({
		checkboxClass: 'icheckbox_square-blue',
		radioClass: 'iradio_square-blue',
      increaseArea: '20%' 
  });
	
	cmb_mon_id(<?php echo $mon_id ?>);
	cmb_caj_id(<?php echo $caj_id?>);
	cmb_cue_id();
	cmb_subcue_id(<?php echo $cue_id?>);
	cmb_doc_id('6','<?php echo $doc_id?>','<?php echo $_POST['action']?>');
	$('#cmb_doc_id').change(function(event) {
		//ingreso_txt_numdoc();
	});
	$( "#txt_cli_doc" ).autocomplete({ 
		minLength: 1,
		source: "../cliente/cliente_complete_doc.php",
		select: function(event, ui){			
			$("#hdd_cli_id").val(ui.item.id);
			$("#txt_cli_nom").val(ui.item.nombre);
			$("#txt_cli_dir").val(ui.item.direccion);
			$("#hdd_cli_tip").val(ui.item.tipo);
		}
	});
	$( "#txt_cli_nom" ).autocomplete({ 
		minLength: 1,
		source: "../cliente/cliente_complete_nom.php",
		select: function(event, ui){			
			$("#hdd_cli_id").val(ui.item.id);							
			$("#txt_cli_doc").val(ui.item.documento);
			$("#txt_cli_dir").val(ui.item.direccion);
			$("#hdd_cli_tip").val(ui.item.tipo);	
		}
	});
	
	$('#cmb_cue_id').change(function(){
		cmb_subcue_id($('#cmb_cue_id').val());
	});
	
	$('#txt_ing_det').autocomplete({
		minLength: 1,
		source: "../ingreso/complete_ingreso_det.php"
	});
	$('#txt_ing_det').change(function(){
		$(this).val($(this).val().toUpperCase());
	});
	<?php if($_POST['vista']=='venta_ingreso_tabla'){ ?>
		$('#txt_ing_imp').change(function(){
		
			if($('#txt_ing_imp').autoNumericGet()><?php echo $imp_max?>)
			{
				toastr["success"]('Importe debe ser menor o igual a : '+<?php echo formato_money($imp_max);?>);
				$('#txt_ing_imp').val('<?php echo formato_money($imp_max);?>');
			}
		});
		<?php }?>
		<?php if($_POST['action']=="editar"){ ?>
	
	$('#txt_cli_doc,#txt_cli_nom').attr('disabled','disabled');
	<?php }?>
	$("#btn_ing_guardar").click(function() {
		$("#for_ing").submit();
	});
$('#for_ing').bootstrapValidator({ 
	     
	      message: 'Valor no valido',
	      feedbackIcons: {
	      	valid: 'glyphicon glyphicon-ok',
	      	invalid: 'glyphicon glyphicon-remove',
	      	validating: 'glyphicon glyphicon-refresh'
	      },
	      fields: {	      	
	      	txt_ing_fec: {
	      		group: '.col-lg-3',
	      		validators: {	      			
	      			date: {
	      				format: 'DD-MM-YYYY',
	      				message: 'Fecha no Valida'
	      			}
	      		}
	      	},txt_ing_det: {
	      		group: '.col-lg-12',
	      		validators: {
	      			notEmpty: {
	      				message: 'Campo vacio *'
	      			}
	      		}
	      	},cmb_caj_id: {
	      		group: '.col-lg-3',
	      		validators: {
	      			notEmpty: {
	      				message: 'Campo vacio *'
	      			}
	      		}
	      	},cmb_cue_id: {
	      		group: '.col-lg-6',
	      		validators: {
	      			notEmpty: {
	      				message: 'Campo vacio *'
	      			}
	      		}
	      	},txt_ing_imp: {
	      		group: '.col-lg-4',
	      		validators: { 
	      			notEmpty: {
	      				message: 'Campo vacio *'
	      			} 	      			 
                    }
                },cmb_ing_est: {
                	group: '.col-lg-3',
                	validators: {
                		notEmpty: {
                			message: 'Campo vacio *'
                		}
                	}
                },
            }
        }).on('success.form.bv', function(e) { 
        	
        	$.ajax({
        		type: "POST",
        		url: "../ingreso/ingreso_reg.php",
        		async:true,
        		dataType: "json",
        		data: $("#for_ing").serialize(),
        		beforeSend: function(){
        			
        		},
        		success: function(data){
        			$('.modal').modal('hide');
					$('.in').removeClass('modal-backdrop');		
					toastr["success"](data.ing_msj);
        			
        			/* ingreso_impresion(data.ing_id); */
        		},
        		complete: function(){
        			<?php
        			if($_POST['vista']=="ingreso_tabla")
        			{
        				echo $_POST['vista'].'();';
        			}
        			if($_POST['vista']=="venta_ingreso_tabla")
        			{
        				echo $_POST['vista'].'();';
        			}
        			?>
        		}
        	});
        });
        $("#cmb_caj_id").keydown(function(e){
        	if (e.which == 13){$("#cmb_mon_id").focus();return false; } });
        $("#cmb_mon_id").keydown(function(e){
        	if (e.which == 13){$("#cmb_ing_est").focus();return false; } });
        $("#cmb_ing_est").keydown(function(e){
        	if (e.which == 13){$("#cmb_cue_id").focus();return false;  } });
        $("#cmb_cue_id").keydown(function(e){
        	if (e.which == 13){$("#cmb_subcue_id").focus();return false;  } });
        $("#cmb_subcue_id").keydown(function(e){
        	if (e.which == 13){$("#txt_cli_doc").focus();return false;
        }
    });
        $("#txt_cli_doc").keydown(function(e){
        	if (e.which == 13){$("#txt_cli_nom").focus();return false;
        }
    });
        $("#txt_cli_nom").keydown(function(e){
        	if (e.which == 13){$("#cmb_doc_id").focus();return false;
        }
    });
        $("#cmb_doc_id").keydown(function(e){
        	if (e.which == 13){$("#txt_ing_numdoc").focus();return false;
        }
    });
        $("#txt_ing_numdoc").keydown(function(e){
        	if (e.which == 13){$("#txt_ing_det").focus();return false;
        }
    });
        $("#txt_ing_det").keydown(function(e){
        	if (e.which == 13){$("#txt_ing_imp").focus();return false;
        }
    });
        $("#txt_ing_imp").keydown(function(e){
        	if (e.which == 13){$("#btn_ing_guardar").focus();return false;
        }
    });
    });
</script>
<div class="col-xs-12 col-lg-12 col-md-12 col-sm-12" >
<form  role="form" id="for_ing" method="POST">
	<input type="hidden" id="action" name="action" value="<?php echo $_POST['action']?>">
	<input type="hidden" id="hdd_ing_id" name="hdd_ing_id" value="<?php echo $_POST['ing_id']?>">
	<input type="hidden" id="hdd_ing_usureg" name="hdd_ing_usureg" value="<?php echo $_SESSION['usuario_id']?>">
	<input type="hidden" id="hdd_ing_usumod" name="hdd_ing_usumod" value="<?php echo $_SESSION['usuario_id']?>">
	<input type="hidden" id="hdd_emp_id" name="hdd_emp_id" value="<?php echo $_SESSION['empresa_id']?>">
	<input type="hidden" id="hdd_ven_id" name="hdd_ven_id" value="<?php echo $ven_id?>">
	<input type="hidden" id="hdd_tra_id" name="hdd_tra_id" value="<?php echo $tra_id?>">
	<div class="box-header">
	<h3 class="box-title">Información de Ingreso</h3>
	</div>
					
	<div class="row">
		<div class="col-lg-3 col-sm-4 col-xs-6">
			<label for="txt_ing_fec">Fecha:</label>
			<input name="txt_ing_fec" type="text" class="form-control" id="txt_ing_fec" value="<?php echo $fec?>" >
		</div>
		<div class="col-lg-4 col-sm-4 col-xs-6">
			<label for="cmb_caj_id">Caja:</label>
			<select name="cmb_caj_id" id="cmb_caj_id" class="form-control"></select>
		</div>
		
	<!--	<div class="col-lg-3 col-sm-4 col-xs-6">
			<label for="cmb_mon_id">Moneda:</label>
			<select name="cmb_mon_id" id="cmb_mon_id" class="form-control"></select>
		</div>
-->
		<div class="col-lg-3 col-sm-4 col-xs-6" style="display:none" >
			<label for="cmb_ing_est">Estado:</label>
			<select name="cmb_ing_est" id="cmb_ing_est" class="form-control">
				<option value="">-</option>
				<option value="1" <?php if($est==1)echo 'selected'?>>CANCELADO</option>
				<?php if($_POST['vista']!='venta_ingreso_tabla'){?>
				<option value="2" <?php if($est==2)echo 'selected'?>>EMITIDO</option>
				<?php }?>
			</select>
		</div>
		<div class="col-lg-6 col-sm-6 col-xs-12">
			<label for="cmb_cue_id">Cuenta:</label>
			<select name="cmb_cue_id" id="cmb_cue_id" class="form-control"> </select>
		</div>
		<div class="col-lg-6 col-sm-6 col-xs-12">
			<label for="cmb_subcue_id">Sub Cuenta:</label>
			<select name="cmb_subcue_id" id="cmb_subcue_id" class="form-control"></select>
		</div>
	
		<div class="col-lg-4 col-sm-6 col-xs-6 d-none">
			<label for="txt_ven_cli_doc">RUC/DNI:</label>
			<div class="input-group">
				
				<input name="txt_cli_doc" type="text" id="txt_cli_doc" value="<?php echo $cli_doc?>"   maxlength="11" class="form-control" />    
			</div>
		</div>
		<div class="col-lg-8 col-sm-6 col-xs-6 d-none">
			<label for="txt_cli_nom">Cliente:</label>
			<input type="text" id="txt_cli_nom" name="txt_cli_nom"   class="form-control" value="<?php echo $cli_nom?>" /> 
			<input type="hidden" id="hdd_cli_id" name="hdd_cli_id" value="<?php echo $cli_id?>" /> 
		</div>
	
		<div class="col-lg-4 col-sm-6 col-xs-6 d-none">
			<label for="cmb_doc_id">Documento:</label>
			<select name="cmb_doc_id" id="cmb_doc_id" class="form-control"> </select>
		</div>
		<div class="col-lg-3 col-sm-6 col-xs-6 d-none">
			<label for="txt_ing_numdoc">N°. Doc.:</label>
			<input name="txt_ing_numdoc" type="text" id="txt_ing_numdoc"  value="<?php echo $numdoc?>" class="form-control" >
		</div>
	
		<div class="col-lg-12 col-sm-12 col-xs-12">
			<label for="txt_ing_det">Detalle:</label>
			<textarea name="txt_ing_det" class="form-control"  rows="1" id="txt_ing_det"><?php echo $det?></textarea>
		</div> 
	
		<div class="col-lg-4 col-sm-4 col-xs-4" style="display:none;">
			<?php if($_POST['action']=="insertar"){?>
			<label for=""> </label>
			<div    class=" input-group checkbox icheck">
				<label title="Activar para Imprimir" >
					<input title="Activar para Imprimir" name="chk_imprimir" id="chk_imprimir"   value="1" type="checkbox"> Imprimir?
				</label> 
			</div>  
			<?php }?> 
		</div> 
		<div class="col-lg-8 col-sm-4 col-xs-12">
			<?php 
			if($_POST['action']=="insertar"){?>
			<label for="chk_imprimir">Responsable del ingreso</label><br>
			<span class="badge badge-success"><?php echo $_SESSION['usuario_nombre']?></span>
			<?php } 
			if($_POST['action']=="editar"){?>  <br>
			<span title="REGISTRADO POR" class="badge badge-success"><i class="fa fa-plus"></i> <?php echo $usuario_reg.' - '.$fecreg; ?></span>
			<span title="EDITADO POR" class="badge badge-info"><i class="fa fa-pencil"></i> <?php echo $usuario_mod.' - '.$fecmod; ?></span>
			<?php } ?>			
		</div> 
		<div class="col-lg-4 col-sm-4 col-xs-12 float-right">
			<label for="txt_ing_imp">Importe:</label>
			<input type="text"   name="txt_ing_imp" id="txt_ing_imp" class="form-control moneda2"  style="text-align:right"  maxlength="12" value="<?php echo formato_money($imp)?>" <?php if($_POST['action2']=='caja') echo 'readonly'?>>
		</div> 
	</div> 
</form>
  
<div class="modal-footer float-right">	
			<?php 
			if($_POST['action']=="insertar"){?>
			<button type="button" class="btn btn-default" id="" data-dismiss="modal">Cancelar</button>
			<button type="button" class="btn btn-primary " id="btn_ing_guardar">Guardar</button>
			<?php } 
			if($_POST['action']=="editar"){?>  <br>
			<button type="button" class="btn btn-default" id="" data-dismiss="modal">Cancelar</button>
			<button type="button" class="btn btn-primary " id="btn_ing_guardar">Guardar</button>
			<?php } ?>	
			
	
</div>
</div>