<?php
if(isset($_POST["bimp"])) {	
	$var = VarServer("MYSQLI");
	$obj = new clsConexion($var[0],$var[1],$var[2],$var[3],$var[4]);
	$varFINI = (isset($_POST["eini"]))?$_POST["eini"]:NULL;
	$varFFIN = (isset($_POST["efin"]))?$_POST["efin"]:NULL;
	$varCCLI = (isset($_POST["ccod"]))?$_POST["ccod"]:NULL;
	$varFIni = FechaMySql($varFINI);
	$varFFin = FechaMySql($varFFIN);
	
	$sql = "call spQuery_Estado_Cuenta_CxC_Cabecera($varCCLI);";
	$obj->AbrirConexion();
	$rs = $obj->Query($sql);
	$obj->CerrarConexion();
	$fila = $obj->FetchArray($rs);
	$FechaActual = MostrarFecha();
	$html = '
		<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
		<head>
		<link rel="STYLESHEET" href="clases/dompdf/www/test/print_static.css" type="text/css" />
		<meta http-equiv="msthemecompatible" content="no" />
<link href="images/logo_siscomges_32x32.png" rel="shortcut icon" type="image/x-icon" />
</HEAD>
		
		<body>	
		<div id="body">	
		<div id="section_header">
		</div>	
		<div id="content">	  
		<div class="page" style="font-size: 7pt">
		
	<table style="width: 100%;" class="header">
	<tr>
	<td><h1 style="text-align: left">'.$varSysEmpresa.'</td>
	<td><h1 style="text-align: right">'.$_POST[titu].'</td>
	</tr>
	</table>
			
	<table style="width: 100%; font-size: 8pt;">
	<tr>
	<td width="40"><strong>Codigo</strong></td>
	<td width="5"><strong>:</strong></td>
	<td width="200" style="text-align: left">'.$fila["CCLI"].'</td>
	<td width="80" style="text-align: right"><strong>Ultima Compra :</strong></td>
	<td width="250" >'.$fila["ULT_COMPRA"].'</td>
	</tr>
	<tr>
	<td><strong>Nombre</strong></td>
	<td><strong>:</strong></td>
	<td style="text-align: left">'.$fila["CLIENTE"].'</td>
	<td style="text-align: right"><strong>Ultimo Pago :</strong></td>
	<td>'.$fila["ULT_PAGO"].'</td>
	</tr>
	<tr>
	<td><strong>Dirección</strong></td>
	<td><strong>:</strong></td>
	<td style="text-align: left">'.$fila["DIRECCION"].'</td>
	<td style="text-align: right"><strong>Saldo Actual :</strong></td>
	<td>'.number_format($fila["SALDO"],"2",".",",").'</td>
	</tr>
	<tr>
	<td colspan="5">Registro de Movimientos del '.$varFINI.' al '.$varFFIN.'</td>
	</tr>
	</table>		
	<table class="change_order_items">
	<tbody>
	<tr>
	<th colspan="8">LISTADO DE MOVIMIENTOS</th>
	</tr>
	<tr>
	<th width="40">Fecha</th>
	<th width="80">Tipo Doc</th>
	<th width="60">Documento</th>
	<th width="180">Descripcion</th>
	<th width="35">Cant.</th>
	<th width="35">Venta</th>
	<th width="35">Pagos</th>
	<th width="35">Saldo</th>
	</tr>';
	$sql = "call spQuery_Estado_Cuenta_CxC($varCCLI,'$varFIni','$varFFin')";
	$obj->AbrirConexion();
	$rs = $obj->Query($sql);
	$obj->CerrarConexion();
	$j=0;
	$bgcolor1 = 'class="even_row" ';
	$bgcolor2 = 'class="odd_row" ';
	$varSaldo = 0;
	while($fila = $obj->FetchArray($rs))	{
		$j=$j+1;
		$varSaldo = $varSaldo + $fila["VENTA"] - $fila["PAGOS"];
		$html.= ($j%2==0)?'<tr '.$bgcolor1.'>':'<tr '.$bgcolor2.'>';
		$html.= '<td style="text-align:center;">'.$fila[0].'</td>
		<td>'.ucwords(strtolower($fila[1])).'</td>
		<td style="text-align: center">'.strtolower($fila[2]).'</td>
		<td>'.ucwords(strtolower($fila[3])).'</td>
		<td style="text-align: center">';
	$html.= (!is_null($fila[4]) && $fila[4]<>0)?number_format($fila[4],"0",".",","):"";
	$html.= '</td>
		<td style="text-align: right">';
	$html.= (!is_null($fila[5]) && $fila[5]<>0)?number_format($fila[5],"2",".",","):"";
	$html.= '</td>
		<td style="text-align: right">';
	$html.= (!is_null($fila[6]) && $fila[6]<>0)?number_format($fila[6],"2",".",","):"";
	$html.= '</td>
		<td style="text-align: right">'.number_format($varSaldo,"2",".",",").'</td>
		</tr>';
		}
	$html.= '
	</tbody>
	</table>
			
		
			</div>
			
			</div>
			</div>
			
			<script type="text/php">
			
			if ( isset($pdf) ) {
			
			  $font = Font_Metrics::get_font("verdana");;
			  $size = 7;
			  $color = array(0,0,0);
			  $text_height = Font_Metrics::get_font_height($font, $size);
			
			  $foot = $pdf->open_object();
			  
			  $w = $pdf->get_width();
			  $h = $pdf->get_height();
			
			  // Draw a line along the bottom
			  $y = $h - 2 * $text_height - 24;
			  $pdf->line(16, $y, $w - 16, $y, $color, 1);
			
			  $y += $text_height;
			
			  $text = "by KenCitoxD";
			  $pdf->text(16, $y, $text, $font, $size, $color);
			
			  $pdf->close_object();
			  $pdf->add_object($foot, "all");
			
			  global $initials;
			  $initials = $pdf->open_object();
			  
			  // Add an initals box
			  $text = "'.$FechaActual.'";
			  $width = Font_Metrics::get_text_width($text, $font, $size);
			  $pdf->text($w - 16 - $width, $y, $text, $font, $size, $color);
				
			
			  $pdf->close_object();
			  $pdf->add_object($initials);
			
			  $text = "Pagina {PAGE_NUM} de {PAGE_COUNT}";  
			
			  // Center the text
			  $width = Font_Metrics::get_text_width("Pagina 1 de 2", $font, $size);
			  $pdf->page_text($w / 2 - $width / 2, $y, $text, $font, $size, $color);
			  
			}
			</script>
			
			</body>
			</html>';
	require_once("clases/dompdf/dompdf_config.inc.php");
	ini_set("memory_limit","64M");
	  
	$dompdf = new DOMPDF();
	$dompdf->load_html($html);
	//$dompdf->set_paper("a4", "landscape");
	$dompdf->set_paper("a4", "portrait");
	$dompdf->render();
	$dompdf->stream("Cuenta Corriente");
	}
	
require_once('clases/xajax/xajax_core/xajax.inc.php');
$xajax = new xajax();
//$xajax->setFlag('debug',true); 
$xajax->configure('javascript URI', 'clases/xajax/');

require "clases/KoolAjax/koolajax.php";
$koolajax->scriptFolder = "clases/KoolAjax";
	
function seleccionaProducto($ide) {
	if($ide<>"") {
		$var = VarServer("MYSQLI");
		$obj = new clsConexion($var[0],$var[1],$var[2],$var[3],$var[4]);
		$obj->AbrirConexion();
		$sql = "call spQuery_Lista_Producto('$ide','');";
		$rs = $obj->Query($sql);
		$obj->CerrarConexion();
		$Fila = $obj->FetchArray($rs);
		if($obj->NumFilas($rs)>0) $retorna = $Fila[1]."[[sep]]".$Fila[2];
		else $retorna = "NO EXISTE";
		}
	return $retorna;
	}
	
function seleccionaCliente($ide) {
	if($ide<>"") {
		$var = VarServer("MYSQLI");
		$obj = new clsConexion($var[0],$var[1],$var[2],$var[3],$var[4]);
		$obj->AbrirConexion();
		$sql = "call spQuery_Lista_Cliente('$ide','','');";
		$rs = $obj->Query($sql);
		$obj->CerrarConexion();
		$Fila = $obj->FetchArray($rs);
		if($obj->NumFilas($rs)>0) $retorna = $Fila[1];
		else $retorna = "NO EXISTE";
		}
	return $retorna;
	}	
	
$xajax->processRequest();
$xajax->printJavascript("clases/xajax");

$koolajax->enableFunction("seleccionaProducto");
$koolajax->enableFunction("seleccionaCliente");	
echo $koolajax->Render();
		
function MyTable($obj, $Titulo, $Opcion, $Valor) {
$Link = $_SERVER['PHP_SELF'];
$MyTabla = "_sv_venta";
$myID = "id_venta";
?>
<script language="javascript">
function pulsar(e, a) {
	tecla=(document.all) ? e.keyCode : e.which;
	var Campo = a.name;		
		
	if(tecla==13) {
		if(Campo == "ccod") {
			cargar("U","C",a.value,document.form.emp.value);
			document.form.cond.focus();
			}
		if(Campo.indexOf("acod")==0) {
			msj_articulo = "NO PRESIONES ENTER\n";
			}
		}
	return(tecla!=13);
//	document.form.cond.focus();
	}

function cargarCliente(ccod, cnom) {
	var Ruta = 'lista_cliente.php?ccod='+ccod+'&cnom='+cnom;
	testwindow= window.open (Ruta, "mywindow", "location=1,status=1,scrollbars=1,width=600,height=550");
	}

function impCuenta(cliente, fechaini, fechafin) {
	var Ruta = 'print/print_cuenta.php?ccli='+cliente+'&fini='+fechaini+'&ffin='+fechafin;
	testwindow= window.open (Ruta, "mywindow",
    "location=1,status=1,scrollbars=1,width=100,height=50");
	}

function select_Cliente(ccod, cnom) {		
	var ccod1 = document.getElementById(ccod);
	var cnom1 = document.getElementById(cnom);
	if(ccod1.value=="") {
		ccod1.value = "";
		cnom1.value = "";
		}
	else {			
		var dato = koolajax.callback(seleccionaCliente(ccod1.value));
		if(dato=="NO EXISTE") {
//			alert("CLIENTE NO EXISTE");
			ccod1.value = "";
			cnom1.value = dato;
			ccod1.focus();
			}
		else {
			cnom1.value = dato;
			}
		}
	}
</script>
<?php
if(!isset($Opcion)) {
	$varPCOD = (isset($_POST["pcod"]))?$_POST["pcod"]:NULL;
	$varPNOM = (isset($_POST["pnom"]))?$_POST["pnom"]:NULL;
	
	$varTabla=array("id"=>"tabla", "name"=>"table", "tamano"=>"420", "clase"=>"Formtitulo", "titulo"=>$Titulo." - BUSQUEDA",
					"formu"=>array("id"=>"form", "name"=>"form", "metodo"=>"POST", "onsubmit"=>"return validaForm(this)"),						
					"ocult"=>array(array("tipo"=>"oculto", "id"=>"titu", "name"=>"titu", "valor"=>$Titulo),
								   array("tipo"=>"oculto", "id"=>"opt", "name"=>"opt", "valor"=>$Opcion)
								  ),
					"conte"=>array(array("titulo"=>"Proveedor :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "campo"=>array("tipo"=>"varios",
														    "contenido"=>array(array("tipo"=>"text", "id"=>"pcod", "name"=>"pcod", "valor"=>$varPCOD, 
																					 "ancho"=>"60",  "alinear"=>"center", 
																					 "blur"=>"xajax_seleccionar_proveedor(this.value)", 
																					 "dclick"=>"fn_cargar_listado_proveedor('pcod', 'pnom')"),
																			   array("tipo"=>"text", "id"=>"pnom", "name"=>"pnom", "valor"=>$varPNOM, 
																			   		 "ancho"=>"220", "clase"=>"inputDisable", "locked"=>"SI")
																			   )
														 )
										  	 ),								  
								   array("titulo"=>"Fecha Incial :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
										 "campo"=>array("tipo"=>"fecha", "id"=>"eini", "name"=>"eini", "alinear"=>"center", "valor"=>$_POST[eini]) ),
								   array("titulo"=>"Fecha Final :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
										 "campo"=>array("tipo"=>"fecha", "id"=>"efin", "name"=>"efin", "alinear"=>"center", "valor"=>$_POST[efin]) )									   
								   ),
					"boton"=>array(array("tipo"=>"submit", "id"=>"bcon", "name"=>"bcon", "ancho"=>"80", "alto"=>"22", "texto"=>"Consultar"),			  
								   array("tipo"=>"submit", "id"=>"bimp", "name"=>"bimp", "ancho"=>"80", "alto"=>"22", "texto"=>"Imprimir")
								   )
					);
	echo $obj->setTablaForm($varTabla);		
	if(isset($_POST["bcon"])) {		
		$varFIni = FechaMySql($_POST["eini"]);
		$varFFin = FechaMySql($_POST["efin"]);		
		$sql = "call spQuery_Estado_Cuenta_CxC($_POST[ccod],'$varFIni','$varFFin')";
		$obj->AbrirConexion();
		$rs = $obj->Query($sql);
		$obj->CerrarConexion();

		echo "<table id=\"tablea\" style=\"padding: 0; margin-top:5px; margin-bottom:10px; border-collapse:collapse;\" 
			  align=\"center\" cellpadding=\"0\" cellspacing=\"0\"  width=\"800\" >";
		echo "<tr>";
		echo "<th width=70 	class=\"sortable\">FECHA</th>";
		echo "<th width=150 class=\"sortable\">TDOC</th>";
		echo "<th width=70 	class=\"sortable\">NRO documento</th>";
		echo "<th width=300 class=\"sortable\">DESCRIPCION</th>";
		echo "<th width=40 	class=\"sortable\">CANT.</th>";
		echo "<th width=50 	class=\"sortable\">VENTA</th>";
		echo "<th width=50	class=\"sortable\">PAGOS</th>";
		echo "<th width=50 	class=\"sortable\">SALDO</th>";
		echo "</tr>";
		echo "<tbody>";
		$j=0;
		$color1 = "#F5FAFA";
		$color2 = "#edf3f3";
		$colors = "#FFFF33";//"#99FFCC";	
		$bgcolor1 = "bgcolor=$color1 onMouseOver=\"uno(this,'$colors')\"";
		$bgcolor1.= "onMouseOut=\"dos(this,'$color1')\"";		
		$bgcolor2 = "bgcolor=$color2 onMouseOver=\"uno(this,'$colors')\"";
		$bgcolor2.= "onMouseOut=\"dos(this,'$color2')\"";
		$varSaldo=0;
		while($fila = $obj->FetchArray($rs))	{
			$varSaldo = $varSaldo + $fila["VENTA"] - $fila["PAGOS"];
			$j++;	
			echo ($j%2==0)?"<tr $bgcolor1>": "<tr $bgcolor2>";
			echo "<td class=\"interior\" align=\"center\" height=20>&nbsp;$fila[0]</td>";
			echo "<td class=\"interior\">&nbsp;$fila[1]</td>";
			echo "<td class=\"interior\" align=\"center\">&nbsp;$fila[2]</td>";
			echo "<td class=\"interior\">&nbsp;$fila[3]</td>";
			echo "<td class=\"interior\" align=\"right\">&nbsp;";
			if(!is_null($fila["CANTIDAD"])) echo number_format($fila["CANTIDAD"], 2,'.',',');
			echo "</td>";
			echo "<td class=\"interior\" align=\"right\">&nbsp;";
			if(!is_null($fila["VENTA"])) echo number_format($fila["VENTA"], 2,'.',',');
			echo "</td>";
			echo "<td class=\"interior\" align=\"right\">&nbsp;";
			if(!is_null($fila["PAGOS"])) echo number_format($fila["PAGOS"], 2,'.',',');
			echo "</td>";
			echo "<td class=\"interior\" align=\"right\"><b>".number_format($varSaldo, 2,'.',',')."</b></td>";
			echo "</tr>";
			}
		echo "</tbody>";
		echo "</table>";	
		}
	}
elseif($Opcion=="PAG") {
	$sql = "SELECT V.id_cliente as CCLI, UPPER(C.nombre) as CLIENTE,
			T.nombre as TIPO,  T.abrev as CTIP, V.nro_documento as NFAC, 
			Co.nombre as CONDICION,
			date_format(V.fecha_emision,'%d/%m/%Y') as FECHA, V.TOTAL, V.SALDO, V.estado
			FROM _sv_venta V
			inner join _sv_cliente C ON V.id_cliente = C.id_cliente
			inner join _sv_tipo_doc_pago T ON V.id_tipo_doc = T.id_tipo_doc
			inner join _sv_tipo_condicion Co ON V.id_condicion = Co.id_condicion
			where V.estado not in ('AN','CA')
			and V.id_venta = $Valor";
	$obj->AbrirConexion();
	$rs = $obj->Query($sql);
	$obj->CerrarConexion();
	$fila = $obj->FetchArray($rs);
	
	echo "<form name=\"formulario\" id=\"formulario\" method=\"post\" onSubmit=\"return validaRegistroPago(this)\">";
	echo "<table style=\"padding:0;margin-top:0px;border-collapse:collapse;\" ";
	echo "width=450 align=center cellpadding=0 cellspacing=0>";
	echo "<tr>";
	echo "<td height=25 colspan=2 valign=top align=\"center\" class=\"FormTitulo\">";
	echo "<input name=\"txtven\" type=\"hidden\" id=\"txtven\" value=\"$Valor\" />";
	echo "<input name=\"txtdoc\" type=\"hidden\" id=\"txtdoc\" value=\"$fila[CTIP] $fila[NFAC]\" />";
	echo "<input name=\"txtcli\" type=\"hidden\" id=\"txtcli\" value=\"$fila[CCLI]\" />";
	echo "<input name=\"txtmon\" type=\"hidden\" id=\"txtmon\" value=\"$fila[TOTAL]\" />";
	echo "<input name=\"txtsal\" type=\"hidden\" id=\"txtsal\" value=\"$fila[SALDO]\" />";
	echo "$Titulo - REALIZAR PAGO</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\" width=100>Documento :</td>";
	echo "<td class=\"form_texto\" width=300>$fila[TIPO] ($fila[CTIP])</td>";
	echo "</tr>";	
	echo "<tr>";
	echo "<td class=\"form_titulo\">Numero :</td>";
	echo "<td class=\"form_texto\">$fila[NFAC]</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\" width=100>Condicion :</td>";
	echo "<td class=\"form_texto\" width=300>$fila[CONDICION]</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\" width=100>Cliente :</td>";
	echo "<td class=\"form_texto\" width=300>$fila[CLIENTE]</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\">Fecha Emisión :</td>";
	echo "<td class=\"form_texto\">$fila[FECHA]</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\">Monto :</td>";
	echo "<td class=\"form_texto\">$fila[TOTAL]</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\">Saldo :</td>";
	echo "<td class=\"form_texto\">$fila[SALDO]</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\">Fecha Pago :</td>";
	echo "<td class=\"form_texto\">";
	echo "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
	echo "<tr>";
	echo "<td width=\"90\" height=\"22\" valign=\"middle\">";
	echo "<input name=femi type=text class=inputNormal id=femi ";
	echo "style=\"width:100px; height:18px; font-family:tahoma; font-size:11px; text-align:center\" value=\"\">";
	echo "</td>";
	echo "<td width=\"40\" valign=\"middle\">";
	echo "<a href=\"javascript:void(0)\" ";
	echo "onClick=\"if(self.gfPop)gfPop.fPopCalendar(document.formulario.femi);return false;\" >";
	echo "<img class=PopcalTrigger src=\"HelloWorld/calbtn.gif\" width=34 height=22 border=0></a>";
	echo "</td>";
	echo "<td width=\"300\" valign=\"middle\">";
	echo "Ejm. ",date( "d/m/Y",time()); 
	echo "</td>";
	echo "</tr>";
	echo "</table>";	
	echo "</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\">Monto a Pagar :</td>";
	echo "<td class=\"form_texto\">";
	echo "<input id=\"txtpago\" name=\"txtpago\" type=\"text\" style=\"width:100px;text-align:center\" onkeypress=\"return SoloNumeros(event)\" >";
	echo "</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td class=\"form_titulo\">Observacion :</td>";
	echo "<td class=\"form_texto\">";
	echo "<textarea name=\"txtobs\" rows=\"5\" id=\"txtobs\" style=\"width:300px;\"></textarea>";
	echo "</td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td height=25 colspan=10 valign=top aling=\"center\" class=\"FormTitulo\">";		
	echo "<input id=\"save\" name=\"save\" type=\"submit\" style=\"width:100px;height:22px;\" value=\"Registrar Pago\" ";
	echo "onClick=\"return confirm('¿DESEA GUARDAR ESTE PAGO?')\" >&nbsp;&nbsp;";
	echo "<input name=\"regresar\" type=\"button\" id=\"regresar\" style=\"width:100px; height:22px;\" ";
	echo "onClick=\"location='".$Link."'\" value=\"Regresar\">";
	echo "</td>";
	echo "</tr>";
	echo "</table>";
	echo "<br>";
	
	
	$sql = "select D.id_producto as CPRO, P.descripcion as PRODUCTO, D.cantidad, D.precio, D.subtotal, D.igv, D.total
			from _sv_venta_detalle D
			inner join _sv_producto P ON D.id_producto = P.id_producto
			where D.id_venta = $Valor";
			
	$rs_cab = array(0=>array("Tamano"=>20, "Titulo"=>"CPRO", "Negrita"=>"SI", "Alinear"=>"center"),
					1=>array("Tamano"=>300, "Titulo"=>"DESCRIPCION"),
					2=>array("Tamano"=>60,  "Titulo"=>"CANT", "Alinear"=>"right"),
					3=>array("Tamano"=>60,  "Titulo"=>"UNIT", "Alinear"=>"right"),
					4=>array("Tamano"=>60,  "Titulo"=>"V.VENTA", "Alinear"=>"right"),
					5=>array("Tamano"=>60,  "Titulo"=>"IGV", "Alinear"=>"right"),
					6=>array("Tamano"=>60,  "Titulo"=>"TOTAL", "Alinear"=>"right")
				   );
				   
	echo $obj->SetGrid(600,$rs_cab,$sql,NULL,4,NULL,"SI"); 
	echo "</form>";		
	}

	
} 
?>