<!DOCTYPE html>
<html lang="es-ES">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Pantalla Reporte Cuentas por Pagar 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";

$rep=$_GET["rep"];
$tipo=$_GET["tipo"];
$agrupar=$_POST["agrupar"];
$proyectado=$_POST["proyectado"];
$saldo_cero=$_POST["saldo_cero"];
$nombre=$_POST["nombre"];
$fechaini=$_POST["fechaini"];
$fechafin=$_POST["fechafin"];
$concepto_pago=$_POST["concepto_pago"];
$cod_contexto=$_POST["contexto"];
$canal_venta=$_POST["canal_venta"];
$otra_moneda=$_POST["otra_moneda"];
$usuario=$_POST["usuario"];

//$cod_cxp=$_GET["cod_cxp"];
$empresa=$_GET["empresa"];
$otra_moneda_det=$_GET["otra_moneda_det"];
$fechainidet=$_GET["fechainidet"];
$fechafindet=$_GET["fechafindet"];
$nombredet=$_GET["nombredet"];
$totaldet=$_GET["totaldet"];
$concepto_pago_det=$_GET["concepto_pago_det"];
$cod_contexto_det=$_GET["contexto_det"];
$proyectado_det=$_GET["proyectado_det"];
$total_periodo=$_GET["total_periodo"];
$usuario_det=$_GET["usuario_det"];
//$n_decimales = 6;

//verificar el tipo de usuario 3 es normal (no muestra CxP)
$resultuser = mysqli_query($link, "select pkyUser as cod_user, codType as cod_tipo 
from accUser
where fldLogin = '$usuario' and
sysEnabled = 1 and sysAuthorized = 1;");
		
while ($row = mysqli_fetch_array($resultuser)) {
$cod_usuario = $row['cod_user'];
$cod_tipo_usuario = $row['cod_tipo'];
}
mysqli_free_result($resultuser);

if($cod_tipo_usuario == 3) { 
	$valor_ver = ' a.sysVisible <> 1 and ';
	$valor_ver2 = ' c.sysVisible <> 1 and ';
} else {
	$valor_ver = ' ';
	$valor_ver2 = ' ';
}

//verificar el tipo de usuario 3 es normal (no muestra CxP) para el detalle
$resultuser = mysqli_query($link, "select pkyUser as cod_user, codType as cod_tipo 
from accUser
where fldLogin = '$usuario_det' and
sysEnabled = 1 and sysAuthorized = 1;");
		
while ($row = mysqli_fetch_array($resultuser)) {
$cod_usuario_det = $row['cod_user'];
$cod_tipo_usuario_det = $row['cod_tipo'];
}
mysqli_free_result($resultuser);

if($cod_tipo_usuario_det == 3) { 
	$valor_ver_det = ' a.sysVisible <> 1 and ';
	$valor_ver2_det = ' g.sysVisible <> 1 and ';
} else {
	$valor_ver_det = ' ';
	$valor_ver2_det = ' ';
}

?>
<body>
<?php

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

if($agrupar == 0) { 
	$nom_agrupar = 'Empresa / Empleado';
} else {
	$nom_agrupar = 'Concepto';
}

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 pagar 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_pago == 0) { // if concepto pago
	$nom_concepto_pago = 'Todos';
	$valor_concepto = ' ';
	$valor_concepto2 = ' ';
} else {
	$resultcon = mysqli_query($link, "select fldName as nombre
from payAccountsPayableConcept
where
pkyAccountsPayableConcept = '$concepto_pago';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_pago = $row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto = ' a.codConcept = '. $concepto_pago .' and ';
	$valor_concepto2 = ' c.codConcept = '. $concepto_pago .' and ';
}//fin if concepto de pago

if($proyectado == 0) { // if proyectado 0
	$nom_proyectado = 'Todos';
	$valor_proyectado = ' ';
	$valor_proyectado2 = ' ';
}//fin if proyectado 0

if($proyectado == 1) { // if proyectado 1
	$nom_proyectado = 'Proyectados';
	$valor_proyectado = ' a.codProductionProjection is not NULL and ';
	$valor_proyectado2 = ' c.codProductionProjection is not NULL and ';
}//fin if proyectado 1

if($proyectado == 2) { // if proyectado 2
	$nom_proyectado = 'No Proyectados';
	$valor_proyectado = ' a.codProductionProjection is NULL and ';
	$valor_proyectado2 = ' c.codProductionProjection is not NULL and ';
}//fin if proyectado 2


//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, originalmente se tenía comentado, porque en la parte inferior en los querys en lugar de $ultimo_tc as tc se tenia a.codExchangeRate 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;");
$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;

//contexto
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_proveedor = 'Empresas';
	$valor_proveedor = ' ';
	$valor_proveedor2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultprov = 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($resultprov)) {
			$nom_proveedor = $row['codigo'].' - '.$row['empresa'];
		}
		mysqli_free_result($resultprov);
	$valor_proveedor = ' a.codSupplier = '. $nombreemp .' and ';
	$valor_proveedor2 = ' c.codSupplier = '. $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
	
	//CxP empresas
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d 
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");

	//suma Pagos empresas
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos,
 otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
 otra.cod_moneda_cxp as cod_moneda_cxp, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d 
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_canal_venta1 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d 
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_canal_venta1 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");		

$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 cxp
	$matriz_salini [$i][4] = 0; //suma pagos
	$matriz_salini [$i][5] = 0; //saldo inicial
	$matriz_salini [$i][6] = 0; //suma cxp periodo
	$matriz_salini [$i][7] = 0; //suma pagos periodo
	$matriz_salini [$i][8] = 0; //saldo periodo
	$matriz_salini [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

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

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

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

//inicio calculo registros

	//CxP empresas
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d 
where
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d 
where
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");
	
	//suma Pagos empresas
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos,
 otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
 otra.cod_moneda_cxp as cod_moneda_cxp, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d 
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
$valor_proveedor2 
$valor_concepto2 
$valor_canal_venta1 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d 
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
$valor_proveedor2 
$valor_concepto2 
$valor_canal_venta1 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");	

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

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

$i = 1;
while($i <= $fin) {
	$reg_cxp = $matriz_salini [$i][6];
	$reg_pagos = $matriz_salini [$i][7];
	$matriz_salini [$i][8] = $reg_cxp - $reg_pagos;
	$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 pagar 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_proveedor; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_pago; ?></TD>
        <TD width="25%"><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><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>Mostrar: </b><?php echo $nom_proyectado; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        <TD><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        <TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<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; ?>" 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>

</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>CxP Sal. Ini.</b></TD>
    <TD align="center"><b>Pag. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxP Periodo</b></TD>
    <TD align="center"><b>Pagos 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_cxp = 0;
  $suma_total_pagos = 0;
  $suma_total_ini = 0;
  $suma_total_cxp_per = 0;
  $suma_total_pagos_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));// CxP saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][4],$n_decimales));// pagos 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 CxP periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][7],$n_decimales));// suma pagos 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_pago_det=$concepto_pago&total_periodo=$total_periodo&proyectado_det=$proyectado&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini [$j][9],$n_decimales));//total
	   
	$suma_total_cxp = $suma_total_cxp + $matriz_salini [$j][3];
    $suma_total_gastos = $suma_total_gastos + $matriz_salini [$j][4];
	$suma_total_ini = $suma_total_ini + $matriz_salini [$j][5];
	
    $suma_total_cxp_per = $suma_total_cxp_per + $matriz_salini [$j][6];
    $suma_total_pagos_per = $suma_total_pagos_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_cxp,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos,$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_cxp_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos_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_proveedor = 'Empleados';
	$valor_proveedor = ' ';
	$valor_proveedor2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultprov = 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($resultprov)) {
			$nom_proveedor = $row['codigo'].' - '.$row['empleado'];
		}
		mysqli_free_result($resultprov);
	$valor_proveedor = ' a.codEmployee = '. $nombreemp .' and ';
	$valor_proveedor2 = ' 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
from agnPerson
where
sysEnabled = 1 and sysAuthorized = 1
order by empleado;");
	
	//inicio calculo saldo inicial
	//CxP empleados
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");
	
	//suma Pagos empleados
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos, 
otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
otra.cod_moneda_cxp as cod_moneda_cxp,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");	
	
	$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 cxp
	$matriz_salini2 [$i][4] = 0; //suma pagos
	$matriz_salini2 [$i][5] = 0; //saldo inicial
	$matriz_salini2 [$i][6] = 0; //suma cxp periodo
	$matriz_salini2 [$i][7] = 0; //suma pagos periodo
	$matriz_salini2 [$i][8] = 0; //saldo periodo
	$matriz_salini2 [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

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

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

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

//inicio calculo registros
	
	//CxP empleados
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");
	
	//suma Pagos empleados
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos, 
otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
otra.cod_moneda_cxp as cod_moneda_cxp,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");	

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

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

$i = 1;
while($i <= $fin) {
	$reg_cxp = $matriz_salini2 [$i][6];
	$reg_pagos = $matriz_salini2 [$i][7];
	$matriz_salini2 [$i][8] = $reg_cxp - $reg_pagos;
	$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 pagar 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_proveedor; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_pago; ?></TD>
        <TD width="25%"><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Mostrar: </b><?php echo $nom_proyectado; ?></TD>
        <TD><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        <TD colspan="2"><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<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; ?>" 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>

</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>CxP Sal. Ini.</b></TD>
    <TD align="center"><b>Pag. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxP Periodo</b></TD>
    <TD align="center"><b>Pagos 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_cxp2 = 0;
  $suma_total_pagos2 = 0;
  $suma_total_ini2 = 0;
  $suma_total_cxp_per2 = 0;
  $suma_total_pagos_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]);//empleado
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][3],$n_decimales));//CxP saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][4],$n_decimales));// pagos 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 CxP periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][7],$n_decimales));// suma pagos 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_pago_det=$concepto_pago&total_periodo=$total_periodo&proyectado_det=$proyectado&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini2 [$j][9],$n_decimales));//total
	   
	$suma_total_cxp2 = $suma_total_cxp2 + $matriz_salini2 [$j][3];
    $suma_total_pagos2 = $suma_total_pagos2 + $matriz_salini2 [$j][4];
	$suma_total_ini2 = $suma_total_ini2 + $matriz_salini2 [$j][5];
	
    $suma_total_cxp_per2 = $suma_total_cxp_per2 + $matriz_salini2 [$j][6];
    $suma_total_pagos_per2 = $suma_total_pagos_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_cxp2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos2,$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_cxp_per2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos_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
	
	//echo 'hola';
	$nom_orden = 'Nombre';
	$nom_proveedor = 'Todos';
	$valor_proveedor = ' ';
	$valor_proveedor2 = ' ';
	
		//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
	
	//CxP empresas
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d 
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");

	//suma Pagos empresas
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos,
 otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
 otra.cod_moneda_cxp as cod_moneda_cxp, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
$valor_proveedor2 
$valor_concepto2 
$valor_canal_venta1 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
$valor_proveedor2 
$valor_concepto2 
$valor_canal_venta1 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");		

$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 cxp
	$matriz_salini [$i][4] = 0; //suma pagos
	$matriz_salini [$i][5] = 0; //saldo inicial
	$matriz_salini [$i][6] = 0; //suma cxp periodo
	$matriz_salini [$i][7] = 0; //suma pagos periodo
	$matriz_salini [$i][8] = 0; //saldo periodo
	$matriz_salini [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

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

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

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

//inicio calculo registros

	//CxP empresas
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, r.fldRate as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, t.cod_moneda as cod_moneda,
t.tc as tc, t.otra_moneda as otra_moneda, 1 as tasa
from
(select a.codSupplier as cod_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a, agnCompany d
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and
$valor_proveedor 
$valor_concepto 
$valor_canal_venta1 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codSupplier = d.pkyCompany and 
a.codSupplier is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");
	
	//suma Pagos empresas
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos,
 otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
 otra.cod_moneda_cxp as cod_moneda_cxp, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
$valor_proveedor2 
$valor_concepto2 
$valor_canal_venta1 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codClient as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c, agnCompany d
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
$valor_proveedor2 
$valor_concepto2 
$valor_canal_venta1 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codClient = d.pkyCompany and 
a.codClient is not null and 
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");	

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

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

$i = 1;
while($i <= $fin) {
	$reg_cxp = $matriz_salini [$i][6];
	$reg_pagos = $matriz_salini [$i][7];
	$matriz_salini [$i][8] = $reg_cxp - $reg_pagos;
	$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 pagar 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_proveedor; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_pago; ?></TD>
        <TD width="25%"><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><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>Mostrar: </b><?php echo $nom_proyectado; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        <TD><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        <TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<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; ?>" 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>

</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>CxP Sal. Ini.</b></TD>
    <TD align="center"><b>Pag. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxP Periodo</b></TD>
    <TD align="center"><b>Pagos 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_cxp = 0;
  $suma_total_pagos = 0;
  $suma_total_ini = 0;
  $suma_total_cxp_per = 0;
  $suma_total_pagos_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));//CxP saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][4],$n_decimales));// pagos 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 CxP periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][7],$n_decimales));// suma pagos 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_pago_det=$concepto_pago&total_periodo=$total_periodo&proyectado_det=$proyectado&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini [$j][9],$n_decimales));//total
	   
	$suma_total_cxp = $suma_total_cxp + $matriz_salini [$j][3];
    $suma_total_pagos = $suma_total_pagos + $matriz_salini [$j][4];
	$suma_total_ini = $suma_total_ini + $matriz_salini [$j][5];
	
    $suma_total_cxp_per = $suma_total_cxp_per + $matriz_salini [$j][6];
    $suma_total_pagos_per = $suma_total_pagos_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_cxp,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos,$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_cxp_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos_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
	//CxP empleados
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate < '$fechaini' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");
	
	//suma Pagos empleados
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos, 
otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
otra.cod_moneda_cxp as cod_moneda_cxp,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");	
	
	$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 cxp
	$matriz_salini2 [$i][4] = 0; //suma pagos
	$matriz_salini2 [$i][5] = 0; //saldo inicial
	$matriz_salini2 [$i][6] = 0; //suma cxp periodo
	$matriz_salini2 [$i][7] = 0; //suma pagos periodo
	$matriz_salini2 [$i][8] = 0; //saldo periodo
	$matriz_salini2 [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

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

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

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

//inicio calculo registros
	
	//CxP empleados
	$result3 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as cxp
from(
select otra.cod_prov as cod_prov, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, 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_prov as cod_prov, t.cxp as cxp, 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_prov, sum(a.fldTotal) as cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
$valor_proveedor 
$valor_concepto 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.codEmployee is not NULL 
group by cod_prov, cod_moneda, tc) t
where
t.cod_moneda = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");
	
	//suma Pagos empleados
	$result5 = mysqli_query($link, "select final.cod_prov as cod_prov, sum(final.total) as suma_pagos
from(
select otra.cod_prov as cod_prov, otra.suma_pagos as suma_pagos, 
otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
otra.cod_moneda_cxp as cod_moneda_cxp,
otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
otra.suma_pagos * otra.tasa as total
from
(select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_prov as cod_prov, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select a.codEmployee as cod_prov, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
$valor_proveedor2 
$valor_concepto2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.codEmployee is not null and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_prov, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_prov
order by final.cod_prov;");	

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

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

$i = 1;
while($i <= $fin) {
	$reg_cxp = $matriz_salini2 [$i][6];
	$reg_pagos = $matriz_salini2 [$i][7];
	$matriz_salini2 [$i][8] = $reg_cxp - $reg_pagos;
	$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_cxp2 = 0;
  $suma_total_pagos2 = 0;
  $suma_total_ini2 = 0;
  $suma_total_cxp_per2 = 0;
  $suma_total_pagos_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));//CxP saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][4],$n_decimales));// pagos 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 CxP periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini2 [$j][7],$n_decimales));// suma pagos 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_pago_det=$concepto_pago&total_periodo=$total_periodo&proyectado_det=$proyectado&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini2 [$j][9],$n_decimales));//total
	   
	$suma_total_cxp2 = $suma_total_cxp2 + $matriz_salini2 [$j][3];
    $suma_total_pagos2 = $suma_total_pagos2 + $matriz_salini2 [$j][4];
	$suma_total_ini2 = $suma_total_ini2 + $matriz_salini2 [$j][5];
	
    $suma_total_cxp_per2 = $suma_total_cxp_per2 + $matriz_salini2 [$j][6];
    $suma_total_pagos_per2 = $suma_total_pagos_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_cxp3 = $suma_total_cxp + $suma_total_cxp2;
$suma_total_pagos3 = $suma_total_pagos + $suma_total_pagos2;
$suma_total_ini3 = $suma_total_ini + $suma_total_ini2;
$suma_total_cxp_per3 = $suma_total_cxp_per + $suma_total_cxp_per2;
$suma_total_pagos_per3 = $suma_total_pagos_per + $suma_total_pagos_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_cxp2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos2,$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_cxp_per2,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos_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_cxp3,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos3,$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_cxp_per3,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos_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, originalmente se tenía comentado, porque en la parte inferior en los querys en lugar de $ultimo_tc as tc se tenia a.codExchangeRate as tc
$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;");
$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;
/*
//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;
*/

if($concepto_pago_det == 0) { // if concepto pago
	$nom_concepto_pago_det = 'Todos';
	$valor_concepto_det = ' ';
	$valor_concepto2_det = ' ';
} else {
	$resultcon = mysqli_query($link, "select fldName as nombre
from payAccountsPayableConcept
where
pkyAccountsPayableConcept = '$concepto_pago_det';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_pago_det = $row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto_det = ' a.codConcept = '. $concepto_pago_det .' and ';
	$valor_concepto2_det = ' g.codConcept = '. $concepto_pago_det .' and ';
}//fin if concepto de pago


if($proyectado_det == 0) { // if proyectado 0
	$nom_proyectado_det = 'Todos';
	$valor_proyectado_det = ' ';
	$valor_proyectado2_det = ' ';
}//fin if proyectado 0

if($proyectado_det == 1) { // if proyectado 1
	$nom_proyectado_det = 'Proyectados';
	$valor_proyectado_det = ' a.codProductionProjection is not NULL and ';
	$valor_proyectado2_det = ' g.codProductionProjection is not NULL and ';
}//fin if proyectado 1

if($proyectado_det == 2) { // if proyectado 2
	$nom_proyectado_det = 'No Proyectados';
	$valor_proyectado_det = ' a.codProductionProjection is NULL and ';
	$valor_proyectado2_det = ' g.codProductionProjection is not NULL and ';
}//fin if proyectado 2

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_pago as fecha_pago, final.concepto as concepto, final.via as via_pago, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cxp as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_proy as cod_proy, 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_pago as fecha_pago, otro.concepto as concepto, otro.via as via, otro.empresa as empresa, otro.moneda as moneda, otro.glosa as glosa, otro.cxp as cxp,
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.cxp as total, otro.cod_proy as cod_proy, 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_pago as fecha_pago, t.concepto as concepto, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, 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.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b, agnCompany d, actCurrency f
where 
$valor_concepto_det 
$valor_ver_det 
$valor_proyectado_det 
$valor_contexto_det 
a.codSupplier = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept and
a.codSupplier = 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_pago as fecha_pago, t.concepto as concepto, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b, agnCompany d, actCurrency f
where 
$valor_concepto_det 
$valor_ver_det 
$valor_proyectado_det 
$valor_contexto_det 
a.codSupplier = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept and
a.codSupplier = 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 Pagar 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="33%"><b>Empresa: </b><?php echo $nomempdet; ?></TD>
        <TD width="33%"><b>Concepto: </b><?php echo $nom_concepto_pago_det; ?></TD>
        <TD width="33%"><b>Mostrar: </b><?php echo $nom_proyectado_det; ?></TD>
        </TR>
        <TR>
        <TD><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></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>

<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; ?>" 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>

</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"><b>Proyecci&oacute;n</b></TD>
	<TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center" width="65"><b>Fecha Pago</b></TD>
    <TD align="center"><b>Concepto</b></TD>
    <TD align="center"><b>Via Pago</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>Debito 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 cxp para mostrar los pagos que se hicieron en el periodo y no tienen cxp 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'];	
	$cod_proy = $row['cod_proy'];
	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='../../ModulePayments/VoucherAccountsPayable/index.php?pkyAccountsPayable=$codigo_det&user=$usuario_det' title='Nota de Cuenta por Pagar'>%s</a></td>", $row['codigo']);//cod
	printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionProjection/index.php?pkyProductionProjection=$cod_proy&user=$usuario_det' title='Proyecci&oacute;n de Producci&oacute;n'>%s</a></td>", $row['cod_proy']);//cod proyeccion
	printf("<td align='right'>%s</td>", $row['fecha']);//fecha
	printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
	printf("<td>%s</td>", $row['concepto']);//concepto viene de los parametros
	printf("<td>%s</td>", $row['via_pago']);//via pago
	//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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
	} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
	}
	
	//$suma_periodo = $suma_periodo + $row['total_om'];
	$total_cxp = $row['total_om'];
	$suma_saldo = $total_cxp;
	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 codigo as codigo, nrodoc as nrodoc, fecha as fecha, fecha_pago as fecha_pago, concepto as concepto, via_pago as via_pago, via_pago as via_pago, empresa as empresa, moneda as moneda, glosa as glosa, pago as total, tipo as tipo, tasa as tasa, 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_pago, otro.concepto as concepto, otro.via_pago as via_pago, otro.empresa as empresa, otro.moneda_cxp as moneda, otro.glosa as glosa, otro.pago as pago, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, otro.tasa * otro.pago 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_ver2_det 
$valor_proyectado2_det
$valor_contexto_det 
a.codClient = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago,  a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_ver2_det 
$valor_proyectado2_det
$valor_contexto_det 
a.codClient = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = 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";
	
		$codigo_detp = $row['codigo'];
		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
		}
		
		printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$codigo_detp&user=$usuario_det' title='Nota de Pago'>%s</a></td>", $row['codigo']);//cod
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>&nbsp;</td>");//cod_proy
		printf("<td align='right'>%s</td>", $row['fecha']);//fecha
		printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
		printf("<td>%s</td>", $row['concepto']);//concepto viene con NULL
		printf("<td>%s</td>", $row['via_pago']);//via pago
		//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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $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_cxp + $suma_det) > 0) {
	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_cxp + $suma_det,$n_decimales));//total cuenta
	} else {
	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_cxp + $suma_det)*-1,$n_decimales));//total cuenta
	printf("<td>&nbsp;</td>");//espacio al final
	}
		
	printf("<td>&nbsp;</td></tr>");//espacio al final
	
	$suma_periodo = $suma_periodo + $total_cxp + $suma_det;
}//fin while
mysqli_free_result($result2);
$suma_total = $suma_periodo + $totaldet; 

//verificacion si existe un pago que no tenga cxp 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_cxp 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_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.pago as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxp as cod_cxp, 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_pago, otro.concepto as concepto, otro.via_pago as via_pago, otro.empresa as empresa, otro.moneda_cxp as moneda, otro.glosa as glosa, otro.pago as pago, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, otro.tasa * otro.pago as total, otro.cod_cxp as cod_cxp, 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, r.fldRate as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_concepto2_det 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
a.codClient = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 1 as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_concepto2_det 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
a.codClient = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = t.otra_moneda) otro) final
$cadena_no
order by final.fecha, final.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";
		
		$codigo_detp = $row['codigo'];
		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
		}
		printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$codigo_detp&user=$usuario_det' title='Nota de Pago'>%s</a></td>", $row['codigo']);//cod
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>&nbsp;</td>");//cod_proy
		printf("<td align='right'>%s</td>", $row['fecha']);//fecha
		printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
		printf("<td>%s</td>", $row['concepto']);//concepto viene con NULL
		printf("<td>%s</td>", $row['via_pago']);//via pago
		//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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
		}
		$suma_det_solo = $suma_det_solo + $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*-1,$n_decimales); ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_cred,$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.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;");
 
while ($row = mysqli_fetch_array($result)) {
	$nomempdet = $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_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago, final.empleado as empleado,  final.moneda as moneda, final.glosa as glosa, final.cxp as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_proy as cod_proy, 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_pago as fecha_pago, otro.concepto as concepto, otro.via as via_pago, otro.empleado as empleado, otro.moneda as moneda, otro.glosa as glosa, otro.cxp as cxp, 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.cxp as total, otro.cod_proy as cod_proy, 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_pago as fecha_pago, t.concepto as concepto,  t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, 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.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, 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 cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b,  agnPerson e, actCurrency f
where 
$valor_concepto_det 
$valor_ver_det 
$valor_proyectado_det 
$valor_contexto_det 
a.codEmployee = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept 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_pago as fecha_pago, t.concepto as concepto, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, 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 cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b, 
agnPerson e, actCurrency f
where 
$valor_concepto_det 
$valor_ver_det 
$valor_proyectado_det 
$valor_contexto_det 
a.codEmployee = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept 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 Pagar 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="33%"><b>Empleado: </b><?php echo $nomempdet; ?></TD>
        <TD width="33%"><b>Concepto: </b><?php echo $nom_concepto_pago_det; ?></TD>
        <TD width="33%"><b>Mostrar: </b><?php echo $nom_proyectado_det; ?></TD>
        </TR>
        <TR>
        <TD><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></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>

<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; ?>" 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>

</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"><b>Proyecci&oacute;n</b></TD>
	<TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center" width="65"><b>Fecha Pago</b></TD>
    <TD align="center"><b>Concepto</b></TD>
    <TD align="center"><b>Via Pago</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>Debito 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 cxp para mostrar los pagos que se hicieron en el periodo y no tienen cxp 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'];
	$cod_proy = $row['cod_proy'];	
	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='../../ModulePayments/VoucherAccountsPayable/index.php?pkyAccountsPayable=$codigo_det&user=$usuario_det' title='Nota de Cuenta por Pagar'>%s</a></td>", $row['codigo']);//cod
	printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionProjection/index.php?pkyProductionProjection=$cod_proy&user=$usuario_det' title='Proyecci&oacute;n de Producci&oacute;n'>%s</a></td>", $row['cod_proy']);//cod proyeccion
	printf("<td align='right'>%s</td>", $row['fecha']);//fecha
	printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
	printf("<td>%s</td>", $row['concepto']);//concepto viene de parametros
	printf("<td>%s</td>", $row['via_pago']);//via pago
	//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>&nbsp;</td>");//total otra moneda debito
	printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
	$suma_cred = $suma_cred + $row['total_om'];
	} else {
	printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
	printf("<td>&nbsp;</td>");//total otra moneda credito
	$suma_deb = $suma_deb + $row['total_om'];
	}
		
	//$suma_periodo = $suma_periodo + $row['total_om'];
	$total_cxp = $row['total_om'];
	$suma_saldo = $total_cxp;
	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 codigo as codigo, nrodoc as nrodoc, fecha as fecha, fecha_pago as fecha_pago, concepto as concepto, via_pago as via_pago, empleado as empleado,  moneda as moneda, glosa as glosa, pago as total, tipo as tipo, tasa as tasa, 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_pago, 
otro.concepto as concepto,  
otro.via_pago as via_pago, otro.empleado as empleado, 
otro.moneda_cxp as moneda, otro.glosa as glosa, 
otro.pago as pago, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.pago 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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
a.codEmployee = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
a.codEmployee = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = 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";
		
		$codigo_detp = $row['codigo'];
		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
		}
		printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$codigo_detp&user=$usuario_det' title='Nota de Pago'>%s</a></td>", $row['codigo']);//cod
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>&nbsp;</td>");//cod_proy
		printf("<td align='right'>%s</td>", $row['fecha']);//fecha
		printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
		printf("<td>%s</td>", $row['concepto']);//concepto viene con NULL
		printf("<td>%s</td>", $row['via_pago']);//via pago
		//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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $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_cxp + $suma_det) > 0) {
	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_cxp + $suma_det,$n_decimales));//total cuenta
	} else {
	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_cxp + $suma_det)*-1,$n_decimales));//total cuenta
	printf("<td>&nbsp;</td>");//espacio al final
	}
		
	printf("<td>&nbsp;</td></tr>");//espacio al final
	
	$suma_periodo = $suma_periodo + $total_cxp + $suma_det;
	
}//fin while
mysqli_free_result($result2);
$suma_total = $suma_periodo + $totaldet;  

//verificacion si existe un pago que no tenga cxp 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_cxp 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_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago, final.empleado as empleado, final.moneda as moneda, final.glosa as glosa, final.pago as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxp as cod_cxp, 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_pago, 
otro.concepto as concepto,  
otro.via_pago as via_pago, otro.empleado as empleado, 
otro.moneda_cxp as moneda, otro.glosa as glosa, 
otro.pago as pago, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.pago as total, otro.cod_cxp as cod_cxp,
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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
r.fldRate as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, 
g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_concepto2_det 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
a.codEmployee = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
1 as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, 
a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i 
where 
$valor_concepto2_det 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
a.codEmployee = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = t.otra_moneda) otro) final 
$cadena_no 
order by final.fecha, final.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";
		
		$codigo_detp = $row['codigo'];
		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
		}
		printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$codigo_detp&user=$usuario_det' title='Nota de Pago'>%s</a></td>", $row['codigo']);//cod
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>&nbsp;</td>");//cod_proy
		printf("<td align='right'>%s</td>", $row['fecha']);//fecha
		printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
		printf("<td>%s</td>", $row['concepto']);//concepto 
		printf("<td>%s</td>", $row['via_pago']);//via pago
		//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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $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*-1,$n_decimales); ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_cred,$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.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 pagar 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_pago == 0) { // if concepto pago
	$nom_concepto_pago = 'Todos';
	$valor_concepto = ' ';
	$valor_concepto2 = ' ';
} else {
	$resultcon = mysqli_query($link, "select fldName as nombre
from payAccountsPayableConcept
where
pkyAccountsPayableConcept = '$concepto_pago';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_pago = $row['nombre'];
	}
	mysqli_free_result($resultcon);
	$valor_concepto = ' a.codConcept = '. $concepto_pago .' and ';
	$valor_concepto2 = ' c.codConcept = '. $concepto_pago .' and ';
}//fin if concepto de pago

if($proyectado == 0) { // if proyectado 0
	$nom_proyectado = 'Todos';
	$valor_proyectado = ' ';
	$valor_proyectado2 = ' ';
}//fin if proyectado 0

if($proyectado == 1) { // if proyectado 1
	$nom_proyectado = 'Proyectados';
	$valor_proyectado = ' a.codProductionProjection is not NULL and ';
	$valor_proyectado2 = ' c.codProductionProjection is not NULL and ';
}//fin if proyectado 1

if($proyectado == 2) { // if proyectado 2
	$nom_proyectado = 'No Proyectados';
	$valor_proyectado = ' a.codProductionProjection is NULL and ';
	$valor_proyectado2 = ' c.codProductionProjection is not NULL and ';
}//fin if proyectado 2


//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, originalmente se tenía comentado, porque en la parte inferior en los querys en lugar de $ultimo_tc as tc se tenia a.codExchangeRate 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;");
$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;

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_proveedor = 'Empresas';
	$valor_proveedor = ' ';
	$valor_proveedor2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultprov = 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($resultprov)) {
			$nom_proveedor = $row['codigo'].' - '.$row['empresa'];
		}
		mysqli_free_result($resultprov);
	$valor_proveedor = ' a.codSupplier = '. $nombreemp .' and ';
	$valor_proveedor2 = ' c.codSupplier = '. $nombreemp .' and ';
	}
$valor_empo = ' a.codSupplier is not NULL and ';
$valor_empo2 = ' c.codSupplier is not NULL and ';
}//fin if 2.2
	
	
	if ($empresaoempleado == -2) { // if 2.3
	
	if($nombreemp == 0) {
	$nom_orden = 'Nombre';
	$nom_proveedor = 'Empleados';
	$valor_proveedor = ' ';
	$valor_proveedor2 = ' ';
	} else { 
	$nom_orden = 'Nombre';
		$resultprov = 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($resultprov)) {
			$nom_proveedor = $row['empleado'];
		}
		mysqli_free_result($resultprov);
	$valor_proveedor = ' a.codEmployee = '. $nombreemp .' and ';
	$valor_proveedor2 = ' c.codEmployee = '. $nombreemp .' and ';
	}
$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
	
	$nom_orden = 'Nombre';
	$nom_proveedor = 'Todos';
	$valor_proveedor = ' ';
	$valor_proveedor2 = ' ';
$valor_empo = ' ';
$valor_empo2 = ' ';
}// fin if 2.4

	//listado de conceptos
	$result = mysqli_query($link, "select pkyAccountsPayableConcept as codigo, fldName as concepto
from payAccountsPayableConcept
where
sysEnabled = 1 and sysAuthorized = 1
order by concepto;");
		
	//inicio calculo saldo inicial
	
	//CxP empresas o empleados
	$result3 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as cxp
from(
select otra.cod_con as cod_con, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_con as cod_con, t.cxp as cxp, 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 cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where
$valor_proveedor 
$valor_concepto 
$valor_empo 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.fldDate < '$fechaini' 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.cxp as cxp, 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 cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where 
$valor_proveedor 
$valor_concepto 
$valor_empo 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.fldDate < '$fechaini' 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 Pagos empresas o empleados
	$result5 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as suma_pagos
from(
select otra.cod_con as cod_con, otra.suma_pagos as suma_pagos,
 otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
 otra.cod_moneda_cxp as cod_moneda_cxp, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_pagos * otra.tasa as total
from
(select t.cod_con as cod_con, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where
$valor_proveedor2 
$valor_concepto2 
$valor_empo2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_con as cod_con, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where 
$valor_proveedor2 
$valor_concepto2 
$valor_empo2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.pkyPayment = b.codPayment and
a.fldDate < '$fechaini' and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = 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 empresa
	$matriz_salini [$i][2] = $row['concepto'];//nombre empresa
	$matriz_salini [$i][3] = 0; //suma cxp
	$matriz_salini [$i][4] = 0; //suma pagos
	$matriz_salini [$i][5] = 0; //saldo inicial
	$matriz_salini [$i][6] = 0; //suma cxp periodo
	$matriz_salini [$i][7] = 0; //suma pagos periodo
	$matriz_salini [$i][8] = 0; //saldo periodo
	$matriz_salini [$i][9] = 0; //total
	$i++;
}
$fin = $i - 1;
mysqli_free_result($result);

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

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

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

//inicio calculo registros

	//CxP empresas o empleados
	$result3 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as cxp
from(
select otra.cod_con as cod_con, otra.cxp as cxp, otra.cod_moneda as cod_moneda,
otra.tc as tc, otra.otra_moneda as otra_moneda, otra.tasa as tasa, otra.cxp * otra.tasa as total
from
(select t.cod_con as cod_con, t.cxp as cxp, 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 cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where 
$valor_proveedor 
$valor_concepto 
$valor_empo 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' 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.cxp as cxp, 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 cxp, 
a.codCurrency as cod_moneda, '$ultimo_tc' as tc, '$otra_moneda' as otra_moneda
from payAccountsPayable a
where 
$valor_proveedor 
$valor_concepto 
$valor_empo 
$valor_ver 
$valor_proyectado 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' 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 Pagos empresas
	$result5 = mysqli_query($link, "select final.cod_con as cod_con, sum(final.total) as suma_pagos
from(
select otra.cod_con as cod_con, otra.suma_pagos as suma_pagos,
 otra.cod_moneda_pago as cod_moneda_pago, otra.tc as tc, 
 otra.cod_moneda_cxp as cod_moneda_cxp, 
 otra.otra_moneda as otra_moneda, otra.tasa as tasa, 
 otra.suma_pagos * otra.tasa as total
from
(select t.cod_con as cod_con, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
r.fldRate as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where 
$valor_proveedor2 
$valor_concepto2 
$valor_empo2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_pago, cod_moneda_cxp, tc) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = r.codTargetCurrency and
t.otra_moneda = r.codBaseCurrency
union all
select t.cod_con as cod_con, t.suma_pagos as suma_pagos, 
t.cod_moneda_pago as cod_moneda_pago, t.tc as tc, 
t.cod_moneda_cxp as cod_moneda_cxp, t.otra_moneda as otra_moneda, 
1 as tasa
from
(select c.codConcept as cod_con, sum(b.fldTotal) as suma_pagos,
a.codCurrency as cod_moneda_pago, '$ultimo_tc' as tc, 
c.codCurrency as cod_moneda_cxp, '$otra_moneda' as otra_moneda
from payPayment a, payPaymentDetail b, payAccountsPayable c
where 
$valor_proveedor2 
$valor_concepto2 
$valor_empo2 
$valor_ver2 
$valor_proyectado2 
$valor_contexto 
a.pkyPayment = b.codPayment and
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and
b.codAccountsPayable is not null and
b.codAccountsPayable = c.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1
group by cod_con, cod_moneda_pago, cod_moneda_cxp, tc) t
where
t.cod_moneda_cxp = t.otra_moneda) otra) final
group by final.cod_con
order by final.cod_con;");	

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

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

$i = 1;
while($i <= $fin) {
	$reg_cxp = $matriz_salini [$i][6];
	$reg_pagos = $matriz_salini [$i][7];
	$matriz_salini [$i][8] = $reg_cxp - $reg_pagos;
	$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 pagar 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_proveedor; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Concepto: </b><?php echo $nom_concepto_pago; ?></TD>
        <TD width="25%"><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        </TR>
        <TR>
        
        </TR>
        <TR>
        <TD colspan="2"><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Mostrar: </b><?php echo $nom_proyectado; ?></TD>
        <TD><b>Agrupado por: </b><?php echo $nom_agrupar; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Saldos en cero: </b><?php echo $nom_saldo_cero; ?></TD>
        <TD colspan="2"><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

</td>

<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; ?>" 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>

</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>CxP Sal. Ini.</b></TD>
    <TD align="center"><b>Pag. Sal. Ini.</b></TD>
    <TD align="center"><b>Total Sal. Ini.</b></TD>
    <TD align="center"><b>CxP Periodo</b></TD>
    <TD align="center"><b>Pagos 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_cxp = 0;
  $suma_total_pagos = 0;
  $suma_total_ini = 0;
  $suma_total_cxp_per = 0;
  $suma_total_pagos_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));// CxP saldo inicial
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][4],$n_decimales));// pagos 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 CxP periodo
	printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][7],$n_decimales));// suma pagos 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&empresa=1&fechainidet=$fechaini&fechafindet=$fechafin&totaldet=$totaldet&otra_moneda_det=$otra_moneda&concepto_pago_det=$concepto_pago&total_periodo=$total_periodo&proyectado_det=$proyectado&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Cuenta del Periodo'>%s</a></td></tr>", number_format($matriz_salini [$j][9],$n_decimales));//total
	   
	$suma_total_cxp = $suma_total_cxp + $matriz_salini [$j][3];
    $suma_total_gastos = $suma_total_gastos + $matriz_salini [$j][4];
	$suma_total_ini = $suma_total_ini + $matriz_salini [$j][5];
	
    $suma_total_cxp_per = $suma_total_cxp_per + $matriz_salini [$j][6];
    $suma_total_pagos_per = $suma_total_pagos_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 por Concepto</b>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cxp,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_gastos,$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_cxp_per,$n_decimales)); ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_pagos_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);

if($proyectado_det == 0) { // if proyectado 0
	$nom_proyectado_det = 'Todos';
	$valor_proyectado_det = ' ';
	$valor_proyectado2_det = ' ';
}//fin if proyectado 0

if($proyectado_det == 1) { // if proyectado 1
	$nom_proyectado_det = 'Proyectados';
	$valor_proyectado_det = ' a.codProductionProjection is not NULL and ';
	$valor_proyectado2_det = ' g.codProductionProjection is not NULL and ';
}//fin if proyectado 1

if($proyectado_det == 2) { // if proyectado 2
	$nom_proyectado_det = 'No Proyectados';
	$valor_proyectado_det = ' a.codProductionProjection is NULL and ';
	$valor_proyectado2_det = ' g.codProductionProjection is not NULL and ';
}//fin if proyectado 2


//valor del codigo del ultimo tipo de cambio
//uso del codigo del tipo de cambio según la fecha final, originalmente se tenía comentado, porque en la parte inferior en los querys en lugar de $ultimo_tc as tc se tenia a.codExchangeRate as tc
$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;");
$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;
/*
//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 fldName as nombre
from payAccountsPayableConcept
where
pkyAccountsPayableConcept = '$nombredet';");
	while ($row = mysqli_fetch_array($resultcon)) {   
	$nom_concepto_pago_det = $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 ';	
}

 $result2 = mysqli_query($link, "select final2.codigo as codigo, final2.nrodoc as nrodoc, final2.fecha as fecha, final2.fecha_pago as fecha_pago, final2.concepto as concepto, final2.via_pago as via_pago, 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_proy as cod_proy, 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_pago as fecha_pago, final.concepto as concepto, final.via as via_pago, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.cxp as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_proy as cod_proy, 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_pago as fecha_pago, otro.concepto as concepto, otro.via as via, otro.empresa as empresa, otro.moneda as moneda, otro.glosa as glosa, otro.cxp as cxp,
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.cxp as total, otro.cod_proy as cod_proy, 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_pago as fecha_pago, t.concepto as concepto, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, 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.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b, agnCompany d, actCurrency f
where 
$valor_ver 
$valor_proyectado_det 
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept and
a.codSupplier = 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_pago as fecha_pago, t.concepto as concepto, t.via as via, t.empresa as empresa, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, null as via, d.fldName as empresa, f.fldName as moneda, a.txtDescription as glosa, a.fldTotal as cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b, agnCompany d, actCurrency f
where 
$valor_ver 
$valor_proyectado_det 
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept and
a.codSupplier = 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_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago, final.empleado as empresa,  final.moneda as moneda, final.glosa as glosa, final.cxp as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_proy as cod_proy, 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_pago as fecha_pago, otro.concepto as concepto, otro.via as via_pago, otro.empleado as empleado, otro.moneda as moneda, otro.glosa as glosa, otro.cxp as cxp, 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.cxp as total, otro.cod_proy as cod_proy, 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_pago as fecha_pago, t.concepto as concepto,  t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, 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.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, 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 cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b, agnPerson e, actCurrency f
where 
$valor_ver 
$valor_proyectado_det 
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept 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_pago as fecha_pago, t.concepto as concepto, t.via as via, t.empleado as empleado, t.moneda as moneda, t.glosa as glosa, t.cxp as cxp, t.tipo as tipo, t.tc as tc, t.otra_moneda as otra_moneda, t.cod_moneda as cod_moneda, 1 as tasa, t.cod_proy as cod_proy, t.papa as papa, t.cod_papa as cod_papa
from (
select a.pkyAccountsPayable as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, a.fldPaymentDate as fecha_pago, b.fldName as concepto, 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 cxp, 'CxP' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda, a.codProductionProjection as cod_proy, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from payAccountsPayable a, payAccountsPayableConcept b, agnPerson e, actCurrency f
where 
$valor_ver 
$valor_proyectado_det 
$valor_contexto_det 
a.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and
a.codConcept = b.pkyAccountsPayableConcept 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 Pagar 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_pago_det; ?></TD>
        <TD width="25%"><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></TD>
        <TD width="25%"><b>Mostrar: </b><?php echo $nom_proyectado_det; ?></TD>
        <TD width="25%"><b>Expresado en: </b><?php echo $nom_otra_moneda_det; ?></TD>
        </TR>
        <TR>
        <TD colspan="4"><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
        </TR>
    </table>

</td>

<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; ?>" 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>

</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"><b>Proyecci&oacute;n</b></TD>
	<TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center" width="65"><b>Fecha Pago</b></TD>
    <TD align="center"><b>Via Pago</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>Debito 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 cxp para mostrar los pagos que se hicieron en el periodo y no tienen cxp 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'];
	$cod_proy = $row['cod_proy'];	
	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='../../ModulePayments/VoucherAccountsPayable/index.php?pkyAccountsPayable=$codigo_det&user=$usuario_det' title='Nota de Cuenta por Pagar'>%s</a></td>", $row['codigo']);//cod
	printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionProjection/index.php?pkyProductionProjection=$cod_proy&user=$usuario_det' title='Proyecci&oacute;n de Producci&oacute;n'>%s</a></td>", $row['cod_proy']);//cod proyeccion
	printf("<td align='right'>%s</td>", $row['fecha']);//fecha
	printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
	//printf("<td>%s</td>", $row['concepto']);//concepto viene de los parametros
	printf("<td>%s</td>", $row['via_pago']);//via pago
	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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
	} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
	}
	
	//$suma_periodo = $suma_periodo + $row['total_om'];
	$total_cxp = $row['total_om'];
	$suma_saldo = $total_cxp;
	
	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_pago as fecha_pago, final2.concepto as concepto, final2.via_pago as via_pago, 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_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago, final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.pago 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_pago, otro.concepto as concepto, otro.via_pago as via_pago, otro.empresa as empresa, otro.moneda_cxp as moneda, otro.glosa as glosa, otro.pago as pago, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, otro.tasa * otro.pago 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = t.otra_moneda) otro) final

UNION ALL

select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago, final.empleado as empresa,  final.moneda as moneda, final.glosa as glosa, final.pago 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_pago, 
otro.concepto as concepto,  
otro.via_pago as via_pago, otro.empleado as empleado, 
otro.moneda_cxp as moneda, otro.glosa as glosa, 
otro.pago as pago, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.pago 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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
r.fldRate as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
1 as tasa, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
g.pkyAccountsPayable = '$codigo_det' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = 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";
		
		$codigo_detp = $row['codigo'];
		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
		}
		
		printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$codigo_detp&user=$usuario_det' title='Nota de Pago'>%s</a></td>", $row['codigo']);//cod
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>&nbsp;</td>");//cod_proy
		printf("<td align='right'>%s</td>", $row['fecha']);//fecha
		printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
		//printf("<td>%s</td>", $row['concepto']);//concepto viene con NULL
		printf("<td>%s</td>", $row['via_pago']);//via pago
		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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $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_cxp + $suma_det) > 0) {
	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_cxp + $suma_det,$n_decimales));//total cuenta
	} else {
	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_cxp + $suma_det)*-1,$n_decimales));//total cuenta
	printf("<td>&nbsp;</td>");//espacio al final
	}
		
	printf("<td>&nbsp;</td></tr>");//espacio al final
	
	$suma_periodo = $suma_periodo + $total_cxp + $suma_det;
}//fin while
mysqli_free_result($result2);
$suma_total = $suma_periodo + $totaldet; 

//verificacion si existe un pago que no tenga cxp 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_cxp 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_pago as fecha_pago, final2.concepto as concepto, final2.via_pago as via_pago, 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_cxp as cod_cxp, 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_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago,  final.empresa as empresa, final.moneda as moneda, final.glosa as glosa, final.pago as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxp as cod_cxp, 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_pago, otro.concepto as concepto, otro.via_pago as via_pago, otro.empresa as empresa, otro.moneda_cxp as moneda, otro.glosa as glosa, otro.pago as pago, otro.tipo as tipo, otro.tc as tc, otro.otra_moneda as otra_moneda, otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, otro.tasa * otro.pago as total, otro.cod_cxp as cod_cxp, 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, r.fldRate as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp, t.empresa as empresa, t.moneda_pago as moneda_pago, t.glosa as glosa, t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 1 as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, a.fldDate as fecha, null as fecha_cob_pag, null as concepto, i.fldName as via_pago, d.fldName as empresa, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnCompany d, actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codClient = d.pkyCompany and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = t.otra_moneda) otro) final
$cadena_no

UNION ALL 

select final.codigo as codigo, final.nrodoc as nrodoc, final.fecha as fecha, final.fecha_pago as fecha_pago, final.concepto as concepto, final.via_pago as via_pago, final.empleado as empresa,  final.moneda as moneda, final.glosa as glosa, final.pago as total, final.tipo as tipo, final.tasa as tasa, final.total as total_om, final.cod_cxp as cod_cxp, 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_pago, 
otro.concepto as concepto,  
otro.via_pago as via_pago, otro.empleado as empleado, 
otro.moneda_cxp as moneda, otro.glosa as glosa, 
otro.pago as pago, otro.tipo as tipo, otro.tc as tc, 
otro.otra_moneda as otra_moneda, 
otro.cod_moneda_cxp as cod_moneda, otro.tasa as tasa, 
otro.tasa * otro.pago as total, otro.cod_cxp as cod_cxp, 
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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
r.fldRate as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i
where 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t,
actExchangeRateDetail r
where
t.tc = r.codExchangeRate and
t.cod_moneda_cxp = 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.via_pago as via_pago, 
t.cod_moneda_cxp as cod_moneda_cxp, t.moneda_cxp as moneda_cxp,
t.empleado as empleado, 
t.moneda_pago as moneda_pago, t.glosa as glosa, 
t.pago as pago, t.tipo as tipo, t.tc as tc, 
t.otra_moneda as otra_moneda, t.cod_moneda_pago as cod_moneda_pago, 
1 as tasa, t.cod_cxp as cod_cxp, t.papa as papa, t.cod_papa as cod_papa
from 
(select a.pkyPayment as codigo, a.fldDocumentNumber as nrodoc, 
a.fldDate as fecha, null as fecha_cob_pag, null as concepto, 
i.fldName as via_pago, case when e.fldMiddleName is NULL then concat(e.fldLastName,', ',e.fldFirstName) else concat(e.fldLastName,' ',e.fldMiddleName,', ',e.fldFirstName) end as empleado, g.codCurrency as cod_moneda_cxp, h.fldName as moneda_cxp, 
f.fldName as moneda_pago, a.txtDescription as glosa, (b.fldTotal * -1) as pago, 
'Pago' as tipo, '$ultimo_tc_det' as tc, '$otra_moneda_det' as otra_moneda, 
a.codCurrency as cod_moneda_pago, g.pkyAccountsPayable as cod_cxp, a.fldParentComponent as papa, a.cosComponentKey as cod_papa
from
payPayment a, payPaymentDetail b, agnPerson e, 
actCurrency f, payAccountsPayable g, actCurrency h, payPaymentRoute i 
where 
$valor_ver2_det 
$valor_proyectado2_det 
$valor_contexto_det 
g.codConcept = '$nombredet' and
a.fldDate >= '$fechainidet' and
a.fldDate <= '$fechafindet' and 
a.codRoute = i.pkyPaymentRoute and 
a.pkyPayment = b.codPayment and
a.codEmployee = e.pkyPerson and
a.codCurrency = f.pkyCurrency and
g.codCurrency = h.pkyCurrency and
b.codAccountsPayable is not NULL and
b.codAccountsPayable = g.pkyAccountsPayable and
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_cxp = 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";
		
		$codigo_detp = $row['codigo'];
		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
		}
		printf("<td align='center'><a href='../../ModulePayments/VoucherPayment/index.php?pkyPayment=$codigo_detp&user=$usuario_det' title='Nota de Pago'>%s</a></td>", $row['codigo']);//cod
		printf("<td align='center'>%s</td>", $row['nrodoc']);//nro doc
		printf("<td align='center'>&nbsp;</td>");//cod_proy
		printf("<td align='right'>%s</td>", $row['fecha']);//fecha
		printf("<td align='right'>%s</td>", $row['fecha_pago']);//fecha pago
		//printf("<td>%s</td>", $row['concepto']);//concepto viene con NULL
		printf("<td>%s</td>", $row['via_pago']);//via pago
		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>&nbsp;</td>");//total otra moneda debito
		printf("<td align='right'>%s</td>", number_format($row['total_om'],$n_decimales));//total otra moneda credito
		$suma_cred = $suma_cred + $row['total_om'];
		} else {
		printf("<td align='right'>%s</td>", number_format($row['total_om']*-1,$n_decimales));//total otra moneda debito
		printf("<td>&nbsp;</td>");//total otra moneda credito
		$suma_deb = $suma_deb + $row['total_om'];
		}
		$suma_det_solo = $suma_det_solo + $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*-1,$n_decimales); ?></b></TD>
  <TD align="right"><b><?php echo number_format($suma_cred,$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


?>

</body>
</html>
