<!DOCTYPE html>
<html lang="es-ES">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Pantalla Reporte Cuentas por Cobrar Saldo a Fecha</title>
<link href="../../maincss.css" rel="stylesheet" type="text/css" />
<link href="../../printcss.css" rel="stylesheet" type="text/css" media="print" />

</head>
<?php
include "../../conn.php";
include "../../general.php";
include "../../token.php";

$rep=$_GET["rep"];
$tipo=$_GET["tipo"];
$agrupar=$_POST["agrupar"];
$detalle_resumido=$_POST["detalle_resumido"];
$saldo_cero=$_POST["saldo_cero"];
$nombre=$_POST["nombre"];
$fechaini=$_POST["fechaini"];
$fechafin=$_POST["fechafin"];
$concepto_cobro=$_POST["concepto_cobro"];
$cuenta_concepto_cxc=$_POST["cuenta_concepto_cxc"];
$cod_contexto=$_POST["contexto"];
$canal_venta=$_POST["canal_venta"];
$otra_moneda=$_POST["otra_moneda"];
$vendedor=$_POST["vendedor"];
$usar_tc=$_POST["usar_tc"];
//$usuario=$_POST["usuario"];

//$cod_cxc=$_GET["cod_cxc"];
$empresa=$_GET["empresa"];
$otra_moneda_det=$_GET["otra_moneda_det"];
$fechainidet=$_GET["fechainidet"];
$fechafindet=$_GET["fechafindet"];
$nombredet=$_GET["nombredet"];
$totaldet=$_GET["totaldet"];
$concepto_cobro_det=$_GET["concepto_cobro_det"];
$cuenta_concepto_cxc_det=$_GET["cuenta_concepto_cxc_det"];
$cod_contexto_det=$_GET["contexto_det"];
$total_periodo=$_GET["total_periodo"];
$usar_tc_det=$_GET["usar_tc_det"];
$detalle_resumido_det=$_GET["detalle_resumido_det"];
//$usuario_det=$_GET["usuario_det"];
//$n_decimales = 6;
?>
<body>

<?php

$empresaoempleado = substr($nombre, -2);
$nombreemp = substr($nombre, 0, -3);

//si el detalle resumido es si entonces solo agrupar por empresa
if($detalle_resumido == 0) {
	$agrupar = 0;
	$nom_detalle_resumido = 'Si';
} else {
	$nom_detalle_resumido = 'No';
}

if($agrupar == 0) { $nom_agrupar = 'Empresa / Empleado'; }
if($agrupar == 1) { $nom_agrupar = 'Concepto'; }
if($agrupar == 2) { $nom_agrupar = 'Vendedor (solo CxC generadas en notas de venta)'; }

if($saldo_cero == 0) { 
	$nom_saldo_cero = 'Si';
} else {
	$nom_saldo_cero = 'No';
}



//agrupar = 0 por empresa / empleado

if($agrupar == 0) {//if agrupar 0

//Inicio reporte cuentas por cobrar saldo a fecha

if($rep == 6 && $tipo == 1) { // if 2

//nombre otra moneda
$resultotra = mysqli_query($link, "SELECT fldName as otra_moneda
from
actCurrency
where
pkyCurrency = '$otra_moneda' and
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultotra)) {
	$nom_otra_moneda = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);

if($concepto_cobro == 0) { // if concepto cobro
	$nom_concepto_cobro = 'Todos';
	$valor_concepto = ' ';
	$valor_concepto2 = ' ';
} else {
	$resultcon = mysqli_query($link, "select pkyAccountsReceivableConcept as codigo, fldName as nombre
from colAccountsReceivableConcept
where
pkyAccountsReceivableConcept = '$concepto_cobro';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_cobro = $row['codigo'].' - '.$row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto = ' a.codConcept = '. $concepto_cobro .' and ';
	$valor_concepto2 = ' c.codConcept = '. $concepto_cobro .' and ';
}//fin if concepto de cobro

if ($cuenta_concepto_cxc == 0) { // if cuenta concepto cxc
	$nom_cuenta_concepto_cxc = 'Todos';
	$valor_cuenta_concepto_cxc = ' ';
	$valor_cuenta_concepto_cxc2 = ' ';
} else {
	$valor_cuenta_concepto_cxc = ' b.codAccount = ' .$cuenta_concepto_cxc. ' and ';
	$valor_cuenta_concepto_cxc2 = ' e.codAccount = ' .$cuenta_concepto_cxc. ' and ';
	//nombre de la cuenta contable del concepto de cxc
	$result2 = mysqli_query($link, "select pkyAccount, fldName 
							from actAccount 
							where 
							pkyAccount = '$cuenta_concepto_cxc' and
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result2)) {
		$nom_cuenta_concepto_cxc = $row['pkyAccount'].' - '.$row['fldName'];
	}
	mysqli_free_result($result2);
} //fin if cuenta concepto cxc

//restrinjo en el listado de empresas, no en los demas querys
if($canal_venta == 0) { // if canal venta
	$nom_canal_venta = 'Todos';
	$valor_canal_venta1 = ' ';
	$valor_canal_venta2 = ' ';
} else { 
	$result5 = mysqli_query($link, "select pkyChannel as codigo, fldName as canal
						from agnChannel
						where
						pkyChannel = '$canal_venta';");
	while ($row = mysqli_fetch_array($result5)) {   
	$nom_canal_venta = $row['canal'];
	}
	mysqli_free_result($result5);
	$valor_canal_venta1 = ' d.codChannel = '.$canal_venta.' and ';
	$valor_canal_venta2 = ' a.codEmployee = 0 and ';
} // fin if canal venta

//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, segun lo que elijan, antes solo era fecha final del reporte, '$ultimo_tc' as tc, tambien sirve para mostar en la cabecera
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafin' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc = $row['tc'];
	}
	mysqli_free_result($resultom);

$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc';");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

$resulttcdet = mysqli_query($link, "select a.pkyExchangeRateDetail as cod_tc_det, a.codBaseCurrency as cod_mon_target, b.fldName as mon_target, b.txtDescription as nom_mon_target, a.codTargetCurrency as cod_mon_base, c.fldName as mon_base, c.txtDescription as nom_mon_base, a.fldRate as tasa
from
actExchangeRateDetail a, actCurrency b, actCurrency c
where
a.codExchangeRate = '$ultimo_tc' and 
a.codBaseCurrency = '$cod_moneda_principal' and 
a.codBaseCurrency = b.pkyCurrency and 
a.codTargetCurrency = c.pkyCurrency 
order by cod_mon_target, cod_mon_base;");
$ma_tc = array();
$m = 1;
while ($row = mysqli_fetch_array($resulttcdet)) {
	$ma_tc [$m][1] = $row['mon_base'];
	$ma_tc [$m][2] = $row['mon_target'];
	$ma_tc [$m][3] = $row['tasa'];
	$m++;
}
mysqli_free_result($resulttcdet);
$fin_m = $m - 1;

//segun el tc
if($usar_tc == 0) { 
	$nom_usar_tc = 'De Fecha Final';
	$valor_tc = $ultimo_tc.' as tc';
} else {
	$nom_usar_tc = 'De Fecha Transacci&oacute;n';
	$valor_tc = ' a.codExchangeRate as tc';
}

if($cod_contexto == -1){ 
	$nom_contexto = 'Todos';
	$valor_contexto = ' ';
} else {
	$resultcontx = mysqli_query($link, "select pkyContext as cod_contexto, fldName as contexto, codCostCenter as cod_cc 
	from srvContext
	where 
	pkyContext = '$cod_contexto';");
		while ($row = mysqli_fetch_array($resultcontx)) {   
			$nom_contexto = $row['cod_contexto'].' - '.$row['contexto'];
		}
		mysqli_free_result($resultcontx);
	$valor_contexto = ' a.sysContext = '.$cod_contexto.' and ';	
}
/*
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc' and
codBaseCurrency = '$otra_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
$matriz_tc = array();
$i = 1;
while ($row = mysqli_fetch_array($resulttc)) {
	$matriz_tc [$i][1] = $row['codigotc'];//codigo tc
	$matriz_tc [$i][2] = $row['monedabase'];//codigo moneda base
	$matriz_tc [$i][3] = $row['monedacambio'];//codigo moneda cambio
	$matriz_tc [$i][4] = $row['tc'];//valor a multiplicar del tc 
	$i++;
	}
	mysqli_free_result($resulttc);

$fin_om = $i - 1;
*/
if ($empresaoempleado == -1) { // if 2.2
	
	if($nombreemp == 0) {
	$nom_orden = 'Nombre';
	$nom_cliente = 'Empresas';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultcli = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
								from agnCompany
								where
								pkyCompany = '$nombreemp' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultcli)) {
			$nom_cliente = $row['codigo'].' - '.$row['empresa'];
		}
		mysqli_free_result($resultcli);
	$valor_cliente = ' a.codClient = '. $nombreemp .' and ';
	$valor_cliente2 = ' c.codClient = '. $nombreemp .' and ';
	}
		
	//listado de empresas
	$result = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
	from agnCompany
	where 
	sysEnabled = 1 and sysAuthorized = 1
	order by empresa;");
		
	//inicio calculo saldo inicial
	
	//CxC empresas
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
	from(
	select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
	otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
	from
	(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
	t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
	from
	(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
	a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
	from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d
	where
	a.fldDate < '$fechaini' and 
	a.codConcept = b.pkyAccountsReceivableConcept and 
	a.sysEnabled = 1 and a.sysAuthorized = 1 and
	$valor_cliente 
	$valor_concepto 
	$valor_cuenta_concepto_cxc 
	$valor_canal_venta1 
	$valor_contexto 
	a.codClient = d.pkyCompany and 
	a.codClient is not NULL 
	group by cod_cli, cod_moneda, tc) t,
	actExchangeRateDetail r
	where
	t.tc = r.codExchangeRate and
	t.cod_moneda = r.codTargetCurrency and
	t.otra_moneda = r.codBaseCurrency
	union all
	select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
	t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
	from
	(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
	a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
	from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d
	where
	a.fldDate < '$fechaini' and 
	a.codConcept = b.pkyAccountsReceivableConcept and 
	a.sysEnabled = 1 and a.sysAuthorized = 1 and
	$valor_cliente 
	$valor_concepto 
	$valor_cuenta_concepto_cxc 
	$valor_canal_venta1 
	$valor_contexto 
	a.codClient = d.pkyCompany and 
	a.codClient is not NULL 
	group by cod_cli, cod_moneda, tc) t
	where
	t.cod_moneda = t.otra_moneda) otra) final
	group by final.cod_cli
	order by final.cod_cli;");

	//suma Cobros empresas
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
	from(
	select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros,
	otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
	otra.cod_moneda_cxc as cod_moneda_cxc, 
	otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
	otra.suma_cobros * otra.tasa as total
	from
	(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
	t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
	t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
	r.fldRate as tasa
	from
	(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyPayment = b.codPayment and
	a.fldDate < '$fechaini' and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	b.codAccountsReceivable is not null and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
	union all
	select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyCollection = b.codCollection and
	a.fldDate < '$fechaini' and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
	actExchangeRateDetail r
	where
	t.tc = r.codExchangeRate and
	t.cod_moneda_cxc = r.codTargetCurrency and
	t.otra_moneda = r.codBaseCurrency
	union all
	select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
	t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
	t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
	1 as tasa
	from
	(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyPayment = b.codPayment and
	a.fldDate < '$fechaini' and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	b.codAccountsReceivable is not null and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
	union all
	select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyCollection = b.codCollection and
	a.fldDate < '$fechaini' and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
	where
	t.cod_moneda_cxc = t.otra_moneda) otra) final
	group by final.cod_cli
	order by final.cod_cli;");		

$matriz_salini = array();
$i = 1;
while ($row = mysqli_fetch_array($result)) {
	$matriz_salini [$i][1] = $row['codigo'];//cod empresa
	$matriz_salini [$i][2] = $row['empresa'];//nombre empresa
	$matriz_salini [$i][3] = 0; //suma cxc
	$matriz_salini [$i][4] = 0; //suma cobros
	$matriz_salini [$i][5] = 0; //saldo inicial
	$matriz_salini [$i][6] = 0; //suma cxc periodo
	$matriz_salini [$i][7] = 0; //suma cobros periodo
	$matriz_salini [$i][8] = 0; //saldo periodo
	$matriz_salini [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][3] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][4] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][3];
	$reg_cobros = $matriz_salini [$i][4];
	$matriz_salini [$i][5] = $reg_cxc - $reg_cobros;
	$i++;
}
	
//fin calculo saldo inicial

//inicio calculo registros

	//CxC empresas
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
from(
select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d 
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta1 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not NULL 
group by cod_cli, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d 
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta1 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not NULL 
group by cod_cli, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");
	
	//suma Cobros empresas
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
from(
select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros,
 otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
 otra.cod_moneda_cxc as cod_moneda_cxc, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_cobros * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");	

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][6] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][7] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][6];
	$reg_cobros = $matriz_salini [$i][7];
	$matriz_salini [$i][8] = $reg_cxc - $reg_cobros;
	$reg_salini = $matriz_salini [$i][5];
	$reg_periodo = $matriz_salini [$i][8];
	$matriz_salini [$i][9] = $reg_salini + $reg_periodo;
	$i++;
}
	
//fin calculo registros
		?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Cuentas por Cobrar Saldo a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Empresa/Empleado: </b><?php echo $nom_cliente; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro; ?></TD>
        <TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc; ?></TD>
        </TR>
        <TR>
        <TD><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Canal (solo para empresas): </b><?php echo $nom_canal_venta; ?></TD>
		<TD><b>Detalle Resumido (Solo para agrupación por Empresa / Empleado): </b><?php echo $nom_detalle_resumido; ?></TD>
        <TD><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        </TR>
        <TR>
        <TD><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        <TD><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc; ?></TD>
        <TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
		<TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>
</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
    <thead>
    <TR> 
    <TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Empresa</b></TD>
    <TD align="center"><b>CxC Sal. Ini.</b></TD>
    <TD align="center"><b>Cob. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxC Periodo</b></TD>
    <TD align="center"><b>Cobros Periodo</b></TD>
    <TD align="center"><b>Total Periodo</b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda; ?></b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total_cxc = 0;
  $suma_total_cobros = 0;
  $suma_total_ini = 0;
  $suma_total_cxc_per = 0;
  $suma_total_cobros_per = 0;
  $suma_total_periodo = 0;
  $suma_total = 0;
  $j = 1;
  while ($j <= $fin) { //while
	
	while($matriz_salini [$j][3] == 0 && $matriz_salini [$j][4] == 0 && $matriz_salini [$j][5] == 0 && $matriz_salini [$j][6] == 0 && $matriz_salini [$j][7] == 0 && $matriz_salini [$j][8] == 0 && $j <= $fin)
	{ $j++; }
	
	if($j > $fin) { //if ultimo 0
	} else { //else ultimo 0
	
	$codigo = $matriz_salini [$j][1];
	$totaldet = $matriz_salini [$j][5];
	
	if($saldo_cero == 1 && $matriz_salini [$j][9] == 0) { //if saldo cero
	} else { //else saldo cero
	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} else { 
	printf("<tr><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} //cierra if color
	printf("<td align='left'>%s</td>", $matriz_salini [$j][2]);//empresa
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][3],$n_decimales));//CxC saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][4],$n_decimales));// cobros saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][5],$n_decimales));// saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][6],$n_decimales));// suma CxC periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][7],$n_decimales));// suma cobros periodo
	$total_periodo = $matriz_salini [$j][7];
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][8],$n_decimales));// total saldo periodo
	printf("<td align='right'><a href='report.php?rep=6&tipo=2&nombredet=$codigo&empresa=1&fechainidet=$fechaini&fechafindet=$fechafin&totaldet=$totaldet&otra_moneda_det=$otra_moneda&concepto_cobro_det=$concepto_cobro&cuenta_concepto_cxc_det=$cuenta_concepto_cxc&total_periodo=$total_periodo&detalle_resumido_det=$detalle_resumido&usar_tc_det=$usar_tc&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini [$j][9],$n_decimales));//total
	   
	$suma_total_cxc = $suma_total_cxc + $matriz_salini [$j][3];
    $suma_total_cobros = $suma_total_cobros + $matriz_salini [$j][4];
	$suma_total_ini = $suma_total_ini + $matriz_salini [$j][5];
	
    $suma_total_cxc_per = $suma_total_cxc_per + $matriz_salini [$j][6];
    $suma_total_cobros_per = $suma_total_cobros_per + $matriz_salini [$j][7];
	$suma_total_periodo = $suma_total_periodo + $matriz_salini [$j][8];
    
    $suma_total = $suma_total + $matriz_salini [$j][9];
	$color++;
	
	} //fin if saldo cero
	
	} //cierra else ultimo 0
	
    $j++;
}//fin while


?>
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total Cuentas Empresas</b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_ini,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_periodo,$n_decimales)); ?>
</td>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total,$n_decimales)); ?>
</td></tr>
</tbody>
</table>
<?php




	}//fin if 2.2
	
	
	if ($empresaoempleado == -2) { // if 2.3
	
	if($nombreemp == 0) {
	$nom_orden = 'Nombre';
	$nom_cliente = 'Empleados';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultcli = mysqli_query($link, "select pkyPerson as codigo, case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado, 'Empleado' as tipo
								from agnPerson
								where
								pkyPerson = '$nombreemp' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultcli)) {
			$nom_cliente = $row['codigo'].' - '.$row['empleado'];
		}
		mysqli_free_result($resultcli);
	$valor_cliente = ' a.codEmployee = '. $nombreemp .' and ';
	$valor_cliente2 = ' c.codEmployee = '. $nombreemp .' and ';
	}
	
	//listado de empleados
	$result = mysqli_query($link, "select pkyPerson as codigo, 
case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado, 'Empleado' as tipo
from agnPerson
where
sysEnabled = 1 and sysAuthorized = 1
order by empleado;");
	
	//inicio calculo saldo inicial
	//CxC empleados
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
from(
select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate < '$fechaini' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate < '$fechaini' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");
	
	//suma Cobros empleados
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
from(
select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros, 
otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
otra.cod_moneda_cxc as cod_moneda_cxc,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_cobros * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");	
	
	$matriz_salini2 = array();
$i = 1;
while ($row = mysqli_fetch_array($result)) {
	$matriz_salini2 [$i][1] = $row['codigo'];//cod empleado
	$matriz_salini2 [$i][2] = $row['empleado'];//nombre empleado
	$matriz_salini2 [$i][3] = 0; //suma cxc
	$matriz_salini2 [$i][4] = 0; //suma cobros
	$matriz_salini2 [$i][5] = 0; //saldo inicial
	$matriz_salini2 [$i][6] = 0; //suma cxc periodo
	$matriz_salini2 [$i][7] = 0; //suma cobros periodo
	$matriz_salini2 [$i][8] = 0; //saldo periodo
	$matriz_salini2 [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][3] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][4] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini2 [$i][3];
	$reg_cobros = $matriz_salini2 [$i][4];
	$matriz_salini2 [$i][5] = $reg_cxc - $reg_cobros;
	$i++;
}
	
//fin calculo saldo inicial

//inicio calculo registros
	
	//CxC empleados
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
from(
select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");
	
	//suma Cobros empleados
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
from(
select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros, 
otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
otra.cod_moneda_cxc as cod_moneda_cxc,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_cobros * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");	

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][6] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][7] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini2 [$i][6];
	$reg_cobros = $matriz_salini2 [$i][7];
	$matriz_salini2 [$i][8] = $reg_cxc - $reg_cobros;
	$reg_salini = $matriz_salini2 [$i][5];
	$reg_periodo = $matriz_salini2 [$i][8];
	$matriz_salini2 [$i][9] = $reg_salini + $reg_periodo;
	$i++;
}
	
//fin calculo registros
		?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Cuentas por Cobrar Saldo a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Empresa/Empleado: </b><?php echo $nom_cliente; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro; ?></TD>
        <TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        <TD><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        </TR>
        <TR>
        <TD><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc; ?></TD>
		<TD><b>Detalle Resumido (Solo para agrupación por Empresa / Empleado): </b><?php echo $nom_detalle_resumido; ?></TD>
        <TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
		<TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>

</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
    <thead>
    <TR> 
    <TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Empleado</b></TD>
    <TD align="center"><b>CxC Sal. Ini.</b></TD>
    <TD align="center"><b>Cob. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxC Periodo</b></TD>
    <TD align="center"><b>Cobros Periodo</b></TD>
    <TD align="center"><b>Total Periodo</b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda; ?></b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total_cxc2 = 0;
  $suma_total_cobros2 = 0;
  $suma_total_ini2 = 0;
  $suma_total_cxc_per2 = 0;
  $suma_total_cobros_per2 = 0;
  $suma_total_periodo2 = 0;
  $suma_total2 = 0;
  $j = 1;
  while ($j <= $fin) { //while
	
	while($matriz_salini2 [$j][3] == 0 && $matriz_salini2 [$j][4] == 0 && $matriz_salini2 [$j][5] == 0 && $matriz_salini2 [$j][6] == 0 && $matriz_salini2 [$j][7] == 0 && $matriz_salini2 [$j][8] == 0 && $j <= $fin)
	{ $j++; }
	
	if($j > $fin) { //if ultimo 0
	} else { //else ultimo 0
	
	$codigo = $matriz_salini2 [$j][1];
	$totaldet = $matriz_salini2 [$j][5];
	
	if($saldo_cero == 1 && $matriz_salini2 [$j][9] == 0) { //if saldo cero
	} else { //else saldo cero
	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini2 [$j][1]);//cod
	} else { 
	printf("<tr><td align='center'>%s</td>", $matriz_salini2 [$j][1]);//cod
	} //cierra if color
	printf("<td align='left'>%s</td>", $matriz_salini2 [$j][2]);//empresa
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][3],$n_decimales));//CxC saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][4],$n_decimales));// cobros saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][5],$n_decimales));// saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][6],$n_decimales));// suma CxC periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][7],$n_decimales));// suma cobros periodo
	$total_periodo = $matriz_salini2 [$j][7];
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][8],$n_decimales));// total saldo periodo
	printf("<td align='right'><a href='report.php?rep=6&tipo=2&nombredet=$codigo&empresa=0&fechainidet=$fechaini&fechafindet=$fechafin&totaldet=$totaldet&otra_moneda_det=$otra_moneda&concepto_cobro_det=$concepto_cobro&cuenta_concepto_cxc_det=$cuenta_concepto_cxc&total_periodo=$total_periodo&detalle_resumido_det=$detalle_resumido&usar_tc_det=$usar_tc&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini2 [$j][9],$n_decimales));//total
	   
	$suma_total_cxc2 = $suma_total_cxc2 + $matriz_salini2 [$j][3];
    $suma_total_cobros2 = $suma_total_cobros2 + $matriz_salini2 [$j][4];
	$suma_total_ini2 = $suma_total_ini2 + $matriz_salini2 [$j][5];
	
    $suma_total_cxc_per2 = $suma_total_cxc_per2 + $matriz_salini2 [$j][6];
    $suma_total_cobros_per2 = $suma_total_cobros_per2 + $matriz_salini2 [$j][7];
	$suma_total_periodo2 = $suma_total_periodo2 + $matriz_salini2 [$j][8];
    
    $suma_total2 = $suma_total2 + $matriz_salini2 [$j][9];
	$color++;
	
	} //fin if saldo cero
	
	} //cierra else ultimo 0
	
    $j++;
}//fin while

?>
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total Cuentas Empleados</b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_ini2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc_per2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros_per2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_periodo2,$n_decimales)); ?>
</td>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total2,$n_decimales)); ?>
</td></tr>
</tbody>
</table>
		
<?php
	}//fin if 2.3
	
	
		
	if ($empresaoempleado == -3) { // if 2.4
	
	$nom_orden = 'Nombre';
	$nom_cliente = 'Todos';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
	
	//listado de empresas
	$result = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
	from agnCompany
	where
	sysEnabled = 1 and sysAuthorized = 1
	order by empresa;");
		
	//inicio calculo saldo inicial
	
	//CxC empresas
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
	from(
	select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
	otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
	from
	(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
	t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
	from
	(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
	a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
	from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d
	where
	a.fldDate < '$fechaini' and 
	a.codConcept = b.pkyAccountsReceivableConcept and 
	a.sysEnabled = 1 and a.sysAuthorized = 1 and
	$valor_cliente 
	$valor_concepto 
	$valor_cuenta_concepto_cxc 
	$valor_canal_venta1 
	$valor_contexto 
	a.codClient = d.pkyCompany and 
	a.codClient is not NULL 
	group by cod_cli, cod_moneda, tc) t,
	actExchangeRateDetail r
	where
	t.tc = r.codExchangeRate and
	t.cod_moneda = r.codTargetCurrency and
	t.otra_moneda = r.codBaseCurrency
	union all
	select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
	t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
	from
	(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
	a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
	from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d
	where
	a.fldDate < '$fechaini' and 
	a.codConcept = b.pkyAccountsReceivableConcept and 
	a.sysEnabled = 1 and a.sysAuthorized = 1 and
	$valor_cliente 
	$valor_concepto 
	$valor_cuenta_concepto_cxc 
	$valor_canal_venta1 
	$valor_contexto 
	a.codClient = d.pkyCompany and 
	a.codClient is not NULL 
	group by cod_cli, cod_moneda, tc) t
	where
	t.cod_moneda = t.otra_moneda) otra) final
	group by final.cod_cli
	order by final.cod_cli;");

	//suma Cobros empresas
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
	from(
	select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros,
	otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
	otra.cod_moneda_cxc as cod_moneda_cxc, 
	otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
	otra.suma_cobros * otra.tasa as total
	from
	(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
	t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
	t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
	r.fldRate as tasa
	from
	(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyPayment = b.codPayment and
	a.fldDate < '$fechaini' and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	b.codAccountsReceivable is not null and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
	union all
	select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyCollection = b.codCollection and
	a.fldDate < '$fechaini' and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
	actExchangeRateDetail r
	where
	t.tc = r.codExchangeRate and
	t.cod_moneda_cxc = r.codTargetCurrency and
	t.otra_moneda = r.codBaseCurrency
	union all
	select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
	t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
	t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
	1 as tasa
	from
	(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyPayment = b.codPayment and
	a.fldDate < '$fechaini' and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	b.codAccountsReceivable is not null and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
	union all
	select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
	a.codCurrency as cod_moneda_cobro, $valor_tc, 
	c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
	from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
	where
	a.pkyCollection = b.codCollection and
	a.fldDate < '$fechaini' and
	b.codAccountsReceivable = c.pkyAccountsReceivable and
	$valor_cliente2 
	$valor_concepto2 
	$valor_cuenta_concepto_cxc2 
	$valor_canal_venta1 
	$valor_contexto 
	c.codConcept = e.pkyAccountsReceivableConcept and 
	a.codClient = d.pkyCompany and 
	a.codClient is not null and 
	a.sysEnabled = 1 and a.sysAuthorized = 1
	group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
	where
	t.cod_moneda_cxc = t.otra_moneda) otra) final
	group by final.cod_cli
	order by final.cod_cli;");		

$matriz_salini = array();
$i = 1;
while ($row = mysqli_fetch_array($result)) {
	$matriz_salini [$i][1] = $row['codigo'];//cod empresa
	$matriz_salini [$i][2] = $row['empresa'];//nombre empresa
	$matriz_salini [$i][3] = 0; //suma cxc
	$matriz_salini [$i][4] = 0; //suma cobros
	$matriz_salini [$i][5] = 0; //saldo inicial
	$matriz_salini [$i][6] = 0; //suma cxc periodo
	$matriz_salini [$i][7] = 0; //suma cobros periodo
	$matriz_salini [$i][8] = 0; //saldo periodo
	$matriz_salini [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][3] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][4] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][3];
	$reg_cobros = $matriz_salini [$i][4];
	$matriz_salini [$i][5] = $reg_cxc - $reg_cobros;
	$i++;
}
	
//fin calculo saldo inicial

//inicio calculo registros

	//CxC empresas
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
from(
select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta1 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not NULL 
group by cod_cli, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codClient as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b, agnCompany d
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta1 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not NULL 
group by cod_cli, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");
	
	//suma Cobros empresas
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
from(
select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros,
 otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
 otra.cod_moneda_cxc as cod_moneda_cxc, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_cobros * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codClient as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, agnCompany d, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta1 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");	

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][6] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][7] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][6];
	$reg_cobros = $matriz_salini [$i][7];
	$matriz_salini [$i][8] = $reg_cxc - $reg_cobros;
	$reg_salini = $matriz_salini [$i][5];
	$reg_periodo = $matriz_salini [$i][8];
	$matriz_salini [$i][9] = $reg_salini + $reg_periodo;
	$i++;
}
	
//fin calculo registros

?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Cuentas por Cobrar Saldo a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Empresa/Empleado: </b><?php echo $nom_cliente; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro; ?></TD>
        <TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc; ?></TD>
        </TR>
        <TR>
        <TD><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Canal (solo para empresas): </b><?php echo $nom_canal_venta; ?></TD>
		<TD><b>Detalle Resumido (Solo para agrupación por Empresa / Empleado): </b><?php echo $nom_detalle_resumido; ?></TD>
        <TD><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        </TR>
        <TR>
        <TD><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        <TD><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc; ?></TD>
        <TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
		<TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>

</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
    <thead>
    <TR> 
    <TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Empresa / Empleado</b></TD>
    <TD align="center"><b>CxC Sal. Ini.</b></TD>
    <TD align="center"><b>Cob. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxC Periodo</b></TD>
    <TD align="center"><b>Cobros Periodo</b></TD>
    <TD align="center"><b>Total Periodo</b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda; ?></b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total_cxc = 0;
  $suma_total_cobros = 0;
  $suma_total_ini = 0;
  $suma_total_cxc_per = 0;
  $suma_total_cobros_per = 0;
  $suma_total_periodo = 0;
  $suma_total = 0;
  $j = 1;
  while ($j <= $fin) { //while
	
	while($matriz_salini [$j][3] == 0 && $matriz_salini [$j][4] == 0 && $matriz_salini [$j][5] == 0 && $matriz_salini [$j][6] == 0 && $matriz_salini [$j][7] == 0 && $matriz_salini [$j][8] == 0 && $j <= $fin)
	{ $j++; }
	
	if($j > $fin) { //if ultimo 0
	} else { //else ultimo 0
	
	$codigo = $matriz_salini [$j][1];
	$totaldet = $matriz_salini [$j][5];
	
	if($saldo_cero == 1 && $matriz_salini [$j][9] == 0) { //if saldo cero
	} else { //else saldo cero
	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} else { 
	printf("<tr><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} //cierra if color
	printf("<td align='left'>%s</td>", $matriz_salini [$j][2]);//empresa
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][3],$n_decimales));//CxC saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][4],$n_decimales));// cobros saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][5],$n_decimales));// saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][6],$n_decimales));// suma CxC periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][7],$n_decimales));// suma cobros periodo
	$total_periodo = $matriz_salini [$j][7];
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][8],$n_decimales));// total saldo periodo
	printf("<td align='right'><a href='report.php?rep=6&tipo=2&nombredet=$codigo&empresa=1&fechainidet=$fechaini&fechafindet=$fechafin&totaldet=$totaldet&otra_moneda_det=$otra_moneda&concepto_cobro_det=$concepto_cobro&cuenta_concepto_cxc_det=$cuenta_concepto_cxc&total_periodo=$total_periodo&detalle_resumido_det=$detalle_resumido&usar_tc_det=$usar_tc&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini [$j][9],$n_decimales));//total
	   
	$suma_total_cxc = $suma_total_cxc + $matriz_salini [$j][3];
    $suma_total_cobros = $suma_total_cobros + $matriz_salini [$j][4];
	$suma_total_ini = $suma_total_ini + $matriz_salini [$j][5];
	
    $suma_total_cxc_per = $suma_total_cxc_per + $matriz_salini [$j][6];
    $suma_total_cobros_per = $suma_total_cobros_per + $matriz_salini [$j][7];
	$suma_total_periodo = $suma_total_periodo + $matriz_salini [$j][8];
    
    $suma_total = $suma_total + $matriz_salini [$j][9];
	$color++;
	
	} //fin if saldo cero
	
	} //cierra else ultimo 0
	
    $j++;
}//fin while


?>
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total Cuentas Empresas</b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_ini,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_periodo,$n_decimales)); ?>
</td>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total,$n_decimales)); ?>
</td></tr>
<?php
	//listado de empleados
	$result = mysqli_query($link, "select pkyPerson as codigo, 
case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado
from agnPerson
where
sysEnabled = 1 and sysAuthorized = 1
order by empleado;");
	
	//inicio calculo saldo inicial
	//CxC empleados
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
from(
select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate < '$fechaini' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta2 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate < '$fechaini' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta2 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");
	
	//suma Cobros empleados
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
from(
select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros, 
otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
otra.cod_moneda_cxc as cod_moneda_cxc,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_cobros * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");	
	
	$matriz_salini2 = array();
$i = 1;
while ($row = mysqli_fetch_array($result)) {
	$matriz_salini2 [$i][1] = $row['codigo'];//cod empleado
	$matriz_salini2 [$i][2] = $row['empleado'];//nombre empleado
	$matriz_salini2 [$i][3] = 0; //suma cxc
	$matriz_salini2 [$i][4] = 0; //suma cobros
	$matriz_salini2 [$i][5] = 0; //saldo inicial
	$matriz_salini2 [$i][6] = 0; //suma cxc periodo
	$matriz_salini2 [$i][7] = 0; //suma cobros periodo
	$matriz_salini2 [$i][8] = 0; //saldo periodo
	$matriz_salini2 [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][3] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][4] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini2 [$i][3];
	$reg_cobros = $matriz_salini2 [$i][4];
	$matriz_salini2 [$i][5] = $reg_cxc - $reg_cobros;
	$i++;
}
	
//fin calculo saldo inicial

//inicio calculo registros
	
	//CxC empleados
	$result3 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as cxc
from(
select otra.cod_cli as cod_cli, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta2 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codEmployee as cod_cli, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_canal_venta2 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_cli, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");
	
	//suma Cobros empleados
	$result5 = mysqli_query($link, "select final.cod_cli as cod_cli, sum(final.total) as suma_cobros
from(
select otra.cod_cli as cod_cli, otra.suma_cobros as suma_cobros, 
otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
otra.cod_moneda_cxc as cod_moneda_cxc,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_cobros * otra.tasa as total
from
(select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_cli as cod_cli, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select a.codEmployee as cod_cli, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_canal_venta2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.codEmployee is not null and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_cli, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_cli
order by final.cod_cli;");	

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][6] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_emp = $row['cod_cli'];
	while ($cod_emp <> $matriz_salini2 [$i][1]) {
		$i++;
	}
	$matriz_salini2 [$i][7] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini2 [$i][6];
	$reg_cobros = $matriz_salini2 [$i][7];
	$matriz_salini2 [$i][8] = $reg_cxc - $reg_cobros;
	$reg_salini = $matriz_salini2 [$i][5];
	$reg_periodo = $matriz_salini2 [$i][8];
	$matriz_salini2 [$i][9] = $reg_salini + $reg_periodo;
	$i++;
}
	
//fin calculo registros

$color = 2;
  $suma_total_cxc2 = 0;
  $suma_total_cobros2 = 0;
  $suma_total_ini2 = 0;
  $suma_total_cxc_per2 = 0;
  $suma_total_cobros_per2 = 0;
  $suma_total_periodo2 = 0;
  $suma_total2 = 0;
  $j = 1;
  while ($j <= $fin) { //while
	
	while($matriz_salini2 [$j][3] == 0 && $matriz_salini2 [$j][4] == 0 && $matriz_salini2 [$j][5] == 0 && $matriz_salini2 [$j][6] == 0 && $matriz_salini2 [$j][7] == 0 && $matriz_salini2 [$j][8] == 0 && $j <= $fin)
	{ $j++; }
	
	if($j > $fin) { //if ultimo 0
	} else { //else ultimo 0
	
	$codigo = $matriz_salini2 [$j][1];
	$totaldet = $matriz_salini2 [$j][5];
	
	if($saldo_cero == 1 && $matriz_salini2 [$j][9] == 0) { //if saldo cero
	} else { //else saldo cero
	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini2 [$j][1]);//cod
	} else { 
	printf("<tr><td align='center'>%s</td>", $matriz_salini2 [$j][1]);//cod
	} //cierra if color
	printf("<td align='left'>%s</td>", $matriz_salini2 [$j][2]);//empresa
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][3],$n_decimales));//CxC saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][4],$n_decimales));// cobros saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][5],$n_decimales));// saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][6],$n_decimales));// suma CxC periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][7],$n_decimales));// suma cobros periodo
	$total_periodo = $matriz_salini2 [$j][7];
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][8],$n_decimales));// total saldo periodo
	printf("<td align='right'><a href='report.php?rep=6&tipo=2&nombredet=$codigo&empresa=0&fechainidet=$fechaini&fechafindet=$fechafin&totaldet=$totaldet&otra_moneda_det=$otra_moneda&concepto_cobro_det=$concepto_cobro&cuenta_concepto_cxc_det=$cuenta_concepto_cxc&total_periodo=$total_periodo&detalle_resumido_det=$detalle_resumido&usar_tc_det=$usar_tc&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini2 [$j][9],$n_decimales));//total
	   
	$suma_total_cxc2 = $suma_total_cxc2 + $matriz_salini2 [$j][3];
    $suma_total_cobros2 = $suma_total_cobros2 + $matriz_salini2 [$j][4];
	$suma_total_ini2 = $suma_total_ini2 + $matriz_salini2 [$j][5];
	
    $suma_total_cxc_per2 = $suma_total_cxc_per2 + $matriz_salini2 [$j][6];
    $suma_total_cobros_per2 = $suma_total_cobros_per2 + $matriz_salini2 [$j][7];
	$suma_total_periodo2 = $suma_total_periodo2 + $matriz_salini2 [$j][8];
    
    $suma_total2 = $suma_total2 + $matriz_salini2 [$j][9];
	$color++;
	
	} //fin if saldo cero
	
	} //cierra else ultimo 0
	
    $j++;
}//fin while

$suma_total_cxc3 = $suma_total_cxc + $suma_total_cxc2;
$suma_total_cobros3 = $suma_total_cobros + $suma_total_cobros2;
$suma_total_ini3 = $suma_total_ini + $suma_total_ini2;
$suma_total_cxc_per3 = $suma_total_cxc_per + $suma_total_cxc_per2;
$suma_total_cobros_per3 = $suma_total_cobros_per + $suma_total_cobros_per2;
$suma_total_periodo3 = $suma_total_periodo + $suma_total_periodo2;  
$suma_total3 = $suma_total + $suma_total2;

?>
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total Cuentas Empleados</b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_ini2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc_per2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros_per2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_periodo2,$n_decimales)); ?>
</td>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total2,$n_decimales)); ?>
</td></tr>
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total Cuentas Empresas y Empleados</b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc3,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros3,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_ini3,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc_per3,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros_per3,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_periodo3,$n_decimales)); ?>
</td>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total3,$n_decimales)); ?>
</td></tr>
</tbody>
</table>
<?php 
	}//fin if 2.4
	
} //fin if 2

} //fin if agrupar 0



// inicio muestra detalle agrupado por Empresa/Empleado 
// el detalle esta fuera del agrupar porque no puedo enviar por POST y GET la variable agrupar 

if($rep == 6 && $tipo == 2) { // if 3

//nombre otra moneda
$resultotra = mysqli_query($link, "SELECT fldName as otra_moneda
from
actCurrency
where
pkyCurrency = '$otra_moneda_det' and
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultotra)) {
	$nom_otra_moneda_det = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);


//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, segun lo que elijan, antes solo era fecha final del reporte, '$ultimo_tc' as tc, tambien sirve para mostar en la cabecera
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafindet' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc_det = $row['tc'];
	}
	mysqli_free_result($resultom);

$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc_det';");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

$resulttcdet = mysqli_query($link, "select a.pkyExchangeRateDetail as cod_tc_det, a.codBaseCurrency as cod_mon_target, b.fldName as mon_target, b.txtDescription as nom_mon_target, a.codTargetCurrency as cod_mon_base, c.fldName as mon_base, c.txtDescription as nom_mon_base, a.fldRate as tasa
from
actExchangeRateDetail a, actCurrency b, actCurrency c
where
a.codExchangeRate = '$ultimo_tc_det' and 
a.codBaseCurrency = '$cod_moneda_principal' and 
a.codBaseCurrency = b.pkyCurrency and 
a.codTargetCurrency = c.pkyCurrency 
order by cod_mon_target, cod_mon_base;");
$ma_tc = array();
$m = 1;
while ($row = mysqli_fetch_array($resulttcdet)) {
	$ma_tc [$m][1] = $row['mon_base'];
	$ma_tc [$m][2] = $row['mon_target'];
	$ma_tc [$m][3] = $row['tasa'];
	$m++;
}
mysqli_free_result($resulttcdet);
$fin_m = $m - 1;

//segun el tc
if($usar_tc_det == 0) { 
	$nom_usar_tc_det = 'De Fecha Final';
	$valor_tc_det = $ultimo_tc_det.' as tc';
} else {
	$nom_usar_tc_det = 'De Fecha Transacci&oacute;n';
	$valor_tc_det = ' a.codExchangeRate as tc';
}
/*
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc_det' and
codBaseCurrency = '$otra_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
$matriz_tc = array();
$i = 1;
while ($row = mysqli_fetch_array($resulttc)) {
	$matriz_tc [$i][1] = $row['codigotc'];//codigo tc
	$matriz_tc [$i][2] = $row['monedabase'];//codigo moneda base
	$matriz_tc [$i][3] = $row['monedacambio'];//codigo moneda cambio
	$matriz_tc [$i][4] = $row['tc'];//valor a multiplicar del tc 
	$i++;
	}
	mysqli_free_result($resulttc);

$fin_om = $i - 1;
*/
//si el detalle resumido es si entonces solo agrupar por empresa
if($detalle_resumido_det == 0) {
	$nom_detalle_resumido_det = 'Si';
} else {
	$nom_detalle_resumido_det = 'No';
}

if($concepto_cobro_det == 0) { // if concepto cobro
	$nom_concepto_cobro_det = 'Todos';
	$valor_concepto_det = ' ';
	$valor_concepto2_det = ' ';
} else {
	$resultcon = mysqli_query($link, "select pkyAccountsReceivableConcept as codigo, fldName as nombre
from colAccountsReceivableConcept
where
pkyAccountsReceivableConcept = '$concepto_cobro_det';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_cobro_det = $row['codigo'].' - '.$row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto_det = ' a.codConcept = '. $concepto_cobro_det .' and ';
	$valor_concepto2_det = ' g.codConcept = '. $concepto_cobro_det .' and ';
}//fin if concepto de cobro

if ($cuenta_concepto_cxc_det == 0) { // if 2.3.1
	$nom_cuenta_concepto_cxc_det = 'Todos';
	$valor_cuenta_concepto_cxc_det = ' ';
	$valor_cuenta_concepto_cxc2_det = ' ';
	$valor_cuenta_concepto_cxc3_det = ' ';
} else {
	$valor_cuenta_concepto_cxc_det = ' b.codAccount = ' .$cuenta_concepto_cxc_det. ' and ';
	$valor_cuenta_concepto_cxc2_det = ' e.codAccount = ' .$cuenta_concepto_cxc_det. ' and ';
	$valor_cuenta_concepto_cxc3_det = ' i.codAccount = ' .$cuenta_concepto_cxc_det. ' and ';
	//nombre de la cuenta contable del concepto de cxc
	$result2 = mysqli_query($link, "select pkyAccount, fldName 
							from actAccount 
							where 
							pkyAccount = '$cuenta_concepto_cxc_det' and
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result2)) {
		$nom_cuenta_concepto_cxc_det = $row['pkyAccount'].' - '.$row['fldName'];
	}
	mysqli_free_result($result2);
} //fin if 2.3.1

if($cod_contexto_det == -1){ 
	$nom_contexto_det = 'Todos';
	$valor_contexto_det = ' ';
} else {
	$resultcontx = mysqli_query($link, "select pkyContext as cod_contexto, fldName as contexto, codCostCenter as cod_cc 
	from srvContext
	where 
	pkyContext = '$cod_contexto_det';");
		while ($row = mysqli_fetch_array($resultcontx)) {   
			$nom_contexto_det = $row['cod_contexto'].' - '.$row['contexto'];
		}
		mysqli_free_result($resultcontx);
	$valor_contexto_det = ' a.sysContext = '.$cod_contexto_det.' and ';	
}


 if($empresa == 1) { //if 3.1
  
 // detalle empresa
  $result = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
from agnCompany
where
pkyCompany = '$nombredet' and
sysEnabled = 1 and sysAuthorized = 1;");
 
while ($row = mysqli_fetch_array($result)) {
	$nomempdet = $row['codigo'].' - '.$row['empresa'];
}
mysqli_free_result($result);

 $result2 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via as via_cobro, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cxc as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cobro as fecha_cobro, otro.concepto as concepto, otro.concepto_ingreso as concepto_ingreso, otro.via as via, otro.empresa as empresa, otro.moneda as moneda, otro.glosa as glosa, otro.cxc as cxc,
otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cxc as total, otro.papa as papa, otro.cod_papa as cod_papa
from (
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c, agnCompany d, actCurrency f
where 
$valor_concepto_det 
$valor_cuenta_concepto_cxc_det 
$valor_contexto_det 
a.codClient = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c, agnCompany d, actCurrency f
where 
$valor_concepto_det 
$valor_cuenta_concepto_cxc_det 
$valor_contexto_det 
a.codClient = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda = t.otra_moneda) otro) final
order by final.fecha, final.codigo;");

 ?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario_det; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Detalle Cuentas por Cobrar a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Empresa: </b><?php echo $nomempdet; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro_det; ?></TD>
        <TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc_det; ?></TD>
		<TD width="25%"><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
        </TR>
        <TR>
        <TD><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></TD>
        <TD><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc_det; ?></TD>
		<TD><b>Detalle Resumido (Solo para agrupación por Empresa / Empleado): </b><?php echo $nom_detalle_resumido_det; ?></TD>
        <TD><b>Expresado en: </b><?php echo $nom_otra_moneda_det; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc_det == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc_det; ?>&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc_det; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>

</tr>
</table>
<br />

<?php
	//detalle resumido no = 1
	if($detalle_resumido_det == 1) { //if detalle 0
?>

		<table border="1" align="center" cellpadding="2" width="100%">
			<TR BGCOLOR='#ffcccc'> 
			<TD align="left" colspan="15"><b>Saldo inicial en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="right"><b><?php echo number_format($totaldet,$n_decimales); ?></b></TD></TR> 
			<thead>
			<TR> 
			<TD align="center"><b>Tipo</b></TD>
			<TD align="center"><b>Cod.</b></TD>
			<TD align="center"><b>Nro. Doc.</b></TD>
			<TD align="center" width="65"><b>Fecha</b></TD>
			<TD align="center" width="65"><b>Fecha Cobro</b></TD>
			<TD align="center"><b>Concepto</b></TD>
			<TD align="center"><b>Concepto Ingreso</b></TD>
			<TD align="center"><b>Via Cobro</b></TD>
			<TD align="center"><b>Glosa</b></TD>
			<TD align="center"><b>Gen. Por</b></TD>
			<TD align="center"><b>Mon.</b></TD>
			<TD align="center"><b>Monto</b></TD>
			<TD align="center"><b>Tasa</b></TD>
			<TD align="center"><b>D&eacute;bito en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="center"><b>Cr&eacute;dito en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="center"><b>Saldo en <?php echo $nom_otra_moneda_det; ?></b></TD>
			</TR>
			</thead>
			<tbody class="marcafila">

		<?php
		$color = 2;
		$suma_total = 0;
		$suma_periodo = 0;
		$suma_deb = 0;
		$suma_cred = 0;
		//esta matriz guarda el codigo de la cxc para mostrar los cobros que se hicieron en el periodo y no tienen cxc asociada
		$v = 1;
		$matriz_verif = array();
		while ($row = mysqli_fetch_array($result2)) { //while
			//para enlazar al que genero el asiento
			$papa_componente = $row['papa'];
			$papa_codigo = $row['cod_papa'];
			$usuario = $usuario_det;
			include "../../generadopor.php";
			
			$codigo_det = $row['codigo'];	
			if($color % 2 == 0) { //if color
			printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
			} else {
			printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
			}
			printf("<td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $row['codigo']);//cod
			printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
			printf("<td align='center'>%s</td>", $row['fecha']);//fecha
			printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
			printf("<td>%s</td>", $row['concepto']);//concepto viene de los parametros
			printf("<td>%s</td>", $row['concepto_ingreso']);//concepto ingreso
			printf("<td>%s</td>", $row['via_cobro']);//via cobro
			//printf("<td>%s</td>", $row['empresa']);//empresa
			printf("<td>%s</td>", $row['glosa']);//glosa
			printf("<td align='center'>%s</td>", $papa_enlace);//gen por
			printf("<td>%s</td>", $row['moneda']);//moneda
			if($row['total'] >= 0) {
				printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
			} else {
				printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
			}
			printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
			
			if($row['total_om'] >= 0) {
				printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
				printf("<td>&nbsp;</td>");//total otra moneda credito
				$suma_deb = $suma_deb + $row['total_om'];
			} else {
				printf("<td>&nbsp;</td>");//total otra moneda debito
				printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
				$suma_cred = $suma_cred + $row['total_om'];
			}
			
			//$suma_periodo = $suma_periodo + $row['total_om'];
			$total_cxc = $row['total_om'];
			//$suma_saldo = $suma_saldo + $total_cxc;
			$suma_saldo = $total_cxc;
			printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));
			$color++;
			$matriz_verif[$v][1] = $row['codigo'];
			$v++;
			
			$result3 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cob_pag as fecha_cobro, final.concepto as concepto, final.con_ing_egr as concepto_ingreso, final.via_cobro as via_cobro, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
		from
		(
		select otro.codigo as codigo, otro.nrodoc as nrodoc, 
		otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, 
		otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, 
		otro.via_cobro as via_cobro, otro.empresa as empresa, 
		otro.moneda_cxc as moneda, otro.glosa as glosa, 
		otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
		otro.otra_moneda as otra_moneda, 
		otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
		otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa
		from 
		(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
		t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
		t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
		t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
		t.empresa as empresa, 
		t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
		t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
		t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
		r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
		from 
		(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where 
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		g.pkyAccountsReceivable = '$codigo_det' and 
		a.codRoute = c.pkyCollectionRoute and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		a.pkyCollection = b.codCollection and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1
		union all
		select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		g.pkyAccountsReceivable = '$codigo_det' and 
		a.pkyPayment = b.codPayment and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		b.codAccountsReceivable is not NULL and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1) t,
		actExchangeRateDetail r
		where
		t.tc = r.codExchangeRate and
		t.cod_moneda_cxc = r.codTargetCurrency and
		t.otra_moneda = r.codBaseCurrency

		union all

		select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
		t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
		t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
		t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
		t.empresa as empresa, 
		t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
		t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
		t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
		1 as tasa, t.papa as papa, t.cod_papa as cod_papa
		from 
		(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		g.pkyAccountsReceivable = '$codigo_det' and 
		a.codRoute = c.pkyCollectionRoute and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		a.pkyCollection = b.codCollection and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1
		union all
		select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where 
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		g.pkyAccountsReceivable = '$codigo_det' and 
		a.pkyPayment = b.codPayment and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		b.codAccountsReceivable is not NULL and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1) t
		where
		t.cod_moneda_cxc = t.otra_moneda) otro) final
		order by final.fecha, final.codigo;");
			$color2 = $color;
			$suma_det = 0;
			while ($row = mysqli_fetch_array($result3)) {//while 3
				//para enlazar al que genero el asiento
				$papa_componente = $row['papa'];
				$papa_codigo = $row['cod_papa'];
				$usuario = $usuario_det;
				include "../../generadopor.php";
				
				$cod_cobro = $row['codigo'];
				$tipo2 = $row['via_cobro'];
				if($color2 % 2 == 0) { //if color
				printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
				} else {
				printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
				}
				
				if($tipo2 == 'Liquidacion') {//if liquidacion
					printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
				} else {//else liquidacion
					printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
				}//fin if liquidacion
				
				printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
				printf("<td align='center'>%s</td>", $row['fecha']);//fecha
				printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
				printf("<td>%s</td>", $row['concepto']);//concepto 
				printf("<td>%s</td>", $row['concepto_ingreso']);//concepto cobro
				printf("<td>%s</td>", $row['via_cobro']);//via cobro
				//printf("<td>%s</td>", $row['empresa']);//empresa
				printf("<td>%s</td>", $row['glosa']);//glosa
				printf("<td align='center'>%s</td>", $papa_enlace);//gen por
				printf("<td>%s</td>", $row['moneda']);//moneda
				if($row['total'] >= 0) {
				printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
				} else {
				printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
				}
				printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
				
				if($row['total_om'] >= 0) {
				printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
				printf("<td>&nbsp;</td>");//total otra moneda credito
				$suma_deb = $suma_deb + $row['total_om'];
				} else {
				printf("<td>&nbsp;</td>");//total otra moneda debito
				printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
				$suma_cred = $suma_cred + $row['total_om'];
				}
				$suma_det = $suma_det + $row['total_om'];
				$suma_saldo = $suma_saldo + $row['total_om'];
				printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
				$color2++;
			}//fin while 3
			mysqli_free_result($result3);
			
			if(($total_cxc + $suma_det) > 0) {
			printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='13'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
			printf("<td align='right'><b>%s</b></td>", number_format($total_cxc + $suma_det,$n_decimales));//total cuenta
			printf("<td>&nbsp;</td>");//espacio al final
			} else {
			printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='14'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
			printf("<td align='right'><b>%s</b></td>", number_format(($total_cxc + $suma_det)*-1,$n_decimales));//total cuenta
			}
				
			printf("<td>&nbsp;</td></tr>");//espacio al final
				
			$suma_periodo = $suma_periodo + $total_cxc + $suma_det;
		}//fin while
		mysqli_free_result($result2);
		$suma_total = $suma_periodo + $totaldet; 

		//verificacion si existe un cobro que no tenga cxc en ese periodo total_periodo viene del link
			if($total_periodo != 0) {//if total periodo
			$cadena_no = '';
			for($w = 1; $w < $v; $w++) { 
				$cadena_no = $cadena_no . $matriz_verif[$w][1].',';
			}
			
			if($cadena_no != '') {
			$cadena_no = ' where final.cod_cxc not in ('.substr($cadena_no,0,-1).')';
			} else {
			$cadena_no = ' ';	
			}
			

		$result3 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cob_pag as fecha_cobro, final.concepto as concepto, final.con_ing_egr as concepto_ingreso, final.via_cobro as via_cobro, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
		from
		(
		select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, otro.via_cobro as via_cobro, otro.empresa as empresa, otro.moneda_cxc as moneda, otro.glosa as glosa, otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, otro.papa as papa, otro.cod_papa as cod_papa
		from 
		(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
		t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
		t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
		t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
		t.empresa as empresa, 
		t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
		t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
		t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
		r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
		from 
		(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where 
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		a.codRoute = c.pkyCollectionRoute and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		a.pkyCollection = b.codCollection and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1
		union all
		select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where 
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		a.pkyPayment = b.codPayment and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		b.codAccountsReceivable is not NULL and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1) t,
		actExchangeRateDetail r
		where
		t.tc = r.codExchangeRate and
		t.cod_moneda_cxc = r.codTargetCurrency and
		t.otra_moneda = r.codBaseCurrency

		union all

		select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
		t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
		t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
		t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
		t.empresa as empresa, 
		t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
		t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
		t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
		1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
		from 
		(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where 
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		a.codRoute = c.pkyCollectionRoute and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		a.pkyCollection = b.codCollection and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1
		union all
		select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
		a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
		null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
		g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
		f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
		'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
		a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from
		payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
		actCurrency f, colAccountsReceivable g, actCurrency h
		where 
		$valor_concepto2_det 
		$valor_cuenta_concepto_cxc2_det 
		$valor_contexto_det 
		g.codConcept = e.pkyAccountsReceivableConcept and 
		a.codClient = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and 
		a.pkyPayment = b.codPayment and
		a.codClient = d.pkyCompany and
		a.codCurrency = f.pkyCurrency and
		g.codCurrency = h.pkyCurrency and
		b.codAccountsReceivable is not NULL and
		b.codAccountsReceivable = g.pkyAccountsReceivable and
		a.sysEnabled = 1 and a.sysAuthorized = 1) t
		where
		t.cod_moneda_cxc = t.otra_moneda) otro) final 
		$cadena_no  
		order by final.fecha, final.codigo;");
		$color3 = $color2;
		$suma_det_solo = 0;
		$control_hay_cobros = 0;

			while ($row = mysqli_fetch_array($result3)) {//while 3

				if($control_hay_cobros == 0){
					printf("<tr BGCOLOR='#C8E6C'><td align='left' colspan='16'><b>Cobros de cuentas que no aparecen en el periodo</b></td></tr>");
					$control_hay_cobros++;
				}

				//para enlazar al que genero el asiento
				$papa_componente = $row['papa'];
				$papa_codigo = $row['cod_papa'];
				$usuario = $usuario_det;
				include "../../generadopor.php";
				
				$cod_cobro = $row['codigo'];
				$tipo2 = $row['via_cobro'];
				if($color3 % 2 == 0) { //if color
				printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
				} else {
				printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
				}
				
				if($tipo2 == 'Liquidacion') {//if liquidacion
					printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
				} else {//else liquidacion
					printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
				}//fin if liquidacion
				
				printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
				printf("<td align='center'>%s</td>", $row['fecha']);//fecha
				printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
				printf("<td>%s</td>", $row['concepto']);//concepto 
				printf("<td>%s</td>", $row['concepto_ingreso']);//concepto cobro
				printf("<td>%s</td>", $row['via_cobro']);//via cobro
				//printf("<td>%s</td>", $row['empresa']);//empresa
				printf("<td>%s</td>", $row['glosa']);//glosa
				printf("<td align='center'>%s</td>", $papa_enlace);//gen por
				printf("<td>%s</td>", $row['moneda']);//moneda
				if($row['total'] >= 0) {
				printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
				} else {
				printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
				}
				printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
				
				if($row['total_om'] >= 0) {
				printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
				printf("<td>&nbsp;</td>");//total otra moneda credito
				$suma_deb = $suma_deb + $row['total_om'];
				} else {
				printf("<td>&nbsp;</td>");//total otra moneda debito
				printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
				$suma_cred = $suma_cred + $row['total_om'];
				}
				$suma_det_solo = $suma_det_solo + $row['total_om'];
				$suma_saldo = $suma_saldo + $row['total_om'];
				printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
				$color3++;
			}//fin while 3
			mysqli_free_result($result3);
		if($suma_det_solo != 0) {
			$suma_periodo = $suma_periodo + $suma_det_solo;	
			$suma_total = $suma_periodo + $totaldet;
		}
			} //fin if total periodo
		?>
		<TR BGCOLOR='#ffcccc'> 
		<TD align="left" colspan="13"><b>Total Periodo en <?php echo $nom_otra_moneda_det; ?></b></TD>
		<TD align="right"><b><?php echo number_format($suma_deb,$n_decimales); ?></b></TD>
		<TD align="right"><b><?php echo number_format($suma_cred*-1,$n_decimales); ?></b></TD>
		<?php if($suma_periodo >= 0) { ?>
		<TD align="right"><b><?php echo number_format($suma_periodo,$n_decimales); ?></b></TD>
		<?php } else { ?>
		<TD align="right"><b><?php echo number_format($suma_periodo*-1,$n_decimales); ?></b></TD>
		<?php } ?>
		</TR> 
		<TR BGCOLOR='#ffcccc'> 
		<TD align="left" colspan="15"><b>Total en <?php echo $nom_otra_moneda_det; ?></b></TD>
		<TD align="right"><b><?php echo number_format($suma_total,$n_decimales); ?></b></TD></TR> 
		</tbody>
		</table>
		<?php


	} else { //else if detalle 0
	?>

		<table border="1" align="center" cellpadding="2" width="100%">
			<TR BGCOLOR='#ffcccc'> 
			<TD align="left" colspan="13"><b>Saldo inicial en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="right"><b><?php echo number_format($totaldet,$n_decimales); ?></b></TD></TR> 
			<thead>
			<TR> 
			<TD align="center"><b>Cod.</b></TD>
			<TD align="center"><b>Nro. Doc.</b></TD>
			<TD align="center" width="65"><b>Fecha</b></TD>
			<TD align="center" width="65"><b>Fecha Cobro</b></TD>
			<TD align="center"><b>Concepto</b></TD>
			<TD align="center"><b>Via Cobro</b></TD>
			<TD align="center"><b>Glosa</b></TD>
			<TD align="center"><b>Gen. Por</b></TD>
			<TD align="center"><b>Mon.</b></TD>
			<TD align="center"><b>Monto</b></TD>
			<TD align="center"><b>Tasa</b></TD>
			<TD align="center"><b>Monto en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="center"><b>Cobros en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="center"><b>Saldo en <?php echo $nom_otra_moneda_det; ?></b></TD>
			</TR>
			</thead>
			<tbody class="marcafila">

		<?php
		$color = 2;
		$suma_monto_om = 0;
		$suma_pagos = 0;
		$suma_total = 0;
		$saldo_periodo = 0;
		//esta matriz guarda el codigo de la cxc para mostrar los cobros que se hicieron en el periodo y no tienen cxc asociada
		$v = 1;
		$matriz_verif = array();
		while ($row = mysqli_fetch_array($result2)) { //while
			//para enlazar al que genero el asiento
			$papa_componente = $row['papa'];
			$papa_codigo = $row['cod_papa'];
			$usuario = $usuario_det;
			include "../../generadopor.php";
			
			$codigo_det = $row['codigo'];	
			$nro_doc = $row['nrodoc'];
			$fecha_reg = $row['fecha'];
			$fecha_cobro = $row['fecha_cobro'];
			$concepto = $row['concepto'];
			$glosa = $row['glosa'];
			$moneda = $row['moneda'];
			$total_c = $row['total'];
			$tasa = $row['tasa'];
			$total_cxc = $row['total_om'];

			//suma el total de los cobros
			$result3 = mysqli_query($link, "select sum(final.total) as total_cobro_om, final.cod_cxc as cod_cxc
			from
			(
			select otro.codigo as codigo, otro.nrodoc as nrodoc, 
			otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, 
			otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, 
			otro.via_cobro as via_cobro, otro.empresa as empresa, 
			otro.moneda_cxc as moneda, otro.glosa as glosa, 
			otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
			otro.otra_moneda as otra_moneda, 
			otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
			otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa, otro.cod_cxc as cod_cxc
			from 
			(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
			t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
			t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
			t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
			t.empresa as empresa, 
			t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
			t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
			t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
			r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa, t.cod_cxc as cod_cxc
			from 
			(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
			from
			colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			g.pkyAccountsReceivable = '$codigo_det' and 
			a.codRoute = c.pkyCollectionRoute and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			a.pkyCollection = b.codCollection and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1
			union all
			select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
			from
			payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			g.pkyAccountsReceivable = '$codigo_det' and 
			a.pkyPayment = b.codPayment and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			b.codAccountsReceivable is not NULL and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1) t,
			actExchangeRateDetail r
			where
			t.tc = r.codExchangeRate and
			t.cod_moneda_cxc = r.codTargetCurrency and
			t.otra_moneda = r.codBaseCurrency

			union all

			select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
			t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
			t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
			t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
			t.empresa as empresa, 
			t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
			t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
			t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
			1 as tasa, t.papa as papa, t.cod_papa as cod_papa, t.cod_cxc as cod_cxc
			from 
			(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
			from
			colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			g.pkyAccountsReceivable = '$codigo_det' and 
			a.codRoute = c.pkyCollectionRoute and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			a.pkyCollection = b.codCollection and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1
			union all
			select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
			from
			payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			g.pkyAccountsReceivable = '$codigo_det' and 
			a.pkyPayment = b.codPayment and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			b.codAccountsReceivable is not NULL and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1) t
			where
			t.cod_moneda_cxc = t.otra_moneda) otro) final
			group by final.cod_cxc;");

			$total_cobros = 0;
			while ($row = mysqli_fetch_array($result3)) {//while 3

				$total_cobros = $row['total_cobro_om'];
			
			}//fin while 3

			mysqli_free_result($result3);

			//controla que no sea 0 el saldo
			if(abs($total_cxc) != abs($total_cobros)) {//if no mostrar 0

				if($color % 2 == 0) { //if color
					printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $codigo_det);//cod
				} else {
					printf("<tr><td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $codigo_det);//cod
				}
				printf("<td align='center'>%s</td>", $nro_doc);//nro doc
				printf("<td align='center'>%s</td>", $$fecha_reg);//fecha
				printf("<td align='center'>%s</td>", $fecha_cobro);//fecha cobro
				printf("<td>%s</td>", $concepto);//concepto viene de los parametros
				printf("<td align='center'>&nbsp;</td>");//via cobro
				//printf("<td>%s</td>", $row['empresa']);//empresa
				printf("<td>%s</td>", $glosa);//glosa
				printf("<td align='center'>%s</td>", $papa_enlace);//gen por
				printf("<td>%s</td>", $moneda);//moneda
				if($total_c >= 0) {
					printf("<td align='right'>%s</td>", number_format($total_c, $n_decimales));//total
				} else {
					printf("<td align='right'>%s</td>", number_format($total_c*-1, $n_decimales));//total
				}
				printf("<td align='right'>%s</td>", number_format($tasa, $n_tipocambio));//tasa
				
				if($total_cxc >= 0) {
					printf("<td align='right'>%s</td>", number_format($total_cxc, $n_decimales));//total otra moneda
				} else {
					printf("<td align='right'>%s</td>", number_format($total_cxc*-1, $n_decimales));//total otra moneda
				}

				if($total_cobros >= 0) {
					printf("<td align='right'>%s</td>", number_format($total_cobros,$n_decimales));//total otra moneda pagos
				} else {
					printf("<td align='right'>%s</td>", number_format($total_cobros*-1,$n_decimales));//total otra moneda pagos
				}

				if(($total_cxc + $total_cobros) > 0) {
					printf("<td align='right'><b>%s</b></td></tr>", number_format($total_cxc + $total_cobros,$n_decimales));//total saldo
				} else {
					printf("<td align='right'><b>%s</b></td></tr>", number_format(($total_cxc + $total_cobros)*-1,$n_decimales));//total saldo
				}
				
				$suma_monto_om = $suma_monto_om + $total_cxc;
				$suma_cobros = $suma_cobros + $total_cobros;
				$color++;
			} //fin if no mostrar 0

			$matriz_verif[$v][1] = $codigo_det;
			$v++;
		
		}//fin while
		mysqli_free_result($result2);

		
		//verificacion si existe un cobro que no tenga cxc en ese periodo total_periodo viene del link
		if($total_periodo != 0) {//if total periodo
			$cadena_no = '';
			for($w = 1; $w < $v; $w++) { 
				$cadena_no = $cadena_no . $matriz_verif[$w][1].',';
			}
			
			if($cadena_no != '') {
				$cadena_no = ' where final.cod_cxc not in ('.substr($cadena_no,0,-1).')';
			} else {
				$cadena_no = ' ';	
			}
			

			$result3 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cob_pag as fecha_cobro, final.concepto as concepto, final.con_ing_egr as concepto_ingreso, final.via_cobro as via_cobro, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
			from
			(
			select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, otro.via_cobro as via_cobro, otro.empresa as empresa, otro.moneda_cxc as moneda, otro.glosa as glosa, otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, otro.papa as papa, otro.cod_papa as cod_papa
			from 
			(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
			t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
			t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
			t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
			t.empresa as empresa, 
			t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
			t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
			t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
			r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
			from 
			(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.codRoute = c.pkyCollectionRoute and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			a.pkyCollection = b.codCollection and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1
			union all
			select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.pkyPayment = b.codPayment and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			b.codAccountsReceivable is not NULL and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1) t,
			actExchangeRateDetail r
			where
			t.tc = r.codExchangeRate and
			t.cod_moneda_cxc = r.codTargetCurrency and
			t.otra_moneda = r.codBaseCurrency

			union all

			select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
			t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
			t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
			t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
			t.empresa as empresa, 
			t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
			t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
			t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
			1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
			from 
			(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.codRoute = c.pkyCollectionRoute and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			a.pkyCollection = b.codCollection and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1
			union all
			select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
			actCurrency f, colAccountsReceivable g, actCurrency h
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc2_det 
			$valor_contexto_det 
			g.codConcept = e.pkyAccountsReceivableConcept and 
			a.codClient = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.pkyPayment = b.codPayment and
			a.codClient = d.pkyCompany and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			b.codAccountsReceivable is not NULL and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1) t
			where
			t.cod_moneda_cxc = t.otra_moneda) otro) final 
			$cadena_no  
			order by final.fecha, final.codigo;");
			$suma_det_solo = 0;
			$control_hay_cobros = 0;

			while ($row = mysqli_fetch_array($result3)) {//while 3

				if($control_hay_cobros == 0){
					printf("<tr BGCOLOR='#C8E6C'><td align='left' colspan='14'><b>Cobros de cuentas que no aparecen en el periodo</b></td></tr>");
					$control_hay_cobros++;
				}
				//para enlazar al que genero el asiento
				$papa_componente = $row['papa'];
				$papa_codigo = $row['cod_papa'];
				$usuario = $usuario_det;
				include "../../generadopor.php";
				
				$cod_cobro = $row['codigo'];
				$tipo2 = $row['via_cobro'];
				if($color3 % 2 == 0) { //if color
					if($tipo2 == 'Liquidacion') {//if liquidacion
						printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
					} else {//else liquidacion
						printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
					}//fin if liquidacion
				} else {
					if($tipo2 == 'Liquidacion') {//if liquidacion
						printf("<tr><td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
					} else {//else liquidacion
						printf("<tr><td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
					}//fin if liquidacion
				}
				
				printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
				printf("<td align='center'>%s</td>", $row['fecha']);//fecha
				printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
				printf("<td>%s</td>", $row['concepto']);//concepto 
				printf("<td>%s</td>", $row['via_cobro']);//via cobro
				//printf("<td>%s</td>", $row['empresa']);//empresa
				printf("<td>%s</td>", $row['glosa']);//glosa
				printf("<td align='center'>%s</td>", $papa_enlace);//gen por
				printf("<td>%s</td>", $row['moneda']);//moneda

				if($row['total'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
				} else {
					printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
				}
				printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
				printf("<td>&nbsp;</td>");//total otra moneda 
				
				if($row['total_om'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda cobro
				} else {
					printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda cobro
				}

				$suma_cobros = $suma_cobros + $row['total_om'];

				if($row['total_om'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda saldo
				} else {
					printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda saldo
				}

				$color3++;
			}//fin while 3
			mysqli_free_result($result3);

		} //fin if total periodo

		$saldo_periodo = $suma_monto_om + $suma_cobros;
		$suma_total = $saldo_periodo + $totaldet;
		?>
		<TR BGCOLOR='#ffcccc'> 
		<TD align="left" colspan="11"><b>Total Periodo en <?php echo $nom_otra_moneda_det; ?></b></TD>
		<TD align="right"><b><?php echo number_format($suma_monto_om, $n_decimales); ?></b></TD>
		<TD align="right"><b><?php echo number_format($suma_cobros*-1,$n_decimales); ?></b></TD>
		<?php if($saldo_periodo >= 0) { ?>
		<TD align="right"><b><?php echo number_format($saldo_periodo,$n_decimales); ?></b></TD>
		<?php } else { ?>
		<TD align="right"><b><?php echo number_format($saldo_periodo*-1,$n_decimales); ?></b></TD>
		<?php } ?>
		</TR> 
		<TR BGCOLOR='#ffcccc'> 
		<TD align="left" colspan="13"><b>Total en <?php echo $nom_otra_moneda_det; ?></b></TD>
		<TD align="right"><b><?php echo number_format($suma_total,$n_decimales); ?></b></TD></TR> 
		</tbody>
		</table>
		<?php

	} //fin if detalle 0

 } //fin if 3.1
 


	if($empresa == 0) { //if 3.2
 
		// detalle empleado
		
		$result = mysqli_query($link, "select pkyPerson as codigo, 
		case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado
		from agnPerson
		where
		pkyPerson = '$nombredet' and 
		sysEnabled = 1 and sysAuthorized = 1
		order by empleado;");
		
		while ($row = mysqli_fetch_array($result)) {
			$nomempdet = $row['codigo'].' - '.$row['empleado'];
		}
		mysqli_free_result($result);

		$result2 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empleado,  final.moneda as moneda, final.glosa as glosa, final.cxc as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
		from
		(
		select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cobro as fecha_cobro, otro.concepto as concepto, otro.concepto_ingreso as concepto_ingreso, otro.via as via_cobro, otro.empleado as empleado, otro.moneda as moneda, otro.glosa as glosa, otro.cxc as cxc, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cxc as total, otro.papa as papa, otro.cod_papa as cod_papa
		from (
		select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
		from (
		select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, concat(e.fldLastName,', ',e.fldFirstName) as empleado, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c, agnPerson e, actCurrency f
		where 
		$valor_concepto_det 
		$valor_cuenta_concepto_cxc_det 
		$valor_contexto_det 
		a.codEmployee = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and
		a.codConcept = b.pkyAccountsReceivableConcept and
		a.codIncomeConcept = c.pkyIncomeConcept and
		a.codEmployee = e.pkyPerson and
		a.codCurrency = f.pkyCurrency and
		a.sysEnabled = 1 and a.sysAuthorized = 1) t,
		actExchangeRateDetail r
		where
		t.tc = r.codExchangeRate and
		t.cod_moneda = r.codTargetCurrency and
		t.otra_moneda = r.codBaseCurrency
		union all
		select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
		from (
		select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, concat(e.fldLastName,', ',e.fldFirstName) as empleado, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
		from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c,
		agnPerson e, actCurrency f
		where 
		$valor_concepto_det 
		$valor_cuenta_concepto_cxc_det 
		$valor_contexto_det 
		a.codEmployee = '$nombredet' and
		a.fldDate >= '$fechainidet' and
		a.fldDate <= '$fechafindet' and
		a.codConcept = b.pkyAccountsReceivableConcept and
		a.codIncomeConcept = c.pkyIncomeConcept and
		a.codEmployee = e.pkyPerson and
		a.codCurrency = f.pkyCurrency and
		a.sysEnabled = 1 and a.sysAuthorized = 1) t
		where
		t.cod_moneda = t.otra_moneda) otro) final 
		order by final.fecha, final.codigo;");
		?>
		<table border="0" align="left" width="100%" cellpadding="5">
		<tr><td><?php echo $mostrar_logo_reportes; ?>
		</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario_det; ?></b>
		</td></tr></table>
		<p><br /><center><font color="#000099" size="+1"><b>Detalle Cuentas por Cobrar a Fecha</b></font></center></p>
		<table border="0" cellpadding="2" align="center" width="100%">
		<tr>
		<td>	
			<table border="1" align="center" cellpadding="2" width="100%">
				<TR> 
				<TD width="25%"><b>Empleado: </b><?php echo $nomempdet; ?></TD>
				<TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro_det; ?></TD>
				<TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc_det; ?></TD>
				<TD width="25%"><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
				</TR>
				<TR>
				<TD><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></TD>
				<TD><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc_det; ?></TD>
				<TD><b>Detalle Resumido (Solo para agrupación por Empresa / Empleado): </b><?php echo $nom_detalle_resumido_det; ?></TD>
				<TD><b>Expresado en: </b><?php echo $nom_otra_moneda_det; ?></TD>
				</TR>
			</table>

		</td>

		<?php if ($usar_tc_det == 0) { //if usar tc?>
		<td valign="top" width="150">

			<table border="1" align="center" cellpadding="2" width="100%">
			<tr>
			<TD><b>Tipo de Cambio:</b></TD>
			</tr><tr>
			<TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc_det; ?>&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc_det; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
				<table border="0" cellpadding="2" align="center">
					<?php
					for($m = 1; $m <= $fin_m; $m++) {
					printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
					printf("<td align='center'>%s</td>", ' = ');//letra a
					printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
					//printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
					}
					?>
				</table>
			</TD>
			</tr>
			</table>
			
		</td>
		<?php } //fin if usar tc?>

		</tr>
		</table>
		<br /> 
	<?php
		//detalle resumido no = 1
		if($detalle_resumido_det == 1) { //if detalle 0
	?>

			<table border="1" align="center" cellpadding="2" width="100%">
				<TR BGCOLOR='#ffcccc'> 
				<TD align="left" colspan="15"><b>Saldo inicial en <?php echo $nom_otra_moneda_det; ?></b></TD>
				<TD align="right"><b><?php echo number_format($totaldet,$n_decimales); ?></b></TD></TR> 
				<thead>
				<TR> 
				<TD align="center"><b>Tipo</b></TD>
				<TD align="center"><b>Cod.</b></TD>
				<TD align="center"><b>Nro. Doc.</b></TD>
				<TD align="center" width="65"><b>Fecha</b></TD>
				<TD align="center" width="65"><b>Fecha Cobro</b></TD>
				<TD align="center"><b>Concepto</b></TD>
				<TD align="center"><b>Concepto Ingreso</b></TD>
				<TD align="center"><b>Via Cobro</b></TD>
				<TD align="center"><b>Glosa</b></TD>
				<TD align="center"><b>Gen. Por</b></TD>
				<TD align="center"><b>Mon.</b></TD>
				<TD align="center"><b>Monto</b></TD>
				<TD align="center"><b>Tasa</b></TD>
				<TD align="center"><b>D&eacute;bito en <?php echo $nom_otra_moneda_det; ?></b></TD>
				<TD align="center"><b>Cr&eacute;dito en <?php echo $nom_otra_moneda_det; ?></b></TD>
				<TD align="center"><b>Saldo en <?php echo $nom_otra_moneda_det; ?></b></TD>
				</TR>
				</thead>
				<tbody class="marcafila">

			<?php
			$color = 2;
			$suma_total = 0;
			$suma_periodo = 0;
			$suma_deb = 0;
			$suma_cred = 0;
			//esta matriz guarda el codigo de la cxc para mostrar los cobros que se hicieron en el periodo y no tienen cxc asociada
			$v = 1;
			$matriz_verif = array();
			while ($row = mysqli_fetch_array($result2)) { //while
				//para enlazar al que genero el asiento
				$papa_componente = $row['papa'];
				$papa_codigo = $row['cod_papa'];
				$usuario = $usuario_det;
				include "../../generadopor.php";
				
				$codigo_det = $row['codigo'];	
				if($color % 2 == 0) { //if color
				printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
				} else {
				printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
				}
				printf("<td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $row['codigo']);//cod
				printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
				printf("<td align='center'>%s</td>", $row['fecha']);//fecha
				printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
				printf("<td>%s</td>", $row['concepto']);//concepto viene de parametros
				printf("<td>%s</td>", $row['concepto_ingreso']);//concepto ingreso
				printf("<td>%s</td>", $row['via_cobro']);//via cobro
				//printf("<td>%s</td>", $row['empleado']);//empleado
				printf("<td>%s</td>", $row['glosa']);//glosa
				printf("<td align='center'>%s</td>", $papa_enlace);//gen por
				printf("<td>%s</td>", $row['moneda']);//moneda
				if($row['total'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
				} else {
					printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
				}
				printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
				
				if($row['total_om'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
					printf("<td>&nbsp;</td>");//total otra moneda credito
					$suma_deb = $suma_deb + $row['total_om'];
				} else {
					printf("<td>&nbsp;</td>");//total otra moneda debito
					printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
					$suma_cred = $suma_cred + $row['total_om'];
				}
				
				//$suma_periodo = $suma_periodo + $row['total_om'];
				$total_cxc = $row['total_om'];
				//$suma_saldo = $suma_saldo + $total_cxc;
				$suma_saldo = $total_cxc;
				printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));
				
				$color++;
				$matriz_verif[$v][1] = $row['codigo'];
				$v++;
				
				$result3 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empleado, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
				from
				(
				select otro.codigo as codigo, otro.nrodoc as nrodoc, 
				otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
				otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
				otro.via_cobro as via_cobro, otro.empleado as empleado, 
				otro.moneda_cxc as moneda, otro.glosa as glosa, 
				otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
				otro.otra_moneda as otra_moneda, 
				otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
				otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa
				from 
				(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
				t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
				t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
				t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
				t.empleado as empleado, 
				t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
				t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
				t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
				r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
				from 
				(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.codRoute = c.pkyCollectionRoute and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				a.pkyCollection = b.codCollection and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1
				UNION ALL
				select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
				g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				payPayment a, payPaymentDetail b, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.pkyPayment = b.codPayment and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				b.codAccountsReceivable is not NULL and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1) t,
				actExchangeRateDetail r
				where
				t.tc = r.codExchangeRate and
				t.cod_moneda_cxc = r.codTargetCurrency and
				t.otra_moneda = r.codBaseCurrency
				union all
				select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
				t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
				t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
				t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
				t.empleado as empleado, 
				t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
				t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
				t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
				1 as tasa, t.papa as papa, t.cod_papa as cod_papa
				from 
				(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.codRoute = c.pkyCollectionRoute and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				a.pkyCollection = b.codCollection and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1
				UNION ALL
				select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				payPayment a, payPaymentDetail b, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where 
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.pkyPayment = b.codPayment and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				b.codAccountsReceivable is not NULL and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1) t
				where
				t.cod_moneda_cxc = t.otra_moneda) otro) final
				order by final.fecha, final.codigo;");
				$color2 = $color;
				$suma_det = 0;
				while ($row = mysqli_fetch_array($result3)) {//while 3
					//para enlazar al que genero el asiento
					$papa_componente = $row['papa'];
					$papa_codigo = $row['cod_papa'];
					$usuario = $usuario_det;
					include "../../generadopor.php";
					
					$cod_cobro = $row['codigo'];
					$tipo2 = $row['via_cobro'];
					if($color2 % 2 == 0) { //if color
					printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
					} else {
					printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
					}
					
					if($tipo2 == 'Liquidacion') {//if liquidacion
						printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
					} else {//else liquidacion
						printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
					}//fin if liquidacion
					
					printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
					printf("<td align='center'>%s</td>", $row['fecha']);//fecha
					printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
					printf("<td>%s</td>", $row['concepto']);//concepto viene con NULL
					printf("<td>%s</td>", $row['concepto_ingreso']);//concepto viene con NULL
					printf("<td>%s</td>", $row['via_cobro']);//via cobro
					//printf("<td>%s</td>", $row['empleado']);//empleado
					printf("<td>%s</td>", $row['glosa']);//glosa
					printf("<td align='center'>%s</td>", $papa_enlace);//gen por
					printf("<td>%s</td>", $row['moneda']);//moneda
					
					if($row['total'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
					} else {
					printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
					}
					printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
					
					if($row['total_om'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
					printf("<td>&nbsp;</td>");//total otra moneda credito
					$suma_deb = $suma_deb + $row['total_om'];
					} else {
					printf("<td>&nbsp;</td>");//total otra moneda debito
					printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
					$suma_cred = $suma_cred + $row['total_om'];
					}
					$suma_det = $suma_det + $row['total_om'];
					$suma_saldo = $suma_saldo + $row['total_om'];
					printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
					
					$color2++;
				}//fin while 3
				mysqli_free_result($result3);
				
				if(($total_cxc + $suma_det) > 0) {
				printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='13'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
				printf("<td align='right'><b>%s</b></td>", number_format($total_cxc + $suma_det,$n_decimales));//total cuenta
				printf("<td>&nbsp;</td>");//espacio al final
				} else {
				printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='14'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
				printf("<td align='right'><b>%s</b></td>", number_format(($total_cxc + $suma_det)*-1,$n_decimales));//total cuenta
				}
					
				printf("<td>&nbsp;</td></tr>");//espacio al final
				
				$suma_periodo = $suma_periodo + $total_cxc + $suma_det;
			}//fin while
			mysqli_free_result($result2);
			$suma_total = $suma_periodo + $totaldet;  

			//verificacion si existe un cobro que no tenga cxc en ese periodo total_periodo viene del link
				if($total_periodo != 0) {//if total periodo
				$cadena_no = '';
				for($w = 1; $w < $v; $w++) { 
					$cadena_no = $cadena_no . $matriz_verif[$w][1].',';
				}
				//echo $cadena_no;
				if($cadena_no != '') {
				$cadena_no = ' where final.cod_cxc not in ('.substr($cadena_no,0,-1).')';
				} else {
				$cadena_no = ' ';	
				}
				//echo $cadena_no;
				
			$result3 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empleado, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
			from
			(
			select otro.codigo as codigo, otro.nrodoc as nrodoc, 
			otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
			otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
			otro.via_cobro as via_cobro, otro.empleado as empleado, 
			otro.moneda_cxc as moneda, otro.glosa as glosa, 
			otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
			otro.otra_moneda as otra_moneda, 
			otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
			otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, 
			otro.papa as papa, otro.cod_papa as cod_papa
			from 
			(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
			t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
			t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
			t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
			t.empleado as empleado, 
			t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
			t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
			t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
			r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
			from 
			(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
			actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc3_det 
			$valor_contexto_det 
			g.codConcept = i.pkyAccountsReceivableConcept and 
			a.codEmployee = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.codRoute = c.pkyCollectionRoute and
			a.codEmployee = e.pkyPerson and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			a.pkyCollection = b.codCollection and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1
			UNION ALL
			select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
			g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			payPayment a, payPaymentDetail b, agnPerson e, 
			actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc3_det 
			$valor_contexto_det 
			g.codConcept = i.pkyAccountsReceivableConcept and 
			a.codEmployee = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.pkyPayment = b.codPayment and
			a.codEmployee = e.pkyPerson and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			b.codAccountsReceivable is not NULL and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1) t,
			actExchangeRateDetail r
			where
			t.tc = r.codExchangeRate and
			t.cod_moneda_cxc = r.codTargetCurrency and
			t.otra_moneda = r.codBaseCurrency
			union all
			select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
			t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
			t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
			t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
			t.empleado as empleado, 
			t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
			t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
			t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
			1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
			from 
			(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
			actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc3_det 
			$valor_contexto_det 
			g.codConcept = i.pkyAccountsReceivableConcept and 
			a.codEmployee = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.codRoute = c.pkyCollectionRoute and
			a.codEmployee = e.pkyPerson and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			a.pkyCollection = b.codCollection and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1
			UNION ALL
			select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
			a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
			null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
			f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
			'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
			a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
			from
			payPayment a, payPaymentDetail b, agnPerson e, 
			actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
			where 
			$valor_concepto2_det 
			$valor_cuenta_concepto_cxc3_det 
			$valor_contexto_det 
			g.codConcept = i.pkyAccountsReceivableConcept and 
			a.codEmployee = '$nombredet' and
			a.fldDate >= '$fechainidet' and
			a.fldDate <= '$fechafindet' and 
			a.pkyPayment = b.codPayment and
			a.codEmployee = e.pkyPerson and
			a.codCurrency = f.pkyCurrency and
			g.codCurrency = h.pkyCurrency and
			b.codAccountsReceivable is not NULL and
			b.codAccountsReceivable = g.pkyAccountsReceivable and
			a.sysEnabled = 1 and a.sysAuthorized = 1) t
			where
			t.cod_moneda_cxc = t.otra_moneda) otro) final 
			$cadena_no 
			order by final.fecha, final.codigo;");
			$color3 = $color2;
			$suma_det_solo = 0;
			$control_hay_cobros = 0;
				while ($row = mysqli_fetch_array($result3)) {//while 3

					if($control_hay_cobros == 0){
						printf("<tr BGCOLOR='#C8E6C'><td align='left' colspan='16'><b>Cobros de cuentas que no aparecen en el periodo</b></td></tr>");
						$control_hay_cobros++;
					}

					//para enlazar al que genero el asiento
					$papa_componente = $row['papa'];
					$papa_codigo = $row['cod_papa'];
					$usuario = $usuario_det;
					include "../../generadopor.php";
					
					$cod_cobro = $row['codigo'];
					$tipo2 = $row['via_cobro'];
					if($color3 % 2 == 0) { //if color
					printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
					} else {
					printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
					}
					
					if($tipo2 == 'Liquidacion') {//if liquidacion
						printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
					} else {//else liquidacion
						printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
					}//fin if liquidacion
					
					printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
					printf("<td align='center'>%s</td>", $row['fecha']);//fecha
					printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
					printf("<td>%s</td>", $row['concepto']);//concepto 
					printf("<td>%s</td>", $row['concepto_ingreso']);//concepto cobro
					printf("<td>%s</td>", $row['via_cobro']);//via cobro
					//printf("<td>%s</td>", $row['empleado']);//empleado
					printf("<td>%s</td>", $row['glosa']);//glosa
					printf("<td align='center'>%s</td>", $papa_enlace);//gen por
					printf("<td>%s</td>", $row['moneda']);//moneda
					
					if($row['total'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
					} else {
					printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
					}
					printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
					
					if($row['total_om'] >= 0) {
					printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
					printf("<td>&nbsp;</td>");//total otra moneda credito
					$suma_deb = $suma_deb + $row['total_om'];
					} else {
					printf("<td>&nbsp;</td>");//total otra moneda debito
					printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
					$suma_cred = $suma_cred + $row['total_om'];
					}
					$suma_det_solo = $suma_det_solo + $row['total_om'];
					$suma_saldo = $suma_saldo + $row['total_om'];
					printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
					
					$color3++;
				}//fin while 3
				mysqli_free_result($result3);
				if($suma_det_solo != 0) {
					$suma_periodo = $suma_periodo + $suma_det_solo;	
					$suma_total = $suma_periodo + $totaldet;
				}
				} //fin if total periodo
			?>
			<TR BGCOLOR='#ffcccc'> 
			<TD align="left" colspan="13"><b>Total Periodo en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="right"><b><?php echo number_format($suma_deb,$n_decimales); ?></b></TD>
			<TD align="right"><b><?php echo number_format($suma_cred*-1,$n_decimales); ?></b></TD>
			<?php if($suma_periodo >= 0) { ?>
			<TD align="right"><b><?php echo number_format($suma_periodo,$n_decimales); ?></b></TD>
			<?php } else { ?>
			<TD align="right"><b><?php echo number_format($suma_periodo*-1,$n_decimales); ?></b></TD>
			<?php } ?>
			</TR> 
			<TR BGCOLOR='#ffcccc'> 
			<TD align="left" colspan="15"><b>Total en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="right"><b><?php echo number_format($suma_total,$n_decimales); ?></b></TD></TR> 
			</tbody>
			</table>
			<?php

		} else { //else if detalle 0
			?>
		
			<table border="1" align="center" cellpadding="2" width="100%">
			<TR BGCOLOR='#ffcccc'> 
			<TD align="left" colspan="13"><b>Saldo inicial en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="right"><b><?php echo number_format($totaldet,$n_decimales); ?></b></TD></TR> 
			<thead>
			<TR> 
			<TD align="center"><b>Cod.</b></TD>
			<TD align="center"><b>Nro. Doc.</b></TD>
			<TD align="center" width="65"><b>Fecha</b></TD>
			<TD align="center" width="65"><b>Fecha Cobro</b></TD>
			<TD align="center"><b>Concepto</b></TD>
			<TD align="center"><b>Via Cobro</b></TD>
			<TD align="center"><b>Glosa</b></TD>
			<TD align="center"><b>Gen. Por</b></TD>
			<TD align="center"><b>Mon.</b></TD>
			<TD align="center"><b>Monto</b></TD>
			<TD align="center"><b>Tasa</b></TD>
			<TD align="center"><b>Monto en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="center"><b>Cobros en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="center"><b>Saldo en <?php echo $nom_otra_moneda_det; ?></b></TD>
			</TR>
			</thead>
			<tbody class="marcafila">

			<?php
			$color = 2;
			$suma_monto_om = 0;
			$suma_pagos = 0;
			$suma_total = 0;
			$saldo_periodo = 0;
			//esta matriz guarda el codigo de la cxc para mostrar los cobros que se hicieron en el periodo y no tienen cxc asociada
			$v = 1;
			$matriz_verif = array();
			while ($row = mysqli_fetch_array($result2)) { //while
				//para enlazar al que genero el asiento
				$papa_componente = $row['papa'];
				$papa_codigo = $row['cod_papa'];
				$usuario = $usuario_det;
				include "../../generadopor.php";
				
				$codigo_det = $row['codigo'];	
				$nro_doc = $row['nrodoc'];
				$fecha_reg = $row['fecha'];
				$fecha_cobro = $row['fecha_cobro'];
				$concepto = $row['concepto'];
				$glosa = $row['glosa'];
				$moneda = $row['moneda'];
				$total_c = $row['total'];
				$tasa = $row['tasa'];
				$total_cxc = $row['total_om'];

				//suma el total de los cobros
				$result3 = mysqli_query($link, "select sum(final.total) as total_cobro_om, final.cod_cxc as cod_cxc
				from
				(
				select otro.codigo as codigo, otro.nrodoc as nrodoc, 
				otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
				otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
				otro.via_cobro as via_cobro, otro.empleado as empleado, 
				otro.moneda_cxc as moneda, otro.glosa as glosa, 
				otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
				otro.otra_moneda as otra_moneda, 
				otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
				otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa, otro.cod_cxc as cod_cxc
				from 
				(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
				t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
				t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
				t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
				t.empleado as empleado, 
				t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
				t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
				t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
				r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa, t.cod_cxc as cod_cxc
				from 
				(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
				from
				colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.codRoute = c.pkyCollectionRoute and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				a.pkyCollection = b.codCollection and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1
				UNION ALL
				select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
				g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
				from
				payPayment a, payPaymentDetail b, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.pkyPayment = b.codPayment and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				b.codAccountsReceivable is not NULL and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1) t,
				actExchangeRateDetail r
				where
				t.tc = r.codExchangeRate and
				t.cod_moneda_cxc = r.codTargetCurrency and
				t.otra_moneda = r.codBaseCurrency
				union all
				select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
				t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
				t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
				t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
				t.empleado as empleado, 
				t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
				t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
				t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
				1 as tasa, t.papa as papa, t.cod_papa as cod_papa, t.cod_cxc as cod_cxc
				from 
				(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
				from
				colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.codRoute = c.pkyCollectionRoute and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				a.pkyCollection = b.codCollection and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1
				UNION ALL
				select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa, g.pkyAccountsReceivable as cod_cxc
				from
				payPayment a, payPaymentDetail b, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where 
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				g.pkyAccountsReceivable = '$codigo_det' and 
				a.pkyPayment = b.codPayment and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				b.codAccountsReceivable is not NULL and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1) t
				where
				t.cod_moneda_cxc = t.otra_moneda) otro) final
				group by final.cod_cxc;");

				$total_cobros = 0;
				while ($row = mysqli_fetch_array($result3)) {//while 3

					$total_cobros = $row['total_cobro_om'];
				
				}//fin while 3

				mysqli_free_result($result3);

				//controla que no sea 0 el saldo
				if(abs($total_cxc) != abs($total_cobros)) {//if no mostrar 0

					if($color % 2 == 0) { //if color
						printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $codigo_det);//cod
					} else {
						printf("<tr><td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $codigo_det);//cod
					}
					printf("<td align='center'>%s</td>", $nro_doc);//nro doc
					printf("<td align='center'>%s</td>", $$fecha_reg);//fecha
					printf("<td align='center'>%s</td>", $fecha_cobro);//fecha cobro
					printf("<td>%s</td>", $concepto);//concepto viene de los parametros
					printf("<td align='center'>&nbsp;</td>");//via cobro
					//printf("<td>%s</td>", $row['empresa']);//empresa
					printf("<td>%s</td>", $glosa);//glosa
					printf("<td align='center'>%s</td>", $papa_enlace);//gen por
					printf("<td>%s</td>", $moneda);//moneda
					if($total_c >= 0) {
						printf("<td align='right'>%s</td>", number_format($total_c, $n_decimales));//total
					} else {
						printf("<td align='right'>%s</td>", number_format($total_c*-1, $n_decimales));//total
					}
					printf("<td align='right'>%s</td>", number_format($tasa, $n_tipocambio));//tasa
					
					if($total_cxc >= 0) {
						printf("<td align='right'>%s</td>", number_format($total_cxc, $n_decimales));//total otra moneda
					} else {
						printf("<td align='right'>%s</td>", number_format($total_cxc*-1, $n_decimales));//total otra moneda
					}

					if($total_cobros >= 0) {
						printf("<td align='right'>%s</td>", number_format($total_cobros,$n_decimales));//total otra moneda pagos
					} else {
						printf("<td align='right'>%s</td>", number_format($total_cobros*-1,$n_decimales));//total otra moneda pagos
					}

					if(($total_cxc + $total_cobros) > 0) {
						printf("<td align='right'><b>%s</b></td></tr>", number_format($total_cxc + $total_cobros,$n_decimales));//total saldo
					} else {
						printf("<td align='right'><b>%s</b></td></tr>", number_format(($total_cxc + $total_cobros)*-1,$n_decimales));//total saldo
					}
					
					$suma_monto_om = $suma_monto_om + $total_cxc;
					$suma_cobros = $suma_cobros + $total_cobros;
					$color++;
				} //fin if no mostrar 0

				$matriz_verif[$v][1] = $codigo_det;
				$v++;
			
			}//fin while
			mysqli_free_result($result2);

			
			//verificacion si existe un cobro que no tenga cxc en ese periodo total_periodo viene del link
			if($total_periodo != 0) {//if total periodo
				$cadena_no = '';
				for($w = 1; $w < $v; $w++) { 
					$cadena_no = $cadena_no . $matriz_verif[$w][1].',';
				}
				
				if($cadena_no != '') {
					$cadena_no = ' where final.cod_cxc not in ('.substr($cadena_no,0,-1).')';
				} else {
					$cadena_no = ' ';	
				}
				

				$result3 = mysqli_query($link, "select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empleado, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
				from
				(
				select otro.codigo as codigo, otro.nrodoc as nrodoc, 
				otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
				otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
				otro.via_cobro as via_cobro, otro.empleado as empleado, 
				otro.moneda_cxc as moneda, otro.glosa as glosa, 
				otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
				otro.otra_moneda as otra_moneda, 
				otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
				otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, 
				otro.papa as papa, otro.cod_papa as cod_papa
				from 
				(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
				t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
				t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
				t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
				t.empleado as empleado, 
				t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
				t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
				t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
				r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
				from 
				(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
				g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where 
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				a.codRoute = c.pkyCollectionRoute and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				a.pkyCollection = b.codCollection and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1
				UNION ALL
				select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
				g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				payPayment a, payPaymentDetail b, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where 
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				a.pkyPayment = b.codPayment and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				b.codAccountsReceivable is not NULL and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1) t,
				actExchangeRateDetail r
				where
				t.tc = r.codExchangeRate and
				t.cod_moneda_cxc = r.codTargetCurrency and
				t.otra_moneda = r.codBaseCurrency
				union all
				select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
				t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
				t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
				t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
				t.empleado as empleado, 
				t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
				t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
				t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
				1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
				from 
				(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where 
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				a.codRoute = c.pkyCollectionRoute and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				a.pkyCollection = b.codCollection and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1
				UNION ALL
				select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
				a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
				null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
				f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
				'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
				a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
				from
				payPayment a, payPaymentDetail b, agnPerson e, 
				actCurrency f, colAccountsReceivable g, actCurrency h, colAccountsReceivableConcept i
				where 
				$valor_concepto2_det 
				$valor_cuenta_concepto_cxc3_det 
				$valor_contexto_det 
				g.codConcept = i.pkyAccountsReceivableConcept and 
				a.codEmployee = '$nombredet' and
				a.fldDate >= '$fechainidet' and
				a.fldDate <= '$fechafindet' and 
				a.pkyPayment = b.codPayment and
				a.codEmployee = e.pkyPerson and
				a.codCurrency = f.pkyCurrency and
				g.codCurrency = h.pkyCurrency and
				b.codAccountsReceivable is not NULL and
				b.codAccountsReceivable = g.pkyAccountsReceivable and
				a.sysEnabled = 1 and a.sysAuthorized = 1) t
				where
				t.cod_moneda_cxc = t.otra_moneda) otro) final 
				$cadena_no 
				order by final.fecha, final.codigo;");
				$suma_det_solo = 0;
				$control_hay_cobros = 0;

				while ($row = mysqli_fetch_array($result3)) {//while 3

					if($control_hay_cobros == 0){
						printf("<tr BGCOLOR='#C8E6C'><td align='left' colspan='14'><b>Cobros de cuentas que no aparecen en el periodo</b></td></tr>");
						$control_hay_cobros++;
					}
					//para enlazar al que genero el asiento
					$papa_componente = $row['papa'];
					$papa_codigo = $row['cod_papa'];
					$usuario = $usuario_det;
					include "../../generadopor.php";
					
					$cod_cobro = $row['codigo'];
					$tipo2 = $row['via_cobro'];
					if($color3 % 2 == 0) { //if color
						if($tipo2 == 'Liquidacion') {//if liquidacion
							printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
						} else {//else liquidacion
							printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
						}//fin if liquidacion
					} else {
						if($tipo2 == 'Liquidacion') {//if liquidacion
							printf("<tr><td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
						} else {//else liquidacion
							printf("<tr><td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
						}//fin if liquidacion
					}
					
					printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
					printf("<td align='center'>%s</td>", $row['fecha']);//fecha
					printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
					printf("<td>%s</td>", $row['concepto']);//concepto 
					printf("<td>%s</td>", $row['via_cobro']);//via cobro
					//printf("<td>%s</td>", $row['empresa']);//empresa
					printf("<td>%s</td>", $row['glosa']);//glosa
					printf("<td align='center'>%s</td>", $papa_enlace);//gen por
					printf("<td>%s</td>", $row['moneda']);//moneda

					if($row['total'] >= 0) {
						printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
					} else {
						printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
					}
					printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
					printf("<td>&nbsp;</td>");//total otra moneda 
					
					if($row['total_om'] >= 0) {
						printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda cobro
					} else {
						printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda cobro
					}

					$suma_cobros = $suma_cobros + $row['total_om'];

					if($row['total_om'] >= 0) {
						printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda saldo
					} else {
						printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda saldo
					}

					$color3++;
				}//fin while 3
				mysqli_free_result($result3);
				
			} //fin if total periodo

			$saldo_periodo = $suma_monto_om + $suma_cobros;
			$suma_total = $saldo_periodo + $totaldet;
			?>
			<TR BGCOLOR='#ffcccc'> 
			<TD align="left" colspan="11"><b>Total Periodo en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="right"><b><?php echo number_format($suma_monto_om, $n_decimales); ?></b></TD>
			<TD align="right"><b><?php echo number_format($suma_cobros*-1,$n_decimales); ?></b></TD>
			<?php if($saldo_periodo >= 0) { ?>
			<TD align="right"><b><?php echo number_format($saldo_periodo,$n_decimales); ?></b></TD>
			<?php } else { ?>
			<TD align="right"><b><?php echo number_format($saldo_periodo*-1,$n_decimales); ?></b></TD>
			<?php } ?>
			</TR> 
			<TR BGCOLOR='#ffcccc'> 
			<TD align="left" colspan="13"><b>Total en <?php echo $nom_otra_moneda_det; ?></b></TD>
			<TD align="right"><b><?php echo number_format($suma_total,$n_decimales); ?></b></TD></TR> 
			</tbody>
			</table>
			<?php

		} //fin if detalle 0
 	} //fin if 3.2
  
} //fin if 3






//agrupar = 1 por concepto
//es idem al de arriba orientado a concepto

if($agrupar == 1) {//if agrupar 1

//Inicio reporte cuentas por cobrar saldo a fecha

if($rep == 6 && $tipo == 1) { // if 2

//nombre otra moneda
$resultotra = mysqli_query($link, "SELECT fldName as otra_moneda
from
actCurrency
where
pkyCurrency = '$otra_moneda' and
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultotra)) {
	$nom_otra_moneda = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);

if($concepto_cobro == 0) { // if concepto cobro
	$nom_concepto_cobro = 'Todos';
	$valor_concepto = ' ';
	$valor_concepto2 = ' ';
} else {
	$resultcon = mysqli_query($link, "select pkyAccountsReceivableConcept as codigo, fldName as nombre
from colAccountsReceivableConcept
where
pkyAccountsReceivableConcept = '$concepto_cobro';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_cobro = $row['codigo'].' - '.$row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto = ' a.codConcept = '. $concepto_cobro .' and ';
	$valor_concepto2 = ' c.codConcept = '. $concepto_cobro .' and ';
}//fin if concepto de cobro

if ($cuenta_concepto_cxc == 0) { // if cuenta concepto cobro
	$nom_cuenta_concepto_cxc = 'Todos';
	$valor_cuenta_concepto_cxc = ' ';
	$valor_cuenta_concepto_cxc2 = ' ';
} else {
	$valor_cuenta_concepto_cxc = ' b.codAccount = ' .$cuenta_concepto_cxc. ' and ';
	$valor_cuenta_concepto_cxc2 = ' e.codAccount = ' .$cuenta_concepto_cxc. ' and ';
	//nombre de la cuenta contable del concepto de cxc
	$result2 = mysqli_query($link, "select pkyAccount, fldName 
							from actAccount 
							where 
							pkyAccount = '$cuenta_concepto_cxc' and
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result2)) {
		$nom_cuenta_concepto_cxc = $row['pkyAccount'].' - '.$row['fldName'];
	}
	mysqli_free_result($result2);
} //fin if cuenta concepto cobro

//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, segun lo que elijan, antes solo era fecah final del reporte, '$ultimo_tc' as tc, tambien sirve para mostar en la cabecera
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafin' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc = $row['tc'];
	}
	mysqli_free_result($resultom);

$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc';");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

$resulttcdet = mysqli_query($link, "select a.pkyExchangeRateDetail as cod_tc_det, a.codBaseCurrency as cod_mon_target, b.fldName as mon_target, b.txtDescription as nom_mon_target, a.codTargetCurrency as cod_mon_base, c.fldName as mon_base, c.txtDescription as nom_mon_base, a.fldRate as tasa
from
actExchangeRateDetail a, actCurrency b, actCurrency c
where
a.codExchangeRate = '$ultimo_tc' and 
a.codBaseCurrency = '$cod_moneda_principal' and 
a.codBaseCurrency = b.pkyCurrency and 
a.codTargetCurrency = c.pkyCurrency 
order by cod_mon_target, cod_mon_base;");
$ma_tc = array();
$m = 1;
while ($row = mysqli_fetch_array($resulttcdet)) {
	$ma_tc [$m][1] = $row['mon_base'];
	$ma_tc [$m][2] = $row['mon_target'];
	$ma_tc [$m][3] = $row['tasa'];
	$m++;
}
mysqli_free_result($resulttcdet);
$fin_m = $m - 1;

//segun el tc
if($usar_tc == 0) { 
	$nom_usar_tc = 'De Fecha Final';
	$valor_tc = $ultimo_tc.' as tc';
} else {
	$nom_usar_tc = 'De Fecha Transacci&oacute;n';
	$valor_tc = ' a.codExchangeRate as tc';
}


if($cod_contexto == -1){ 
	$nom_contexto = 'Todos';
	$valor_contexto = ' ';
} else {
	$resultcontx = mysqli_query($link, "select pkyContext as cod_contexto, fldName as contexto, codCostCenter as cod_cc 
	from srvContext
	where 
	pkyContext = '$cod_contexto';");
		while ($row = mysqli_fetch_array($resultcontx)) {   
			$nom_contexto = $row['cod_contexto'].' - '.$row['contexto'];
		}
		mysqli_free_result($resultcontx);
	$valor_contexto = ' a.sysContext = '.$cod_contexto.' and ';	
}
/*
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc' and
codBaseCurrency = '$otra_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
$matriz_tc = array();
$i = 1;
while ($row = mysqli_fetch_array($resulttc)) {
	$matriz_tc [$i][1] = $row['codigotc'];//codigo tc
	$matriz_tc [$i][2] = $row['monedabase'];//codigo moneda base
	$matriz_tc [$i][3] = $row['monedacambio'];//codigo moneda cambio
	$matriz_tc [$i][4] = $row['tc'];//valor a multiplicar del tc 
	$i++;
	}
	mysqli_free_result($resulttc);

$fin_om = $i - 1;
*/
if ($empresaoempleado == -1) { // if 2.2
	
	$empresa = 1;
	if($nombreemp == 0) {
	$nom_orden = 'Nombre';
	$nom_cliente = 'Empresas';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultcli = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
								from agnCompany
								where
								pkyCompany = '$nombreemp' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultcli)) {
			$nom_cliente = $row['codigo'].' - '.$row['empresa'];
		}
		mysqli_free_result($resultcli);
	$valor_cliente = ' a.codClient = '. $nombreemp .' and ';
	$valor_cliente2 = ' c.codClient = '. $nombreemp .' and ';
	}
//$valor_empo = ' a.codClient is not NULL ';
$valor_empo = ' a.codClient is not NULL and ';
$valor_empo2 = ' c.codClient is not NULL and ';
}//fin if 2.2

if ($empresaoempleado == -2) { // if 2.3
	
	$empresa = 0;
	if($nombreemp == 0) {
	$nom_orden = 'Nombre';
	$nom_cliente = 'Empleados';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultcli = mysqli_query($link, "select pkyPerson as codigo, case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado, 'Empleado' as tipo
								from agnPerson
								where
								pkyPerson = '$nombreemp' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultcli)) {
			$nom_cliente = $row['codigo'].' - '.$row['empleado'];
		}
		mysqli_free_result($resultcli);
	$valor_cliente = ' a.codEmployee = '. $nombreemp .' and ';
	$valor_cliente2 = ' c.codEmployee = '. $nombreemp .' and ';
	}
//$valor_empo = ' a.codEmployee is not NULL ';
$valor_empo = ' a.codEmployee is not NULL and ';
$valor_empo2 = ' c.codEmployee is not NULL and ';
} //fin if 2.3


if ($empresaoempleado == -3) { // if 2.4
	
	$empresa = -1;
	$nom_orden = 'Nombre';
	$nom_cliente = 'Todos';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
$valor_empo = ' ';
$valor_empo2 = ' ';
}// fin if 2.4

	//listado de conceptos
	$result = mysqli_query($link, "select pkyAccountsReceivableConcept as codigo, fldName as concepto
from colAccountsReceivableConcept
where
sysEnabled = 1 and sysAuthorized = 1
order by concepto;");
		
	//inicio calculo saldo inicial
	
	//CxC empresas o empleados
	$result3 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as cxc
from(
select otra.cod_con as cod_con, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_con as cod_con, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codConcept as cod_con, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo  
$valor_contexto 
a.fldDate < '$fechaini' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_con, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_con as cod_con, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codConcept as cod_con, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo  
$valor_contexto 
a.fldDate < '$fechaini' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_con, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_con
order by final.cod_con;");

	//suma Cobros empresas o empleados
	$result5 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as suma_cobros
from(
select otra.cod_con as cod_con, otra.suma_cobros as suma_cobros,
 otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
 otra.cod_moneda_cxc as cod_moneda_cxc, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_cobros * otra.tasa as total
from
(select t.cod_con as cod_con, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_con as cod_con, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_con
order by final.cod_con;");		

$matriz_salini = array();
$i = 1;
while ($row = mysqli_fetch_array($result)) {
	$matriz_salini [$i][1] = $row['codigo'];//cod concepto
	$matriz_salini [$i][2] = $row['concepto'];//nombre concepto
	$matriz_salini [$i][3] = 0; //suma cxc
	$matriz_salini [$i][4] = 0; //suma cobros
	$matriz_salini [$i][5] = 0; //saldo inicial
	$matriz_salini [$i][6] = 0; //suma cxc periodo
	$matriz_salini [$i][7] = 0; //suma cobros periodo
	$matriz_salini [$i][8] = 0; //saldo periodo
	$matriz_salini [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_con = $row['cod_con'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][3] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_con = $row['cod_con'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][4] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][3];
	$reg_cobros = $matriz_salini [$i][4];
	$matriz_salini [$i][5] = $reg_cxc - $reg_cobros;
	$i++;
}
	
//fin calculo saldo inicial

//inicio calculo registros

	//CxC empresas o empleados
	$result3 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as cxc
from(
select otra.cod_con as cod_con, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_con as cod_con, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codConcept as cod_con, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_con as cod_con, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codConcept as cod_con, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, colAccountsReceivableConcept b
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = b.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_con, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_con
order by final.cod_con;");
	
	//suma Cobros empresas o empleados
	$result5 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as suma_cobros
from(
select otra.cod_con as cod_con, otra.suma_cobros as suma_cobros,
 otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
 otra.cod_moneda_cxc as cod_moneda_cxc, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_cobros * otra.tasa as total
from
(select t.cod_con as cod_con, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_con as cod_con, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select c.codConcept as cod_con, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_con
order by final.cod_con;");	

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_con = $row['cod_con'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][6] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_con = $row['cod_con'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][7] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][6];
	$reg_cobros = $matriz_salini [$i][7];
	$matriz_salini [$i][8] = $reg_cxc - $reg_cobros;
	$reg_salini = $matriz_salini [$i][5];
	$reg_periodo = $matriz_salini [$i][8];
	$matriz_salini [$i][9] = $reg_salini + $reg_periodo;
	$i++;
}
	
//fin calculo registros
		?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Cuentas por Cobrar Saldo a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Empresa/Empleado: </b><?php echo $nom_cliente; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro; ?></TD>
        <TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        <TD><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc; ?></TD>
        <TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
		<TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>

</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Concepto</b></TD>
	<TD align="center"><b>CxC Sal. Ini.</b></TD>
    <TD align="center"><b>Cob. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxC Periodo</b></TD>
    <TD align="center"><b>Cobros Periodo</b></TD>
	<TD align="center"><b>Total Periodo</b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda; ?></b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total_cxc = 0;
  $suma_total_cobros = 0;
  $suma_total_ini = 0;
  $suma_total_cxc_per = 0;
  $suma_total_cobros_per = 0;
  $suma_total_periodo = 0;
  $suma_total = 0;
  $j = 1;
  while ($j <= $fin) { //while
	
	while($matriz_salini [$j][3] == 0 && $matriz_salini [$j][4] == 0 && $matriz_salini [$j][5] == 0 && $matriz_salini [$j][6] == 0 && $matriz_salini [$j][7] == 0 && $matriz_salini [$j][8] == 0 && $j <= $fin)
	{ $j++; }
	
	if($j > $fin) { //if ultimo 0
	} else { //else ultimo 0
	
	$codigo = $matriz_salini [$j][1];
	$totaldet = $matriz_salini [$j][5];
	
	if($saldo_cero == 1 && $matriz_salini [$j][9] == 0) { //if saldo cero
	} else { //else saldo cero
	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} else { 
	printf("<tr><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} //cierra if color
	printf("<td align='left'>%s</td>", $matriz_salini [$j][2]);//concepto
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][3],$n_decimales));//CxC saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][4],$n_decimales));// cobros saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][5],$n_decimales));// saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][6],$n_decimales));// suma CxC periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][7],$n_decimales));// suma cobros periodo
	$total_periodo = $matriz_salini [$j][7];
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][8],$n_decimales));// total saldo periodo
	printf("<td align='right'><a href='report.php?rep=6&tipo=3&nombredet=$codigo&nombreempdet=$nombreemp&empresa=$empresa&fechainidet=$fechaini&fechafindet=$fechafin&totaldet=$totaldet&otra_moneda_det=$otra_moneda&total_periodo=$total_periodo&usar_tc_det=$usar_tc&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini [$j][9],$n_decimales));//total //no mando el concepto_cobro_cxc porque el detalle no necesita, se manda el concepto y tiene su propio detalle
	   
	$suma_total_cxc = $suma_total_cxc + $matriz_salini [$j][3];
    $suma_total_cobros = $suma_total_cobros + $matriz_salini [$j][4];
	$suma_total_ini = $suma_total_ini + $matriz_salini [$j][5];
	
    $suma_total_cxc_per = $suma_total_cxc_per + $matriz_salini [$j][6];
    $suma_total_cobros_per = $suma_total_cobros_per + $matriz_salini [$j][7];
	$suma_total_periodo = $suma_total_periodo + $matriz_salini [$j][8];
    
    $suma_total = $suma_total + $matriz_salini [$j][9];
	$color++;
	
	} //fin if saldo cero
	
	} //cierra else ultimo 0
	
    $j++;
}//fin while


?>
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total Cuentas <?php echo $nom_cliente; ?></b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_ini,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_periodo,$n_decimales)); ?>
</td>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total,$n_decimales)); ?>
</td></tr>
</tbody>
</table>
<?php

} //fin if 2

} //fin if agrupar 1



// inicio muestra detalle agrupado por concepto
// el detalle esta fuera del agrupar porque no puedo enviar por POST y GET la variable agrupar 


if($rep == 6 && $tipo == 3) { // if 3

 //nombre otra moneda
$resultotra = mysqli_query($link, "SELECT fldName as otra_moneda
from
actCurrency
where
pkyCurrency = '$otra_moneda_det' and
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultotra)) {
	$nom_otra_moneda_det = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);


//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, segun lo que elijan, antes solo era fecah final del reporte, '$ultimo_tc' as tc, tambien sirve para mostar en la cabecera
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafindet' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc_det = $row['tc'];
	}
	mysqli_free_result($resultom);

$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc_det';");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

$resulttcdet = mysqli_query($link, "select a.pkyExchangeRateDetail as cod_tc_det, a.codBaseCurrency as cod_mon_target, b.fldName as mon_target, b.txtDescription as nom_mon_target, a.codTargetCurrency as cod_mon_base, c.fldName as mon_base, c.txtDescription as nom_mon_base, a.fldRate as tasa
from
actExchangeRateDetail a, actCurrency b, actCurrency c
where
a.codExchangeRate = '$ultimo_tc_det' and 
a.codBaseCurrency = '$cod_moneda_principal' and 
a.codBaseCurrency = b.pkyCurrency and 
a.codTargetCurrency = c.pkyCurrency 
order by cod_mon_target, cod_mon_base;");
$ma_tc = array();
$m = 1;
while ($row = mysqli_fetch_array($resulttcdet)) {
	$ma_tc [$m][1] = $row['mon_base'];
	$ma_tc [$m][2] = $row['mon_target'];
	$ma_tc [$m][3] = $row['tasa'];
	$m++;
}
mysqli_free_result($resulttcdet);
$fin_m = $m - 1;

//segun el tc
if($usar_tc_det == 0) { 
	$nom_usar_tc_det = 'De Fecha Final';
	$valor_tc_det = $ultimo_tc_det.' as tc';
} else {
	$nom_usar_tc_det = 'De Fecha Transacci&oacute;n';
	$valor_tc_det = ' a.codExchangeRate as tc';
}
/*
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc_det' and
codBaseCurrency = '$otra_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
$matriz_tc = array();
$i = 1;
while ($row = mysqli_fetch_array($resulttc)) {
	$matriz_tc [$i][1] = $row['codigotc'];//codigo tc
	$matriz_tc [$i][2] = $row['monedabase'];//codigo moneda base
	$matriz_tc [$i][3] = $row['monedacambio'];//codigo moneda cambio
	$matriz_tc [$i][4] = $row['tc'];//valor a multiplicar del tc 
	$i++;
	}
	mysqli_free_result($resulttc);

$fin_om = $i - 1;
*/

	$resultcon = mysqli_query($link, "select pkyAccountsReceivableConcept as codigo, fldName as nombre
	from colAccountsReceivableConcept
	where
	pkyAccountsReceivableConcept = '$nombredet';");
	while ($row = mysqli_fetch_array($resultcon)) {   
		$nom_concepto_cobro_det = $row['codigo'].' - '.$row['nombre'];
	}
	mysqli_free_result($resultcon);
	
if($cod_contexto_det == -1){ 
	$nom_contexto_det = 'Todos';
	$valor_contexto_det = ' ';
} else {
	$resultcontx = mysqli_query($link, "select pkyContext as cod_contexto, fldName as contexto, codCostCenter as cod_cc 
	from srvContext
	where 
	pkyContext = '$cod_contexto_det';");
		while ($row = mysqli_fetch_array($resultcontx)) {   
			$nom_contexto_det = $row['cod_contexto'].' - '.$row['contexto'];
		}
		mysqli_free_result($resultcontx);
	$valor_contexto_det = ' a.sysContext = '.$cod_contexto_det.' and ';	
}

if($empresa == 1) { //if 3.1
  
 // detalle empresa
  $result = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
from agnCompany
where
pkyCompany = '$nombreempdet' and
sysEnabled = 1 and sysAuthorized = 1;");
 
while ($row = mysqli_fetch_array($result)) {
	$nomempdet = $row['codigo'].' - '.$row['empresa'];
}
mysqli_free_result($result);
$valor_empresadet = ' a.codClient = '.$nombreempdet.' and ';
$valor_empleadodet = ' a.codEmployee = 0 and ';
$valor_empresadet2 = ' g.codClient = '.$nombreempdet.' and ';
$valor_empleadodet2 = ' g.codEmployee = 0 and ';

} //fin if 3.1

if($empresa == 0) { //if 3.2
 
 // detalle empleado
 
 $result = mysqli_query($link, "select pkyPerson as codigo, 
case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado
from agnPerson
where
pkyPerson = '$nombreempdet' and 
sysEnabled = 1 and sysAuthorized = 1
order by empleado;");
while ($row = mysqli_fetch_array($result)) {
	$nomempdet = $row['codigo'].' - '.$row['empleado'];
}
mysqli_free_result($result);
$valor_empresadet = ' a.codClient = 0 and ';
$valor_empleadodet = ' a.codEmployee = '.$nombreempdet.' and ';
$valor_empresadet2 = ' g.codClient = 0 and ';
$valor_empleadodet2 = ' g.codEmployee = '.$nombreempdet.' and ';

} //fin if 3.2

if($empresa == -1) { //if 3.3
	$valor_empresadet = ' ';
	$valor_empleadodet = ' ';
	$valor_empresadet2 = ' ';
	$valor_empleadodet2 = ' ';
	$nomempdet = 'Todos';
} //fin if 3.3

 $result2 = mysqli_query($link, "select final2.codigo as codigo, final2.nrodoc as nrodoc, final2.fecha as fecha, final2.fecha_cobro as fecha_cobro, final2.concepto as concepto, final2.concepto_ingreso as concepto_ingreso, final2.via_cobro as via_cobro, final2.empresa as empresa, final2.moneda as moneda, final2.glosa as glosa, final2.total as total, final2.tipo as tipo, final2.tasa as tasa, final2.total_om as total_om, final2.papa as papa, final2.cod_papa as cod_papa
from 
( 
select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via as via_cobro, final.empresa as empresa,  final.moneda as moneda, final.glosa as glosa, final.cxc as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cobro as fecha_cobro, otro.concepto as concepto, otro.concepto_ingreso as concepto_ingreso, otro.via as via, otro.empresa as empresa, otro.moneda as moneda, otro.glosa as glosa, otro.cxc as cxc, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cxc as total, otro.papa as papa, otro.cod_papa as cod_papa
from (
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c,
agnCompany d, actCurrency f
where 
$valor_empresadet 
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c,
agnCompany d, actCurrency f
where 
$valor_empresadet 
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda = t.otra_moneda) otro) final


UNION ALL 

select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empresa, final.moneda as moneda, final.glosa as glosa, final.cxc as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cobro as fecha_cobro, otro.concepto as concepto, otro.concepto_ingreso as concepto_ingreso, otro.via as via_cobro, otro.empleado as empleado, otro.moneda as moneda, otro.glosa as glosa, otro.cxc as cxc, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cxc as total, otro.papa as papa, otro.cod_papa as cod_papa
from (
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c, agnPerson e, actCurrency f
where 
$valor_empleadodet 
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c,
agnPerson e, actCurrency f
where 
$valor_empleadodet  
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda = t.otra_moneda) otro) final) final2 
order by final2.fecha, final2.codigo;");

 ?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario_det; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Detalle Cuentas por Cobrar a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro_det; ?></TD>
        <TD width="25%"><b>Empresa/Empleado: </b><?php echo $nomempdet; ?></TD>
        <TD width="25%"><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></TD>
        <TD width="25%"><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc_det; ?></TD>
        <TD colspan="2"><b>Expresado en: </b><?php echo $nom_otra_moneda_det; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc_det == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc_det; ?>&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc_det; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>

</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
	<TR BGCOLOR='#ffcccc'> 
 	<TD align="left" colspan="15"><b>Saldo inicial en <?php echo $nom_otra_moneda_det; ?></b></TD>
    <TD align="right"><b><?php echo number_format($totaldet,$n_decimales); ?></b></TD></TR> 
 	<thead>
    <TR> 
    <TD align="center"><b>Tipo</b></TD>
 	<TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Nro. Doc.</b></TD>
	<TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center" width="65"><b>Fecha Cobro</b></TD>
    <TD align="center"><b>Concepto Ingreso</b></TD>
    <TD align="center"><b>Via Cobro</b></TD>
    <TD align="center"><b>Empresa/Empleado</b></TD>
    <TD align="center"><b>Glosa</b></TD>
    <TD align="center"><b>Gen. Por</b></TD>
    <TD align="center"><b>Mon.</b></TD>
    <TD align="center"><b>Monto</b></TD>
    <TD align="center"><b>Tasa</b></TD>
    <TD align="center"><b>D&eacute;bito en <?php echo $nom_otra_moneda_det; ?></b></TD>
    <TD align="center"><b>Cr&eacute;dito en <?php echo $nom_otra_moneda_det; ?></b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda_det; ?></b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total = 0;
  $suma_periodo = 0;
  $suma_deb = 0;
  $suma_cred = 0;
  //esta matriz guarda el codigo de la cxc para mostrar los cobros que se hicieron en el periodo y no tienen cxc asociada
  $v = 1;
  $matriz_verif = array();
while ($row = mysqli_fetch_array($result2)) { //while
	//para enlazar al que genero el asiento
	$papa_componente = $row['papa'];
	$papa_codigo = $row['cod_papa'];
	$usuario = $usuario_det;
	include "../../generadopor.php";
	
	$codigo_det = $row['codigo'];	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
	} else {
	printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
	}
	printf("<td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $row['codigo']);//cod
	printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
	printf("<td align='center'>%s</td>", $row['fecha']);//fecha
	printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
	//printf("<td>%s</td>", $row['concepto']);//concepto viene de los parametros
	printf("<td>%s</td>", $row['concepto_ingreso']);//concepto ingreso
	printf("<td>%s</td>", $row['via_cobro']);//via cobro
	printf("<td>%s</td>", $row['empresa']);//empresa
	printf("<td>%s</td>", $row['glosa']);//glosa
	printf("<td align='center'>%s</td>", $papa_enlace);//generado por
	printf("<td>%s</td>", $row['moneda']);//moneda
	
	if($row['total'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
	} else {
		printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
	}
	printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
	
	if($row['total_om'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
	} else {
		printf("<td>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
	}
	
	//$suma_periodo = $suma_periodo + $row['total_om'];
	$total_cxc = $row['total_om'];
	$suma_saldo = $suma_saldo + $total_cxc;
	
	printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));
	
	$color++;
	$matriz_verif[$v][1] = $row['codigo'];
	$v++;
	
	$result3 = mysqli_query($link, "select final2.codigo as codigo, final2.nrodoc as nrodoc, final2.fecha as fecha, final2.fecha_cobro as fecha_cobro, final2.concepto as concepto, final2.concepto_ingreso as concepto_ingreso, final2.via_cobro as via_cobro, final2.empresa as empresa, final2.moneda as moneda, final2.glosa as glosa, final2.total as total, final2.tipo as tipo, final2.tasa as tasa, final2.total_om as total_om, final2.papa as papa, final2.cod_papa as cod_papa
from
(
select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cob_pag as fecha_cobro, final.concepto as concepto, final.con_ing_egr as concepto_ingreso, final.via_cobro as via_cobro, final.empresa as empresa,  final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, 
otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, 
otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, 
otro.via_cobro as via_cobro, otro.empresa as empresa, 
otro.moneda_cxc as moneda, otro.glosa as glosa, 
otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency

union all

select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final


UNION ALL 


select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, 
otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
otro.via_cobro as via_cobro, otro.empleado as empleado, 
otro.moneda_cxc as moneda, otro.glosa as glosa, 
otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final) final2 
order by final2.fecha, final2.codigo;");
	$color2 = $color;
	$suma_det = 0;
	while ($row = mysqli_fetch_array($result3)) {//while 3
		//para enlazar al que genero el asiento
		$papa_componente = $row['papa'];
		$papa_codigo = $row['cod_papa'];
		$usuario = $usuario_det;
		include "../../generadopor.php";
	
		$cod_cobro = $row['codigo'];
		$tipo2 = $row['via_cobro'];
		if($color2 % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
		} else {
		printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
		}
		
		if($tipo2 == 'Liquidacion') {//if liquidacion
			printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
		} else {//else liquidacion
			printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
		}//fin if liquidacion
		
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>%s</td>", $row['fecha']);//fecha
		printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
		//printf("<td>%s</td>", $row['concepto']);//concepto 
		printf("<td>%s</td>", $row['concepto_ingreso']);//concepto cobro
		printf("<td>%s</td>", $row['via_cobro']);//via cobro
		printf("<td>%s</td>", $row['empresa']);//empresa
		printf("<td>%s</td>", $row['glosa']);//glosa
		printf("<td align='center'>%s</td>", $papa_enlace);//generado por
		printf("<td>%s</td>", $row['moneda']);//moneda
		
		if($row['total'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
		}
		printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
		
		if($row['total_om'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
		} else {
		printf("<td>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		}
		$suma_det = $suma_det + $row['total_om'];
		$suma_saldo = $suma_saldo + $row['total_om'];
		printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
		
		$color2++;
	}//fin while 3
	mysqli_free_result($result3);
	
	if(($total_cxc + $suma_det) > 0) {
	printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='13'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
	printf("<td align='right'><b>%s</b></td>", number_format($total_cxc + $suma_det,$n_decimales));//total cuenta
	printf("<td>&nbsp;</td>");//espacio al final
	} else {
	printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='14'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
	printf("<td align='right'><b>%s</b></td>", number_format(($total_cxc + $suma_det)*-1,$n_decimales));//total cuenta
	}
		
	printf("<td>&nbsp;</td></tr>");//espacio al final
	
	$suma_periodo = $suma_periodo + $total_cxc + $suma_det;
}//fin while
mysqli_free_result($result2);
$suma_total = $suma_periodo + $totaldet; 

//verificacion si existe un cobro que no tenga cxc en ese periodo total_periodo viene del link
	if($total_periodo != 0) {//if total periodo
	$cadena_no = '';
	for($w = 1; $w < $v; $w++) { 
		$cadena_no = $cadena_no . $matriz_verif[$w][1].',';
	}
	
	if($cadena_no != '') {
	$cadena_no = ' where final.cod_cxc not in ('.substr($cadena_no,0,-1).')';
	} else {
	$cadena_no = ' ';	
	}
	

$result3 = mysqli_query($link, "select final2.codigo as codigo, final2.nrodoc as nrodoc, final2.fecha as fecha, final2.fecha_cobro as fecha_cobro, final2.concepto as concepto, final2.concepto_ingreso as concepto_ingreso, final2.via_cobro as via_cobro, final2.empresa as empresa, final2.moneda as moneda, final2.glosa as glosa, final2.total as total, final2.tipo as tipo, final2.tasa as tasa, final2.total_om as total_om, final2.cod_cxc as cod_cxc, final2.papa as papa, final2.cod_papa as cod_papa
from
(
select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cob_pag as fecha_cobro, final.concepto as concepto, final.con_ing_egr as concepto_ingreso, final.via_cobro as via_cobro, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, otro.via_cobro as via_cobro, otro.empresa as empresa, otro.moneda_cxc as moneda, otro.glosa as glosa, otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency

union all

select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empresadet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final 
$cadena_no  


UNION ALL 


select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, 
otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
otro.via_cobro as via_cobro, otro.empleado as empleado, 
otro.moneda_cxc as moneda, otro.glosa as glosa, 
otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, 
otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h
where 
$valor_empleadodet2
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final
$cadena_no ) final2 
order by final2.fecha, final2.codigo;");
$color3 = $color2;
$suma_det_solo = 0;
	while ($row = mysqli_fetch_array($result3)) {//while 3
		//para enlazar al que genero el asiento
		$papa_componente = $row['papa'];
		$papa_codigo = $row['cod_papa'];
		$usuario = $usuario_det;
		include "../../generadopor.php";
		
		$cod_cobro = $row['codigo'];
		$tipo2 = $row['via_cobro'];
		if($color3 % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
		} else {
		printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
		}
		
		if($tipo2 == 'Liquidacion') {//if liquidacion
			printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
		} else {//else liquidacion
			printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
		}//fin if liquidacion
		
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>%s</td>", $row['fecha']);//fecha
		printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
		//printf("<td>%s</td>", $row['concepto']);//concepto 
		printf("<td>%s</td>", $row['concepto_ingreso']);//concepto cobro
		printf("<td>%s</td>", $row['via_cobro']);//via cobro
		printf("<td>%s</td>", $row['empresa']);//empresa
		printf("<td>%s</td>", $row['glosa']);//glosa
		printf("<td align='center'>%s</td>", $papa_enlace);//generado por
		printf("<td>%s</td>", $row['moneda']);//moneda
		
		if($row['total'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
		}
		printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
		
		if($row['total_om'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
		} else {
		printf("<td>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		}
		$suma_det_solo = $suma_det_solo + $row['total_om'];
		$suma_saldo = $suma_saldo + $row['total_om'];
		printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
		
		$color3++;
	}//fin while 3
	mysqli_free_result($result3);
if($suma_det_solo != 0) {
	$suma_periodo = $suma_periodo + $suma_det_solo;	
	$suma_total = $suma_periodo + $totaldet;
}
	} //fin if total periodo
 ?>
<TR BGCOLOR='#ffcccc'> 
  <TD align="left" colspan="13"><b>Total Periodo en <?php echo $nom_otra_moneda_det; ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_deb,$n_decimales); ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_cred*-1,$n_decimales); ?></b></TD>
  <?php if($suma_periodo >= 0) { ?>
  <TD align="right"><b><?php echo number_format($suma_periodo,$n_decimales); ?></b></TD>
  <?php } else { ?>
  <TD align="right"><b><?php echo number_format($suma_periodo*-1,$n_decimales); ?></b></TD>
  <?php } ?>
  </TR> 
  <TR BGCOLOR='#ffcccc'> 
  <TD align="left" colspan="15"><b>Total en <?php echo $nom_otra_moneda_det; ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_total,$n_decimales); ?></b></TD></TR> 
 </tbody>
 </table>
  <?php
 
} //fin if 3



//agrupar = 2 por vendedor
//es parecido al de arriba pero tomo en cuenta la nota de venta no solo la CxC

if($agrupar == 2) {//if agrupar 2

//Inicio reporte cuentas por cobrar saldo a fecha

if($rep == 6 && $tipo == 1) { // if 2

//nombre otra moneda
$resultotra = mysqli_query($link, "SELECT fldName as otra_moneda
from
actCurrency
where
pkyCurrency = '$otra_moneda' and
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultotra)) {
	$nom_otra_moneda = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);

if($concepto_cobro == 0) { // if concepto cobro
	$nom_concepto_cobro = 'Todos';
	$valor_concepto = ' ';
	$valor_concepto2 = ' ';
} else {
	$resultcon = mysqli_query($link, "select pkyAccountsReceivableConcept as codigo, fldName as nombre
from colAccountsReceivableConcept
where
pkyAccountsReceivableConcept = '$concepto_cobro';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_cobro = $row['codigo'].' - '.$row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto = ' a.codConcept = '. $concepto_cobro .' and ';
	$valor_concepto2 = ' c.codConcept = '. $concepto_cobro .' and ';
}//fin if concepto de cobro

if ($cuenta_concepto_cxc == 0) { // if 2.3.1
	$nom_cuenta_concepto_cxc = 'Todos';
	$valor_cuenta_concepto_cxc = ' ';
	$valor_cuenta_concepto_cxc2 = ' ';
} else {
	$valor_cuenta_concepto_cxc = ' c.codAccount = ' .$cuenta_concepto_cxc. ' and ';
	$valor_cuenta_concepto_cxc2 = ' e.codAccount = ' .$cuenta_concepto_cxc. ' and ';
	//nombre de la cuenta contable del concepto de cxc
	$result2 = mysqli_query($link, "select pkyAccount, fldName 
							from actAccount 
							where 
							pkyAccount = '$cuenta_concepto_cxc' and
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result2)) {
		$nom_cuenta_concepto_cxc = $row['pkyAccount'].' - '.$row['fldName'];
	}
	mysqli_free_result($result2);
} //fin if 2.3.1

//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, segun lo que elijan, antes solo era fecah final del reporte, '$ultimo_tc' as tc, tambien sirve para mostar en la cabecera
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafin' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc = $row['tc'];
	}
	mysqli_free_result($resultom);

$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc';");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

$resulttcdet = mysqli_query($link, "select a.pkyExchangeRateDetail as cod_tc_det, a.codBaseCurrency as cod_mon_target, b.fldName as mon_target, b.txtDescription as nom_mon_target, a.codTargetCurrency as cod_mon_base, c.fldName as mon_base, c.txtDescription as nom_mon_base, a.fldRate as tasa
from
actExchangeRateDetail a, actCurrency b, actCurrency c
where
a.codExchangeRate = '$ultimo_tc' and 
a.codBaseCurrency = '$cod_moneda_principal' and 
a.codBaseCurrency = b.pkyCurrency and 
a.codTargetCurrency = c.pkyCurrency 
order by cod_mon_target, cod_mon_base;");
$ma_tc = array();
$m = 1;
while ($row = mysqli_fetch_array($resulttcdet)) {
	$ma_tc [$m][1] = $row['mon_base'];
	$ma_tc [$m][2] = $row['mon_target'];
	$ma_tc [$m][3] = $row['tasa'];
	$m++;
}
mysqli_free_result($resulttcdet);
$fin_m = $m - 1;

//segun el tc
if($usar_tc == 0) { 
	$nom_usar_tc = 'De Fecha Final';
	$valor_tc = $ultimo_tc.' as tc';
} else {
	$nom_usar_tc = 'De Fecha Transacci&oacute;n';
	$valor_tc = ' a.codExchangeRate as tc';
}


if($cod_contexto == -1){ 
	$nom_contexto = 'Todos';
	$valor_contexto = ' ';
} else {
	$resultcontx = mysqli_query($link, "select pkyContext as cod_contexto, fldName as contexto, codCostCenter as cod_cc 
	from srvContext
	where 
	pkyContext = '$cod_contexto';");
		while ($row = mysqli_fetch_array($resultcontx)) {   
			$nom_contexto = $row['cod_contexto'].' - '.$row['contexto'];
		}
		mysqli_free_result($resultcontx);
	$valor_contexto = ' a.sysContext = '.$cod_contexto.' and ';	
}
/*
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc' and
codBaseCurrency = '$otra_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
$matriz_tc = array();
$i = 1;
while ($row = mysqli_fetch_array($resulttc)) {
	$matriz_tc [$i][1] = $row['codigotc'];//codigo tc
	$matriz_tc [$i][2] = $row['monedabase'];//codigo moneda base
	$matriz_tc [$i][3] = $row['monedacambio'];//codigo moneda cambio
	$matriz_tc [$i][4] = $row['tc'];//valor a multiplicar del tc 
	$i++;
	}
	mysqli_free_result($resulttc);

$fin_om = $i - 1;
*/
if ($empresaoempleado == -1) { // if 2.2
	
	$empresa = 1;
	if($nombreemp == 0) {
	$nom_orden = 'Nombre';
	$nom_cliente = 'Empresas';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultcli = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
								from agnCompany
								where
								pkyCompany = '$nombreemp' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultcli)) {
			$nom_cliente = $row['codigo'].' - '.$row['empresa'];
		}
		mysqli_free_result($resultcli);
	$valor_cliente = ' a.codClient = '. $nombreemp .' and ';
	$valor_cliente2 = ' c.codClient = '. $nombreemp .' and ';
	}
//$valor_empo = ' a.codClient is not NULL ';
$valor_empo = ' a.codClient is not NULL and ';
$valor_empo2 = ' c.codClient is not NULL and ';
}//fin if 2.2

if ($empresaoempleado == -2) { // if 2.3
	
	$empresa = 0;
	if($nombreemp == 0) {
	$nom_orden = 'Nombre';
	$nom_cliente = 'Empleados';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultcli = mysqli_query($link, "select pkyPerson as codigo, case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado, 'Empleado' as tipo
								from agnPerson
								where
								pkyPerson = '$nombreemp' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultcli)) {
			$nom_cliente = $row['codigo'].' - '.$row['empleado'];
		}
		mysqli_free_result($resultcli);
	$valor_cliente = ' a.codEmployee = '. $nombreemp .' and ';
	$valor_cliente2 = ' c.codEmployee = '. $nombreemp .' and ';
	}
//$valor_empo = ' a.codEmployee is not NULL ';
$valor_empo = ' a.codEmployee is not NULL and ';
$valor_empo2 = ' c.codEmployee is not NULL and ';
} //fin if 2.3


if ($empresaoempleado == -3) { // if 2.4
	
	$empresa = -1;
	$nom_orden = 'Nombre';
	$nom_cliente = 'Todos';
	$valor_cliente = ' ';
	$valor_cliente2 = ' ';
$valor_empo = ' ';
$valor_empo2 = ' ';
}// fin if 2.4



if ($vendedor == 0) { //if 2.5
    $nom_vendedor = 'Todos';
	$valor_vendedor = ' ';
	$valor_vendedor2 = ' ';
  } else { 
    $valor_vendedor = ' b.codSeller = '.$vendedor.' and ';
	$valor_vendedor2 = ' d.codSeller = '.$vendedor.' and ';
	//$valor_vendedor1 = ' and g.codSeller = '.$vendedor.' ';
	//nombre de vendedor
	$resultven = mysqli_query($link, "select pkyPerson as codigo, case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as vendedor
from agnPerson
where
pkyPerson = '$vendedor' and
sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($resultven)) {
	$nom_vendedor = $row['codigo'].' - '.$row['vendedor'];
	}
	mysqli_free_result($resultven);
  } //fin if 2.5

	//listado de vendedores
	//si el vendedor ya no tiene marcado autorizado a vender e hizo notas de venta no despliega (quitar el fldCanSell = 1 and puede hacer que se ponga lento el reporte si hay muchos empleados)
	$result = mysqli_query($link, "select pkyPerson as codigo, case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as vendedor
from agnPerson
where
fldIsEmployee = 1 and
fldCanSell = 1 and 
sysEnabled = 1 and sysAuthorized = 1;");
		
	//inicio calculo saldo inicial
	
	//CxC vendedores
	$result3 = mysqli_query($link, "select final.cod_ven as cod_ven, sum(final.total) as cxc
from(
select otra.cod_ven as cod_ven, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_ven as cod_ven, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select b.codSeller as cod_ven, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, slsSalesNote b, colAccountsReceivableConcept c
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo  
$valor_vendedor 
$valor_contexto 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = b.pkySalesNote and 
a.fldDate < '$fechaini' and 
a.codConcept = c.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_ven, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_ven as cod_ven, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select b.codSeller as cod_ven, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, slsSalesNote b, colAccountsReceivableConcept c
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo  
$valor_vendedor 
$valor_contexto 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = b.pkySalesNote and 
a.fldDate < '$fechaini' and 
a.codConcept = c.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_ven, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_ven
order by final.cod_ven;");

	//suma Cobros vendedores
	$result5 = mysqli_query($link, "select final.cod_ven as cod_ven, sum(final.total) as suma_cobros
from(
select otra.cod_ven as cod_ven, otra.suma_cobros as suma_cobros,
 otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
 otra.cod_moneda_cxc as cod_moneda_cxc, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_cobros * otra.tasa as total
from
(select t.cod_ven as cod_ven, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_ven as cod_ven, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyCollection = b.codCollection and
a.fldDate < '$fechaini' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_ven
order by final.cod_ven;");		

$matriz_salini = array();
$i = 1;
while ($row = mysqli_fetch_array($result)) {
	$matriz_salini [$i][1] = $row['codigo'];//cod vendedor
	$matriz_salini [$i][2] = $row['vendedor'];//nombre vendedor
	$matriz_salini [$i][3] = 0; //suma cxc
	$matriz_salini [$i][4] = 0; //suma cobros
	$matriz_salini [$i][5] = 0; //saldo inicial
	$matriz_salini [$i][6] = 0; //suma cxc periodo
	$matriz_salini [$i][7] = 0; //suma cobros periodo
	$matriz_salini [$i][8] = 0; //saldo periodo
	$matriz_salini [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_con = $row['cod_ven'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][3] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_con = $row['cod_ven'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][4] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][3];
	$reg_cobros = $matriz_salini [$i][4];
	$matriz_salini [$i][5] = $reg_cxc - $reg_cobros;
	$i++;
}
	
//fin calculo saldo inicial

//inicio calculo registros

	//CxC vendedores
	$result3 = mysqli_query($link, "select final.cod_ven as cod_ven, sum(final.total) as cxc
from(
select otra.cod_ven as cod_ven, otra.cxc as cxc, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxc * otra.tasa as total
from
(select t.cod_ven as cod_ven, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select b.codSeller as cod_ven, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, slsSalesNote b, colAccountsReceivableConcept c
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo  
$valor_vendedor 
$valor_contexto 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = b.pkySalesNote and 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = c.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_ven, cod_moneda, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_ven as cod_ven, t.cxc as cxc, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select b.codSeller as cod_ven, sum(a.fldTotal) as cxc, 
a.codCurrency as cod_moneda, $valor_tc, '$otra_moneda' as otra_moneda
from colAccountsReceivable a, slsSalesNote b, colAccountsReceivableConcept c
where 
$valor_cliente 
$valor_concepto 
$valor_cuenta_concepto_cxc 
$valor_empo  
$valor_vendedor 
$valor_contexto 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = b.pkySalesNote and 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codConcept = c.pkyAccountsReceivableConcept and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_ven, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_ven
order by final.cod_ven;");
	
	//suma Cobros vendedores
	$result5 = mysqli_query($link, "select final.cod_ven as cod_ven, sum(final.total) as suma_cobros
from(
select otra.cod_ven as cod_ven, otra.suma_cobros as suma_cobros,
 otra.cod_moneda_cobro as cod_moneda_cobro, otra.tc as tc, 
 otra.cod_moneda_cxc as cod_moneda_cxc, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_cobros * otra.tasa as total
from
(select t.cod_ven as cod_ven, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_ven as cod_ven, t.suma_cobros as suma_cobros, 
t.cod_moneda_cobro as cod_moneda_cobro, t.tc as tc, 
t.cod_moneda_cxc as cod_moneda_cxc, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable is not null and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc
union all
select d.codSeller as cod_ven, sum(b.fldTotal) as suma_cobros,
a.codCurrency as cod_moneda_cobro, $valor_tc, 
c.codCurrency as cod_moneda_cxc, '$otra_moneda' as otra_moneda
from colCollection a, colCollectionDetail b, colAccountsReceivable c, slsSalesNote d, colAccountsReceivableConcept e
where 
$valor_cliente2 
$valor_concepto2 
$valor_cuenta_concepto_cxc2 
$valor_empo2 
$valor_vendedor2 
$valor_contexto 
c.codConcept = e.pkyAccountsReceivableConcept and 
c.fldParentComponent = 'ComponentSalesNote' and 
c.cosComponentKey = d.pkySalesNote and 
a.pkyCollection = b.codCollection and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
b.codAccountsReceivable = c.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_ven, cod_moneda_cobro, cod_moneda_cxc, tc) t
where
t.cod_moneda_cxc = t.otra_moneda) otra) final
group by final.cod_ven
order by final.cod_ven;");	

//CxC
while ($row = mysqli_fetch_array($result3)) {
	$i = 1;
	$cod_con = $row['cod_ven'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][6] = $row['cxc'];
}
mysqli_free_result($result3);

//Cobros
while ($row = mysqli_fetch_array($result5)) {
	$i = 1;
	$cod_con = $row['cod_ven'];
	while ($cod_con <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][7] = $row['suma_cobros'];
}
mysqli_free_result($result5);

$i = 1;
while($i <= $fin) {
	$reg_cxc = $matriz_salini [$i][6];
	$reg_cobros = $matriz_salini [$i][7];
	$matriz_salini [$i][8] = $reg_cxc - $reg_cobros;
	$reg_salini = $matriz_salini [$i][5];
	$reg_periodo = $matriz_salini [$i][8];
	$matriz_salini [$i][9] = $reg_salini + $reg_periodo;
	$i++;
}
	
//fin calculo registros
		?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Cuentas por Cobrar Saldo a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Empresa/Empleado: </b><?php echo $nom_cliente; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro; ?></TD>
        <TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Vendedor: </b><?php echo $nom_vendedor; ?></TD>
        <TD><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        </TR>
        <TR>
        <TD><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        <TD><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc; ?></TD>
		<TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        <TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>

</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Vendedor</b></TD>
	<TD align="center"><b>CxC Sal. Ini.</b></TD>
    <TD align="center"><b>Cob. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxC Periodo</b></TD>
    <TD align="center"><b>Cobros Periodo</b></TD>
	<TD align="center"><b>Total Periodo</b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda; ?></b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total_cxc = 0;
  $suma_total_cobros = 0;
  $suma_total_ini = 0;
  $suma_total_cxc_per = 0;
  $suma_total_cobros_per = 0;
  $suma_total_periodo = 0;
  $suma_total = 0;
  $j = 1;
  while ($j <= $fin) { //while
	
	while($matriz_salini [$j][3] == 0 && $matriz_salini [$j][4] == 0 && $matriz_salini [$j][5] == 0 && $matriz_salini [$j][6] == 0 && $matriz_salini [$j][7] == 0 && $matriz_salini [$j][8] == 0 && $j <= $fin)
	{ $j++; }
	
	if($j > $fin) { //if ultimo 0
	} else { //else ultimo 0
	
	$codigo = $matriz_salini [$j][1];
	$totaldet = $matriz_salini [$j][5];
	
	if($saldo_cero == 1 && $matriz_salini [$j][9] == 0) { //if saldo cero
	} else { //else saldo cero
	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} else { 
	printf("<tr><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} //cierra if color
	printf("<td align='left'>%s</td>", $matriz_salini [$j][2]);//concepto
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][3],$n_decimales));//CxC saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][4],$n_decimales));// cobros saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][5],$n_decimales));// saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][6],$n_decimales));// suma CxC periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][7],$n_decimales));// suma cobros periodo
	$total_periodo = $matriz_salini [$j][7];
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][8],$n_decimales));// total saldo periodo
	printf("<td align='right'><a href='report.php?rep=6&tipo=4&nombredet=$codigo&nombreempdet=$nombreemp&empresa=$empresa&concepto_cobro_det=$concepto_cobro&cuenta_concepto_cxc_det=$cuenta_concepto_cxc&fechainidet=$fechaini&fechafindet=$fechafin&totaldet=$totaldet&otra_moneda_det=$otra_moneda&total_periodo=$total_periodo&usar_tc_det=$usar_tc&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini [$j][9],$n_decimales));//total
	   
	$suma_total_cxc = $suma_total_cxc + $matriz_salini [$j][3];
    $suma_total_cobros = $suma_total_cobros + $matriz_salini [$j][4];
	$suma_total_ini = $suma_total_ini + $matriz_salini [$j][5];
	
    $suma_total_cxc_per = $suma_total_cxc_per + $matriz_salini [$j][6];
    $suma_total_cobros_per = $suma_total_cobros_per + $matriz_salini [$j][7];
	$suma_total_periodo = $suma_total_periodo + $matriz_salini [$j][8];
    
    $suma_total = $suma_total + $matriz_salini [$j][9];
	$color++;
	
	} //fin if saldo cero
	
	} //cierra else ultimo 0
	
    $j++;
}//fin while


?>
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total Cuentas <?php echo $nom_cliente; ?></b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_ini,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxc_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cobros_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_periodo,$n_decimales)); ?>
</td>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total,$n_decimales)); ?>
</td></tr>
</tbody>
</table>
<?php

} //fin if 2

} //fin if agrupar 1



// inicio muestra detalle agrupado por vendedor
// el detalle esta fuera del agrupar porque no puedo enviar por POST y GET la variable agrupar 


if($rep == 6 && $tipo == 4) { // if 4

 //nombre otra moneda
$resultotra = mysqli_query($link, "SELECT fldName as otra_moneda
from
actCurrency
where
pkyCurrency = '$otra_moneda_det' and
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultotra)) {
	$nom_otra_moneda_det = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);


//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, segun lo que elijan, antes solo era fecah final del reporte, '$ultimo_tc' as tc, tambien sirve para mostar en la cabecera
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafindet' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc_det = $row['tc'];
	}
	mysqli_free_result($resultom);

$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc_det';");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

$resulttcdet = mysqli_query($link, "select a.pkyExchangeRateDetail as cod_tc_det, a.codBaseCurrency as cod_mon_target, b.fldName as mon_target, b.txtDescription as nom_mon_target, a.codTargetCurrency as cod_mon_base, c.fldName as mon_base, c.txtDescription as nom_mon_base, a.fldRate as tasa
from
actExchangeRateDetail a, actCurrency b, actCurrency c
where
a.codExchangeRate = '$ultimo_tc_det' and 
a.codBaseCurrency = '$cod_moneda_principal' and 
a.codBaseCurrency = b.pkyCurrency and 
a.codTargetCurrency = c.pkyCurrency 
order by cod_mon_target, cod_mon_base;");
$ma_tc = array();
$m = 1;
while ($row = mysqli_fetch_array($resulttcdet)) {
	$ma_tc [$m][1] = $row['mon_base'];
	$ma_tc [$m][2] = $row['mon_target'];
	$ma_tc [$m][3] = $row['tasa'];
	$m++;
}
mysqli_free_result($resulttcdet);
$fin_m = $m - 1;

//segun el tc
if($usar_tc_det == 0) { 
	$nom_usar_tc_det = 'De Fecha Final';
	$valor_tc_det = $ultimo_tc_det.' as tc';
} else {
	$nom_usar_tc_det = 'De Fecha Transacci&oacute;n';
	$valor_tc_det = ' a.codExchangeRate as tc';
}


if($cod_contexto_det == -1){ 
	$nom_contexto_det = 'Todos';
	$valor_contexto_det = ' ';
} else {
	$resultcontx = mysqli_query($link, "select pkyContext as cod_contexto, fldName as contexto, codCostCenter as cod_cc 
	from srvContext
	where 
	pkyContext = '$cod_contexto_det';");
		while ($row = mysqli_fetch_array($resultcontx)) {   
			$nom_contexto_det = $row['cod_contexto'].' - '.$row['contexto'];
		}
		mysqli_free_result($resultcontx);
	$valor_contexto_det = ' a.sysContext = '.$cod_contexto_det.' and ';	
}
/*
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc_det' and
codBaseCurrency = '$otra_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
$matriz_tc = array();
$i = 1;
while ($row = mysqli_fetch_array($resulttc)) {
	$matriz_tc [$i][1] = $row['codigotc'];//codigo tc
	$matriz_tc [$i][2] = $row['monedabase'];//codigo moneda base
	$matriz_tc [$i][3] = $row['monedacambio'];//codigo moneda cambio
	$matriz_tc [$i][4] = $row['tc'];//valor a multiplicar del tc 
	$i++;
	}
	mysqli_free_result($resulttc);

$fin_om = $i - 1;
*/

$resultven = mysqli_query($link, "select pkyPerson as codigo, case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as vendedor
from agnPerson
where
fldIsEmployee = 1 and
fldCanSell = 1 and 
pkyPerson = '$nombredet';");
	while ($row = mysqli_fetch_array($resultven)) {   
	$nom_vendedor_det = $row['codigo'].' - '.$row['vendedor'];
	}
	mysqli_free_result($resultven);

if($empresa == 1) { //if 3.1
  
 // detalle empresa
  $result = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
from agnCompany
where
pkyCompany = '$nombreempdet' and
sysEnabled = 1 and sysAuthorized = 1;");
 
while ($row = mysqli_fetch_array($result)) {
	$nomempdet = $row['codigo'].' - '.$row['empresa'];
}
mysqli_free_result($result);
$valor_empresadet = ' a.codClient = '.$nombreempdet.' and ';
$valor_empleadodet = ' a.codEmployee = 0 and ';
$valor_empresadet2 = ' g.codClient = '.$nombreempdet.' and ';
$valor_empleadodet2 = ' g.codEmployee = 0 and ';

} //fin if 3.1

if($empresa == 0) { //if 3.2
 
 // detalle empleado
 
 $result = mysqli_query($link, "select pkyPerson as codigo, 
case when fldMiddleName is NULL then concat(fldLastName,', ',fldFirstName) else concat(fldLastName,' ',fldMiddleName,', ',fldFirstName) end as empleado
from agnPerson
where
pkyPerson = '$nombreempdet' and 
sysEnabled = 1 and sysAuthorized = 1
order by empleado;");
while ($row = mysqli_fetch_array($result)) {
	$nomempdet = $row['codigo'].' - '.$row['empleado'];
}
mysqli_free_result($result);
$valor_empresadet = ' a.codClient = 0 and ';
$valor_empleadodet = ' a.codEmployee = '.$nombreempdet.' and ';
$valor_empresadet2 = ' g.codClient = 0 and ';
$valor_empleadodet2 = ' g.codEmployee = '.$nombreempdet.' and ';

} //fin if 3.2

if($empresa == -1) { //if 3.3
	$valor_empresadet = ' ';
	$valor_empleadodet = ' ';
	$valor_empresadet2 = ' ';
	$valor_empleadodet2 = ' ';
	$nomempdet = 'Todos';
} //fin if 3.3

if($concepto_cobro_det == 0) { // if concepto cobro
	$nom_concepto_cobro_det = 'Todos';
	$valor_concepto_det = ' ';
	$valor_concepto_det2 = ' ';
} else {
	$resultcon = mysqli_query($link, "select pkyAccountsReceivableConcept as codigo, fldName as nombre
from colAccountsReceivableConcept
where
pkyAccountsReceivableConcept = '$concepto_cobro_det';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_cobro_det = $row['codigo'].' - '.$row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto_det = ' a.codConcept = '. $concepto_cobro_det .' and ';
	$valor_concepto_det2 = ' g.codConcept = '. $concepto_cobro_det .' and ';
}//fin if concepto de cobro

if ($cuenta_concepto_cxc_det == 0) { // if 2.3.1
	$nom_cuenta_concepto_cxc_det = 'Todos';
	$valor_cuenta_concepto_cxc_det = ' ';
	$valor_cuenta_concepto_cxc2_det = ' ';
	$valor_cuenta_concepto_cxc3_det = ' ';
} else {
	$valor_cuenta_concepto_cxc_det = ' b.codAccount = ' .$cuenta_concepto_cxc_det. ' and ';
	$valor_cuenta_concepto_cxc2_det = ' e.codAccount = ' .$cuenta_concepto_cxc_det. ' and ';
	$valor_cuenta_concepto_cxc3_det = ' j.codAccount = ' .$cuenta_concepto_cxc_det. ' and ';
	//nombre de la cuenta contable del concepto de cxc
	$result2 = mysqli_query($link, "select pkyAccount, fldName 
							from actAccount 
							where 
							pkyAccount = '$cuenta_concepto_cxc_det' and
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result2)) {
		$nom_cuenta_concepto_cxc_det = $row['pkyAccount'].' - '.$row['fldName'];
	}
	mysqli_free_result($result2);
} //fin if 2.3.1


 $result2 = mysqli_query($link, "select final2.codigo as codigo, final2.nrodoc as nrodoc, final2.fecha as fecha, final2.fecha_cobro as fecha_cobro, final2.concepto as concepto, final2.concepto_ingreso as concepto_ingreso, final2.via_cobro as via_cobro, final2.empresa as empresa, final2.moneda as moneda, final2.glosa as glosa, final2.total as total, final2.tipo as tipo, final2.tasa as tasa, final2.total_om as total_om, final2.papa as papa, final2.cod_papa as cod_papa
from 
( 
select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via as via_cobro, final.empresa as empresa,  final.moneda as moneda, final.glosa as glosa, final.cxc as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cobro as fecha_cobro, otro.concepto as concepto, otro.concepto_ingreso as concepto_ingreso, otro.via as via, otro.empresa as empresa, otro.moneda as moneda, otro.glosa as glosa, otro.cxc as cxc,
otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cxc as total, otro.papa as papa, otro.cod_papa as cod_papa
from (
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c,
agnCompany d, actCurrency f, slsSalesNote g
where 
$valor_empresadet 
$valor_concepto_det 
$valor_cuenta_concepto_cxc_det 
$valor_contexto_det 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = g.pkySalesNote and 
g.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c,
agnCompany d, actCurrency f, slsSalesNote g
where 
$valor_empresadet 
$valor_concepto_det 
$valor_cuenta_concepto_cxc_det 
$valor_contexto_det 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = g.pkySalesNote and 
g.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda = t.otra_moneda) otro) final


UNION ALL 

select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empresa, final.moneda as moneda, final.glosa as glosa, final.cxc as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cobro as fecha_cobro, otro.concepto as concepto, otro.concepto_ingreso as concepto_ingreso, otro.via as via_cobro, otro.empleado as empleado, otro.moneda as moneda, otro.glosa as glosa, otro.cxc as cxc, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cxc as total, otro.papa as papa, otro.cod_papa as cod_papa
from (
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c, agnPerson e, actCurrency f, slsSalesNote g
where 
$valor_empleadodet 
$valor_concepto_det 
$valor_cuenta_concepto_cxc_det 
$valor_contexto_det 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = g.pkySalesNote and 
g.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, t.fecha_cobro as fecha_cobro, t.concepto as concepto, t.concepto_ingreso as concepto_ingreso, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxc as cxc, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsReceivable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldCollectionDate as fecha_cobro, b.fldName as concepto, c.fldName as concepto_ingreso, null as via, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxc, 'CxC' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from colAccountsReceivable a, colAccountsReceivableConcept b, colIncomeConcept c,
agnPerson e, actCurrency f, slsSalesNote g
where 
$valor_empleadodet 
$valor_concepto_det 
$valor_cuenta_concepto_cxc_det 
$valor_contexto_det 
a.fldParentComponent = 'ComponentSalesNote' and 
a.cosComponentKey = g.pkySalesNote and 
g.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsReceivableConcept and
a.codIncomeConcept = c.pkyIncomeConcept and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda = t.otra_moneda) otro) final) final2 
order by final2.fecha, final2.codigo;");

 ?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario_det; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Detalle Cuentas por Cobrar a Fecha</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Vendedor: </b><?php echo $nom_vendedor_det; ?></TD>
        <TD width="25%"><b>Empresa/Empleado: </b><?php echo $nomempdet; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_cobro_det; ?></TD>
        <TD width="25%"><b>Cuenta Contable Concepto CxC: </b><?php echo $nom_cuenta_concepto_cxc_det; ?></TD>
        </TR>
        <TR>
        <TD><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></TD>
        <TD><b>Usar Tipo de Cambio: </b><?php echo $nom_usar_tc_det; ?></TD>
        <TD><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
		<TD><b>Expresado en: </b><?php echo $nom_otra_moneda_det; ?></TD>
        </TR>
    </table>

</td>

<?php if ($usar_tc_det == 0) { //if usar tc?>
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc_det; ?>&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc_det; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
<?php } //fin if usar tc?>

</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
	<TR BGCOLOR='#ffcccc'> 
 	<TD align="left" colspan="15"><b>Saldo inicial en <?php echo $nom_otra_moneda_det; ?></b></TD>
    <TD align="right"><b><?php echo number_format($totaldet,$n_decimales); ?></b></TD></TR> 
 	<thead>
    <TR> 
    <TD align="center"><b>Tipo</b></TD>
 	<TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Nro. Doc.</b></TD>
	<TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center" width="65"><b>Fecha Cobro</b></TD>
    <TD align="center"><b>Concepto Ingreso</b></TD>
    <TD align="center"><b>Via Cobro</b></TD>
    <TD align="center"><b>Empresa/Empleado</b></TD>
    <TD align="center"><b>Glosa</b></TD>
    <TD align="center"><b>Gen. Por</b></TD>
    <TD align="center"><b>Mon.</b></TD>
    <TD align="center"><b>Monto</b></TD>
    <TD align="center"><b>Tasa</b></TD>
    <TD align="center"><b>D&eacute;bito en <?php echo $nom_otra_moneda_det; ?></b></TD>
    <TD align="center"><b>Cr&eacute;dito en <?php echo $nom_otra_moneda_det; ?></b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda_det; ?></b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total = 0;
  $suma_periodo = 0;
  $suma_deb = 0;
  $suma_cred = 0;
  //esta matriz guarda el codigo de la cxc para mostrar los cobros que se hicieron en el periodo y no tienen cxc asociada
  $v = 1;
  $matriz_verif = array();
while ($row = mysqli_fetch_array($result2)) { //while
	//para enlazar al que genero el asiento
	$papa_componente = $row['papa'];
	$papa_codigo = $row['cod_papa'];
	$usuario = $usuario_det;
	include "../../generadopor.php";

	$codigo_det = $row['codigo'];	
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
	} else {
	printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
	}
	printf("<td align='center'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_det&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $row['codigo']);//cod
	printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
	printf("<td align='center'>%s</td>", $row['fecha']);//fecha
	printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
	//printf("<td>%s</td>", $row['concepto']);//concepto viene de los parametros
	printf("<td>%s</td>", $row['concepto_ingreso']);//concepto ingreso
	printf("<td>%s</td>", $row['via_cobro']);//via cobro
	printf("<td>%s</td>", $row['empresa']);//empresa
	printf("<td>%s</td>", $row['glosa']);//glosa
	printf("<td align='center'>%s</td>", $papa_enlace);//generado por
	printf("<td>%s</td>", $row['moneda']);//moneda
	
	if($row['total'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
	} else {
		printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
	}
	printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
	
	if($row['total_om'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
	} else {
		printf("<td>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
	}
	
	//$suma_periodo = $suma_periodo + $row['total_om'];
	$total_cxc = $row['total_om'];
	$suma_saldo = $suma_saldo + $total_cxc;
	
	printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));
	
	$color++;
	$matriz_verif[$v][1] = $row['codigo'];
	$v++;
	
	$result3 = mysqli_query($link, "select final2.codigo as codigo, final2.nrodoc as nrodoc, final2.fecha as fecha, final2.fecha_cobro as fecha_cobro, final2.concepto as concepto, final2.concepto_ingreso as concepto_ingreso, final2.via_cobro as via_cobro, final2.empresa as empresa, final2.moneda as moneda, final2.glosa as glosa, final2.total as total, final2.tipo as tipo, final2.tasa as tasa, final2.total_om as total_om, final2.papa as papa, final2.cod_papa as cod_papa
from
(
select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cob_pag as fecha_cobro, final.concepto as concepto, final.con_ing_egr as concepto_ingreso, final.via_cobro as via_cobro, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, 
otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, 
otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, 
otro.via_cobro as via_cobro, otro.empresa as empresa, 
otro.moneda_cxc as moneda, otro.glosa as glosa, 
otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i
where 
$valor_empresadet2 
$valor_concepto_det2 
$valor_cuenta_concepto_cxc2_det 
$valor_contexto_det 
g.codConcept = e.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i
where
$valor_empresadet2 
$valor_concepto_det2 
$valor_cuenta_concepto_cxc2_det 
$valor_contexto_det 
g.codConcept = e.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency

union all

select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, colAccountsReceivableConcept e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i
where 
$valor_empresadet2 
$valor_concepto_det2 
$valor_cuenta_concepto_cxc2_det 
$valor_contexto_det 
g.codConcept = e.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from 
payPayment a, payPaymentDetail b, agnCompany d, colAccountsReceivableConcept e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i
where 
$valor_empresadet2 
$valor_concepto_det2 
$valor_cuenta_concepto_cxc2_det 
$valor_contexto_det 
g.codConcept = e.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final


UNION ALL 


select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, 
otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
otro.via_cobro as via_cobro, otro.empleado as empleado, 
otro.moneda_cxc as moneda, otro.glosa as glosa, 
otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.cobro as total, otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where 
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where 
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsReceivable = '$codigo_det' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final) final2 
order by final2.fecha, final2.codigo;");
	$color2 = $color;
	$suma_det = 0;
	while ($row = mysqli_fetch_array($result3)) {//while 3
		//para enlazar al que genero el asiento
		$papa_componente = $row['papa'];
		$papa_codigo = $row['cod_papa'];
		$usuario = $usuario_det;
		include "../../generadopor.php";
	
		$cod_cobro = $row['codigo'];
		$tipo2 = $row['via_cobro'];
		if($color2 % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
		} else {
		printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
		}
		
		if($tipo2 == 'Liquidacion') {//if liquidacion
			printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
		} else {//else liquidacion
			printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
		}//fin if liquidacion
		
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>%s</td>", $row['fecha']);//fecha
		printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
		//printf("<td>%s</td>", $row['concepto']);//concepto 
		printf("<td>%s</td>", $row['concepto_ingreso']);//concepto cobro
		printf("<td>%s</td>", $row['via_cobro']);//via cobro
		printf("<td>%s</td>", $row['empresa']);//empresa
		printf("<td>%s</td>", $row['glosa']);//glosa
		printf("<td align='center'>%s</td>", $papa_enlace);//generado por
		printf("<td>%s</td>", $row['moneda']);//moneda
		
		if($row['total'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
		}
		printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
		
		if($row['total_om'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
		} else {
		printf("<td>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		}
		$suma_det = $suma_det + $row['total_om'];
		$suma_saldo = $suma_saldo + $row['total_om'];
		printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
		
		$color2++;
	}//fin while 3
	mysqli_free_result($result3);
	
	if(($total_cxc + $suma_det) > 0) {
	printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='13'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
	printf("<td align='right'><b>%s</b></td>", number_format($total_cxc + $suma_det,$n_decimales));//total cuenta
	printf("<td>&nbsp;</td>");//espacio al final
	} else {
	printf("<tr BGCOLOR='ffcccc'><td align='left' colspan='14'><b>Total Cuenta %s</b></td>", $codigo_det);//titulo total cuenta
	printf("<td align='right'><b>%s</b></td>", number_format(($total_cxc + $suma_det)*-1,$n_decimales));//total cuenta
	}
		
	printf("<td>&nbsp;</td></tr>");//espacio al final
	
	$suma_periodo = $suma_periodo + $total_cxc + $suma_det;
}//fin while
mysqli_free_result($result2);
$suma_total = $suma_periodo + $totaldet; 

//verificacion si existe un cobro que no tenga cxc en ese periodo total_periodo viene del link
	if($total_periodo != 0) {//if total periodo
	$cadena_no = '';
	for($w = 1; $w < $v; $w++) { 
		$cadena_no = $cadena_no . $matriz_verif[$w][1].',';
	}
	
	if($cadena_no != '') {
	$cadena_no = ' where final.cod_cxc not in ('.substr($cadena_no,0,-1).')';
	} else {
	$cadena_no = ' ';	
	}
	

$result3 = mysqli_query($link, "select final2.codigo as codigo, final2.nrodoc as nrodoc, final2.fecha as fecha, final2.fecha_cobro as fecha_cobro, final2.concepto as concepto, final2.concepto_ingreso as concepto_ingreso, final2.via_cobro as via_cobro, final2.empresa as empresa, final2.moneda as moneda, final2.glosa as glosa, final2.total as total, final2.tipo as tipo, final2.tasa as tasa, final2.total_om as total_om, final2.cod_cxc as cod_cxc, final2.papa as papa, final2.cod_papa as cod_papa
from
(
select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cob_pag as fecha_cobro, final.concepto as concepto, final.con_ing_egr as concepto_ingreso, final.via_cobro as via_cobro, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, otro.fecha as fecha, otro.fecha_cob_pag as fecha_cob_pag, otro.concepto as concepto, otro.con_ing_egr as con_ing_egr, otro.via_cobro as via_cobro, otro.empresa as empresa, otro.moneda_cxc as moneda, otro.glosa as glosa, otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where 
$valor_empresadet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empresadet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency

union all

select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empresa as empresa, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, d.fldName as empresa, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empresadet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
union all
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, d.fldName as empresa,
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empresadet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final 
$cadena_no  


UNION ALL 


select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_cobro as fecha_cobro, final.concepto as concepto, final.concepto_ingreso as concepto_ingreso, final.via_cobro as via_cobro, final.empleado as empresa, final.moneda as moneda, final.glosa as glosa, final.cobro as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxc as cod_cxc, final.papa as papa, final.cod_papa as cod_papa
from
(
select otro.codigo as codigo, otro.nrodoc as nrodoc, 
otro.fecha as fecha, otro.fecha_cob_pag as fecha_cobro, 
otro.concepto as concepto, otro.con_ing_egr as concepto_ingreso, 
otro.via_cobro as via_cobro, otro.empleado as empleado, 
otro.moneda_cxc as moneda, otro.glosa as glosa, 
otro.cobro as cobro, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxc as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.cobro as total, otro.cod_cxc as cod_cxc, 
otro.papa as papa, otro.cod_papa as cod_papa
from 
(select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
r.fldRate as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where 
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, 
g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxc = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.codigo as codigo, t.nrodoc as nrodoc, t.fecha as fecha, 
t.fecha_cob_pag as fecha_cob_pag, t.concepto as concepto, 
t.con_ing_egr as con_ing_egr, t.via_cobro as via_cobro, 
t.cod_moneda_cxc as cod_moneda_cxc, t.moneda_cxc as moneda_cxc,
t.empleado as empleado, 
t.moneda_cobro as moneda_cobro, t.glosa as glosa, 
t.cobro as cobro, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_cobro as cod_moneda_cobro, 
1 as tasa, t.cod_cxc as cod_cxc, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyCollection as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, c.fldName as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc,
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
colCollection a, colCollectionDetail b, colCollectionRoute c, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = c.pkyCollectionRoute and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
a.pkyCollection = b.codCollection and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1
UNION ALL
select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
null as con_ing_egr, 'Liquidacion' as via_cobro, concat(e.fldLastName,', ',e.fldFirstName) as empleado, g.codCurrency as cod_moneda_cxc, h.fldName as moneda_cxc, 
f.fldName as moneda_cobro, a.txtDescription as glosa, (b.fldTotal * -1) as cobro, 
'Cobro' as tipo, $valor_tc_det, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_cobro, g.pkyAccountsReceivable as cod_cxc, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, colAccountsReceivable g, actCurrency h, slsSalesNote i, colAccountsReceivableConcept j
where
$valor_empleadodet2  
$valor_concepto_det2 
$valor_cuenta_concepto_cxc3_det 
$valor_contexto_det 
g.codConcept = j.pkyAccountsReceivableConcept and 
g.fldParentComponent = 'ComponentSalesNote' and 
g.cosComponentKey = i.pkySalesNote and 
i.codSeller = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsReceivable is not NULL and
b.codAccountsReceivable = g.pkyAccountsReceivable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxc = t.otra_moneda) otro) final
$cadena_no ) final2 
order by final2.fecha, final2.codigo;");
$color3 = $color2;
$suma_det_solo = 0;
	while ($row = mysqli_fetch_array($result3)) {//while 3
		//para enlazar al que genero el asiento
		$papa_componente = $row['papa'];
		$papa_codigo = $row['cod_papa'];
		$usuario = $usuario_det;
		include "../../generadopor.php";
		
		$cod_cobro = $row['codigo'];
		$tipo2 = $row['via_cobro'];
		if($color3 % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='left'>%s</td>", $row['tipo']);//tipo
		} else {
		printf("<tr><td align='left'>%s</td>", $row['tipo']);//tipo
		}
		
		if($tipo2 == 'Liquidacion') {//if liquidacion
			printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Pago'>%s</a></td>", $cod_cobro);//codigo
		} else {//else liquidacion
			printf("<td align='center'><a href='../../ModuleCollections/VoucherCollection/index.php?pkyCollection=$cod_cobro&user=$usuario_det&token=$token' title='Nota de Cobro'>%s</a></td>", $cod_cobro);//codigo
		}//fin if liquidacion
		
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>%s</td>", $row['fecha']);//fecha
		printf("<td align='center'>%s</td>", $row['fecha_cobro']);//fecha cobro
		//printf("<td>%s</td>", $row['concepto']);//concepto 
		printf("<td>%s</td>", $row['concepto_ingreso']);//concepto cobro
		printf("<td>%s</td>", $row['via_cobro']);//via cobro
		printf("<td>%s</td>", $row['empresa']);//empresa
		printf("<td>%s</td>", $row['glosa']);//glosa
		printf("<td align='center'>%s</td>", $papa_enlace);//generado por
		printf("<td>%s</td>", $row['moneda']);//moneda
		
		if($row['total'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total'],$n_decimales));//total
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total']*-1,$n_decimales));//total
		}
		printf("<td align='right'>%s</td>", number_format($row['tasa'], $n_tipocambio));//tasa
		
		if($row['total_om'] >= 0) {
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
		} else {
		printf("<td>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		}
		$suma_det_solo = $suma_det_solo + $row['total_om'];
		$suma_saldo = $suma_saldo + $row['total_om'];
		printf("<td align='right'>%s</td></tr>", number_format($suma_saldo,$n_decimales));//total otra moneda saldo
		
		$color3++;
	}//fin while 3
	mysqli_free_result($result3);
if($suma_det_solo != 0) {
	$suma_periodo = $suma_periodo + $suma_det_solo;	
	$suma_total = $suma_periodo + $totaldet;
}
	} //fin if total periodo
 ?>
<TR BGCOLOR='#ffcccc'> 
  <TD align="left" colspan="13"><b>Total Periodo en <?php echo $nom_otra_moneda_det; ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_deb,$n_decimales); ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_cred*-1,$n_decimales); ?></b></TD>
  <?php if($suma_periodo >= 0) { ?>
  <TD align="right"><b><?php echo number_format($suma_periodo,$n_decimales); ?></b></TD>
  <?php } else { ?>
  <TD align="right"><b><?php echo number_format($suma_periodo*-1,$n_decimales); ?></b></TD>
  <?php } ?>
  </TR> 
  <TR BGCOLOR='#ffcccc'> 
  <TD align="left" colspan="15"><b>Total en <?php echo $nom_otra_moneda_det; ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_total,$n_decimales); ?></b></TD></TR> 
 </tbody>
 </table>
  <?php
 
} //fin if 4




?>

</body>
</html>
