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

</head>
<?php
/*
Muestra las ordenes de compra combinando Item con proveedor o con almacen no cruza proveedor y almacen aunque se probo que se puede conseguir esta opción eliminando las marcas en la lineas de codigo mas abajo, pero no está probado, el detalle del total distingue los diferentes cruces item proveedor, item almacen o item solamente en el de item solamente el detalle es de todas las compras del item, en los cruces el detalle discrimina filtrando items de un determinado proveedor o de un determinado almacen, el detalle del periodo muestra el kardex del item como el de total pero entre las fechas (modificado por sugerencia de M).
Se adicionó la comparación del monto de la orden de compra con la recepción de la mercadería en dos columnas para tener la diferencia de lo pedido y lo recibido en dinero.
*/
include "../../conn.php";
include "../../general.php";
include "../../token.php";

$rep=$_GET["rep"];
$tipo=$_GET["tipo"];
$item=$_POST["item"];
$proveedor=$_POST["proveedor"];
$almacen=$_POST["almacen"];
$familia=$_POST["familia"];
$subfamilia=$_POST["subfamilia"];
$grupo=$_POST["grupo"];
$subgrupo=$_POST["subgrupo"];
$fechaini=$_POST["fechaini"];
$fechafin=$_POST["fechafin"];
$asientocc=$_POST["asientocc"];
//$usuario = $_POST["usuario"];
$otra_moneda=$_POST["otra_moneda"];
$combinar=$_POST["combinar"];
$mostrar=$_POST["mostrar"];
$cod_contexto=$_POST["contexto"];

$cod_cxc=$_GET["cod_cxc"];
$empresa=$_GET["empresa"];
$otra_moneda_det=$_GET["otra_moneda_det"];
$combinar_det=$_GET["combinar_det"];
$cod_item_det=$_GET["cod_item_det"];
$cod_pro_det=$_GET["cod_pro_det"];
$cod_alm_det=$_GET["cod_alm_det"];
$familia_det=$_GET["familia_det"];
$subfamilia_det=$_GET["subfamilia_det"];
$grupo_det=$_GET["grupo_det"];
$subgrupo_det=$_GET["subgrupo_det"];
$fechaini_det=$_GET["fechaini_det"];
$fechafin_det=$_GET["fechafin_det"];
$periodo_det=$_GET["periodo_det"];
$asientocc_det=$_GET["asientocc_det"];
//$usuario_det = $_GET["usuario_det"];
$mostrar_det = $_GET["mostrar_det"];
$cod_contexto_det=$_GET["contexto_det"];
//$n_decimales = 6;
if($familia == '') { $familia = 0;}
if($subfamilia == '') { $subfamilia = 0;}
if($grupo == '') { $grupo = 0;}
if($subgrupo == '') { $subgrupo = 0;}

?>
<body>

	<?php
	
//Inicio reporte compras por Item


if($rep == 14 && $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);

$otra_moneda_det = $otra_moneda;

if($mostrar == 1) {
	$nom_mostrar = 'Solo Ordenes de compra pendientes';
} else {
	$nom_mostrar = 'Todas las Ordenes de compra';
}
if ($combinar == 0) { //if combinar = 0
	$valor_agrupar = 'group by fin.cod_item';
	$valor_ordenar = 'order by fin.item, fin.proveedor';
	$valor_agrupar3 = 'group by total.cod_item';
	$valor_ordenar3 = 'order by total.item, total.proveedor';
	$nom_orden = 'Item';
	$nom_combinar = 'Item';
	$almacen = 0; //si se quita permite combinar proveedor y almacen
	$proveedor = 0; //si se quita permite combinar proveedor y almacen
} //fin if combinar = 0
if ($combinar == 1) { //if combinar = 1
   	$valor_agrupar = 'group by fin.cod_pro, fin.cod_item';
	$valor_ordenar = 'order by fin.proveedor, fin.item';
	$valor_agrupar2 = 'group by fin2.cod_pro';
	$valor_ordenar2 = 'order by fin2.proveedor, fin2.item';
	$valor_agrupar3 = 'group by total.cod_pro, total.cod_item';
	$valor_ordenar3 = 'order by total.proveedor, total.item';
	$nom_orden = 'Proveedor e Item';
	$nom_combinar = 'Proveedor';
	$almacen = 0; //si se quita permite combinar proveedor y almacen
} //fin if combinar = 1
if ($combinar == 2) { //if combinar = 2
   	$valor_agrupar = 'group by fin.cod_alm, fin.cod_item';
	$valor_ordenar = 'order by fin.almacen, fin.item';
	$valor_agrupar2 = 'group by fin2.cod_alm';
	$valor_ordenar2 = 'order by fin2.almacen, fin2.item';
	$valor_agrupar3 = 'group by total.cod_alm, total.cod_item';
	$valor_ordenar3 = 'order by total.almacen, total.item';
	$nom_orden = 'Almacen e Item';
	$nom_combinar = 'Almacen';
	$proveedor = 0; //si se quita permite combinar proveedor y almacen
} //fin if combinar = 2

if ($item == 0) { //if item
	$nom_item = 'Todos';
	$valor_item = ' ';
  } else { 
  	$valor_item = ' h.codItem = '.$item.' and ';
	//nombre de item
$resultit = mysqli_query($link, "select pkyItem as codigo, fldName as item, fldFactoryKey as cod_fabrica
from 
invItem
where
pkyItem = '$item' and
sysEnabled = 1 and sysAuthorized = 1
order by item;");
	while ($row = mysqli_fetch_array($resultit)) {
	$nom_item = $row['codigo'].' - '.$row['cod_fabrica'].' - '.$row['item'];
	}
	mysqli_free_result($resultit);
  } //fin if item


if ($proveedor == 0) { //if proveedor
    $valor_proveedor = ' ';
	$nom_proveedor = 'Todos';
  } else { 
    $valor_proveedor = ' a.codSupplier = '.$proveedor.' and ';
	//nombre de proveedor
	$resultpro = mysqli_query($link, "select pkyCompany as codigo, fldName as proveedor
from agnCompany
where
fldIsSupplier = 1 and 
pkyCompany = '$proveedor' and
sysEnabled = 1 and sysAuthorized = 1
order by proveedor;");
	while ($row = mysqli_fetch_array($resultpro)) {
	$nom_proveedor = $row['proveedor'];
	}
	mysqli_free_result($resultpro);
  } //fin if proveedor

if ($almacen == 0) { //if almacen
    $valor_almacen = ' ';
	$nom_almacen = 'Todos';
  } else { 
    $valor_almacen = ' a.codWarehouse = '.$almacen.' and ';
	//nombre de almacen
	$resultalm = mysqli_query($link, "select pkyWarehouse as codigo, fldName as almacen
from invWarehouse
where
pkyWarehouse = '$almacen' and 
sysEnabled = 1 and sysAuthorized = 1
order by almacen;");
	while ($row = mysqli_fetch_array($resultalm)) {
	$nom_almacen = $row['almacen'];
	}
	mysqli_free_result($resultalm);
  } //fin if almacen

//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 ';	
}

if ($familia == 0) { // if familia
		$nom_familia = 'Todos';
		$valor_familia = ' ';
	} else {
		//nombre familia
		$resultfam = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$familia' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultfam)) {
			$nom_familia = $row['nombre'];
		}
		mysqli_free_result($resultfam);
		$valor_familia = ' i.codFamily = ' .$familia. ' and ';
} //fin if familia

if ($subfamilia == 0) { // if subfamilia
		$nom_subfamilia = 'Todos';
		$valor_subfamilia = ' ';
	} else {
		//nombre sub familia
		$resultsubf = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$subfamilia' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultsubf)) {
			$nom_subfamilia = $row['nombre'];
		}
		mysqli_free_result($resultsubf);
		$valor_subfamilia = ' i.codSubFamily = ' .$subfamilia. ' and ';
} //fin if subfamilia
	
if ($grupo == 0) { // if grupo
		$nom_grupo = 'Todos';
		$valor_grupo = ' ';
	} else {
		//nombre grupo
		$resultgru = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$grupo' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultgru)) {
			$nom_grupo = $row['nombre'];
		}
		mysqli_free_result($resultgru);
		$valor_grupo = ' i.codGroup = ' .$grupo. ' and ';
} //fin if grupo
	
if ($subgrupo == 0) { // if subgrupo
		$nom_subgrupo = 'Todos';
		$valor_subgrupo = ' ';
	} else {
		//nombre sub grupo
		$resultsubg = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$subgrupo' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultsubg)) {
			$nom_subgrupo = $row['nombre'];
		}
		mysqli_free_result($resultsubg);
		$valor_subgrupo = ' i.codSubGroup = ' .$subgrupo. ' and ';
} //fin if subgrupo
	
//listado de compras del periodo

if($mostrar == 1) {//if mostrar 1
//query con codStatus = 1 OC generadas solamente
$result = mysqli_query($link, "select fin.cod_item as cod_item, fin.item as item, fin.cod_fabrica as cod_fabrica,
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, t.cod_fabrica as cod_fabrica,
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, i.fldFactoryKey as cod_fabrica, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, t.cod_fabrica as cod_fabrica,
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, i.fldFactoryKey as cod_fabrica,
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar 
$valor_ordenar;");
} else {//else if mostrar 1
//query que hace un union all del de arriba para mostrar los generados y los recibidos
$result = mysqli_query($link, "select total.cod_item as cod_item, total.item as item, total.cod_fabrica as cod_fabrica, total.proveedor as proveedor, sum(total.cantidad) as cantidad, sum(total.precio_total_fin) as precio_total_fin, total.cod_pro as cod_pro, 
total.unidad_compra as unidad_compra, total.cod_alm as cod_alm, total.almacen as almacen, 
sum(total.cantidad_recib_fin) as cantidad_recib_fin
from
(
select fin.cod_item as cod_item, fin.item as item, fin.cod_fabrica as cod_fabrica,
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, 
sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, t.cod_fabrica as cod_fabrica,
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, i.fldFactoryKey as cod_fabrica,
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 2 and 
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, t.cod_fabrica as cod_fabrica,
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, i.fldFactoryKey as cod_fabrica,
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 2 and
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar

UNION ALL

select fin.cod_item as cod_item, fin.item as item, fin.cod_fabrica as cod_fabrica,
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, t.cod_fabrica as cod_fabrica,
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, i.fldFactoryKey as cod_fabrica,
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, t.cod_fabrica as cod_fabrica,
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, i.fldFactoryKey as cod_fabrica,
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar) total
$valor_agrupar3 
$valor_ordenar3;");
}//fin if mostrar 1
	
//listado de saldo inicial

if($mostrar == 1) {//if mostrar 2
//query con codStatus = 1 OC generadas solamente
$result1 = mysqli_query($link, "select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate < '$fechaini' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate < '$fechaini' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar 
$valor_ordenar;");
} else {//else if mostrar 2
$result1 = mysqli_query($link, "select total.cod_item as cod_item, total.item as item, total.proveedor as proveedor, sum(total.cantidad) as cantidad, sum(total.precio_total_fin) as precio_total_fin, total.cod_pro as cod_pro, 
total.unidad_compra as unidad_compra, total.cod_alm as cod_alm, total.almacen as almacen, 
sum(total.cantidad_recib_fin) as cantidad_recib_fin
from
(
select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, 
sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate < '$fechaini' and
a.codStatus = 2 and 
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate < '$fechaini' and
a.codStatus = 2 and
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar

UNION ALL

select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate < '$fechaini' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate < '$fechaini' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar) total
$valor_agrupar3 
$valor_ordenar3;");
}//fin if mostrar 2


  
if($otra_moneda != 0){ 
$mostrar_txt_moneda = $nom_otra_moneda;
} else {
$mostrar_txt_moneda = 'Moneda original';	
}

?>
<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>Ordenes de Compra por Item</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>Item: </b><?php echo $nom_item; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Proveedor: </b><?php echo $nom_proveedor; ?></TD>
        <TD width="25%"><b>Almacen: </b><?php echo $nom_almacen; ?></TD>
        </TR>
        <TR> 
        <TD><b>Familia: </b><?php echo $nom_familia; ?></TD>
        <TD><b>Sub Familia: </b><?php echo $nom_subfamilia; ?></TD>
        <TD><b>Grupo: </b><?php echo $nom_grupo; ?></TD>
        <TD><b>Sub Grupo: </b><?php echo $nom_subgrupo; ?></TD>
        </TR>
        <TR>
        <TD><b>Combinar Item con: </b><?php echo $nom_combinar; ?></TD>
        <TD><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Mostrar: </b><?php echo $nom_mostrar; ?></TD>
        <TD><b>Expresado en: </b><?php echo $mostrar_txt_moneda; ?></TD>
        </TR>
        <TR>
        <TD colspan="4"><b>Contexto: </b><?php echo $nom_contexto; ?></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; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td>", 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 />
<?php
if($combinar == 0) { //if combinar = 0, combina todos los items con todos los proveedores, tambien cuando se elige un solo item
?>
<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Uni. Compra</b></TD>
    <TD align="center"><b>Cant. Saldo</b></TD>
    <TD align="center"><b>Cant. No Recep. Saldo</b></TD>
    <TD align="center"><b>Precio x Cant. Saldo</b></TD>
    <TD align="center"><b>Cant. Periodo</b></TD>
    <TD align="center"><b>Cant. No Recep. Periodo</b></TD>
    <TD align="center"><b>Precio x Cant. Periodo</b></TD>
    <TD align="center"><b>Cant. Total</b></TD>
    <TD align="center"><b>Precio Uni.</b></TD>
    <TD align="center"><b>Precio x Cant. Total</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

    <?php

	// cargar listado compras del periodo 
		$matriz_item = array ();
		$i = 1;
		while ($row = mysqli_fetch_array($result)) {
			$matriz_item[$i][0] = $row['cod_fabrica'];
			$matriz_item[$i][1] = $row['cod_item'];
			$matriz_item[$i][2] = $row['item'];
			$matriz_item[$i][3] = $row['cod_pro'];
			$matriz_item[$i][4] = $row['proveedor'];
			$matriz_item[$i][5] = $row['cantidad'];
			$matriz_item[$i][6] = $row['precio_total_fin'];
			$matriz_item[$i][7] = 0;// cantidad saldo inicial
			$matriz_item[$i][8] = 0;// precio saldo inicial
			$matriz_item[$i][9] = $row['unidad_compra'];
			$matriz_item[$i][10] = $row['cantidad_recib_fin'];
			
			$i++;
			}
			mysqli_free_result($result);
		
		$fin_item = $i - 1;
		
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item']) {
					 $matriz_item[$i][7] = $row['cantidad'];
					 $matriz_item[$i][8] = $row['precio_total_fin'];
					 $matriz_item[$i][11] = $row['cantidad_recib_fin'];
					 
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
	
	$color = 2;
	
	$suma_cant = 0;
	$suma_precio = 0;
	
	$suma_cant_sal = 0;
	$suma_precio_sal = 0;
	
	$suma_cant_tot = 0;
	$suma_precio_tot = 0;
	
	$suma_saldo_no_recep = 0;
	$suma_periodo_no_recep = 0;
	$i = 1;
	
	while($i <= $fin_item) { //while
		//$codigo = $matriz_item[$i][14];
		if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		} else {
		printf("<tr><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		}//cierra if color
		printf("<td align='center'>%s</td>", $matriz_item[$i][0]);//cod fabrica
		printf("<td>%s</td>", $matriz_item[$i][2]);//item
		$cod_item_det = $matriz_item[$i][1];
		printf("<td>%s</td>", $matriz_item[$i][9]);//unidad de compra
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7],$n_cantidad));//saldo cant
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7] - $matriz_item[$i][11],$n_cantidad));//saldo no recepcionado
		//es la resta para la diferencia cantidad generada - cantidad recibida
		$suma_saldo_no_recep = $suma_saldo_no_recep + $matriz_item[$i][7] - $matriz_item[$i][11];	
				
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][8],$n_decimales));//saldo precio x cant
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][5],$n_cantidad));//cantidad
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][5] - $matriz_item[$i][10],$n_cantidad));//periodo no recepcionado
		$suma_periodo_no_recep = $suma_periodo_no_recep + $matriz_item[$i][5] - $matriz_item[$i][10];	
		
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=0&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Item del Periodo'>%s</a></td>", number_format($matriz_item[$i][6],$n_decimales));//precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=0&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Item del Periodo'>%s</a></td>", number_format($matriz_item[$i][6],$n_decimales));//precio x cant
		}
		$total_cantidad = $matriz_item[$i][7] + $matriz_item[$i][5];
		printf("<td align='right'>%s</td>", number_format($total_cantidad,$n_cantidad));// total cantidad
		$total_precio = $matriz_item[$i][8] + $matriz_item[$i][6];
		
		if($total_cantidad != 0) {
		   	$precio_unitario = $total_precio / $total_cantidad;
		} else { 
			$precio_unitario = 0;
		}
		printf("<td align='right'>%s</td>", number_format($precio_unitario,$n_decimales));// precio unitario
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=0&periodo_det=0&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Item'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=0&periodo_det=0&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Item'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant	
		}
		
		$suma_cant = $suma_cant + $matriz_item[$i][5];
		$suma_precio = $suma_precio + $matriz_item[$i][6];
	    
		$suma_cant_sal = $suma_cant_sal + $matriz_item[$i][7];
		$suma_precio_sal = $suma_precio_sal + $matriz_item[$i][8];
		
		$suma_cant_tot = $suma_cant_tot + $total_cantidad;
		$suma_precio_tot = $suma_precio_tot + $total_precio;
	  	$color++;
		$i++;
	}//fin while
	
	?>
 
<tr BGCOLOR='#ffcccc'><td colspan="5"><b>Totales</b></td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_saldo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_periodo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot,$n_decimales)); ?></td>
</tr>
</tbody>
</table>
         

<?php
	
} //fin combinar = 0
if ($combinar == 1) { // if combinar = 1
	
	//si combinar = 1 => mostrar proveedor
	?>
	<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Uni. Compra</b></TD>
    <TD align="center"><b>Proveedor</b></TD>
    <TD align="center"><b>Cant. Saldo</b></TD>
    <TD align="center"><b>Cant. No Recep. Saldo</b></TD>
    <TD align="center"><b>Precio x Cant. Saldo</b></TD>
    <TD align="center"><b>Cant. Periodo</b></TD>
    <TD align="center"><b>Cant. No Recep. Periodo</b></TD>
    <TD align="center"><b>Precio x Cant. Periodo</b></TD>
    <TD align="center"><b>Cant. Total</b></TD>
    <TD align="center"><b>Precio Uni.</b></TD>
    <TD align="center"><b>Precio x Cant. Total</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">
    
    <?php
	
	// cargar listado ventas del periodo 
		$matriz_item = array ();
		$i = 1;
		while ($row = mysqli_fetch_array($result)) {
			$matriz_item[$i][0] = $row['cod_fabrica'];
			$matriz_item[$i][1] = $row['cod_item'];
			$matriz_item[$i][2] = $row['item'];
			$matriz_item[$i][3] = $row['cod_pro'];
			$matriz_item[$i][4] = $row['proveedor'];
			$matriz_item[$i][5] = $row['cantidad'];
			$matriz_item[$i][6] = $row['precio_total_fin'];
			$matriz_item[$i][7] = 0;// cantidad saldo inicial
			$matriz_item[$i][8] = 0;// precio saldo inicial
			$matriz_item[$i][9] = $row['unidad_compra'];
			$matriz_item[$i][10] = $row['cantidad_recib_fin'];
			$i++;
			}
			mysqli_free_result($result);
		
		$fin_item = $i - 1;
		
	// cargar saldos iniciales por proveedor
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item'] && $matriz_item[$i][3] == $row['cod_pro']) {
					 $matriz_item[$i][7] = $row['cantidad'];
					 $matriz_item[$i][8] = $row['precio_total_fin'];
					 $matriz_item[$i][11] = $row['cantidad_recib_fin'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);

if($mostrar == 1) {//if mostrar 1
//query con codStatus = 1 OC generadas solamente
$result_it = mysqli_query($link, "select fin2.cod_item as cod_item, fin2.cod_pro as cod_pro,  count(fin2.cod_item) as num_reg
from(
select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar 
$valor_ordenar ) fin2
$valor_agrupar2 
$valor_ordenar2;");
} else {//else if mostrar 1
//query que hace un union all del de arriba para mostrar los generados y los recibidos
$result_it = mysqli_query($link, "select fin2.cod_item as cod_item, fin2.cod_pro as cod_pro,  count(fin2.cod_item) as num_reg
from(
select total.cod_item as cod_item, total.item as item, total.proveedor as proveedor, sum(total.cantidad) as cantidad, sum(total.precio_total_fin) as precio_total_fin, total.cod_pro as cod_pro, 
total.unidad_compra as unidad_compra, total.cod_alm as cod_alm, total.almacen as almacen, 
sum(total.cantidad_recib_fin) as cantidad_recib_fin
from
(
select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, 
sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 2 and 
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 2 and
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar

UNION ALL

select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar) total
$valor_agrupar3 
$valor_ordenar3 ) fin2
$valor_agrupar2 
$valor_ordenar2;");
}//fin if mostrar 1


	
	$matriz_it = array ();
	$i = 1;
	//verifica cuantos registros mostrara en el while de abajo para proveedor
	while ($row = mysqli_fetch_array($result_it)) {
	$matriz_it[$i][1] = $row['cod_pro'];
	$matriz_it[$i][2] = $row['num_reg'];
	$i++;
	}
	
	$fin_it = $i - 1;
	
	mysqli_free_result($result_it);
	
	$color = 2;
	$suma_cant = 0;
	$suma_precio = 0;
	
	$suma_cant_sal = 0;
	$suma_precio_sal = 0;
	
	$suma_cant_tot = 0;
	$suma_precio_tot = 0;
	
	$suma_saldo_no_recep = 0;
	$suma_periodo_no_recep = 0;
	
	
	$suma_cant_par = 0;
	$suma_precio_par = 0;
	
	$suma_cant_sal_par = 0;
	$suma_precio_sal_par = 0;
	
	$suma_cant_tot_par = 0;
	$suma_precio_tot_par = 0;
	
	$suma_saldo_no_recep_par = 0;
	$suma_periodo_no_recep_par = 0;
	$i = 1;
	$j = 1;
	
	while($j <= $fin_it){//while $fin_it
		$k = 1;
	while($k <= $matriz_it[$j][2]) { //while
		if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		} else {
		printf("<tr><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		}//cierra if color
		printf("<td align='center'>%s</td>", $matriz_item[$i][0]);//cod fabrica
		printf("<td>%s</td>", $matriz_item[$i][2]);//item
		$cod_item_det = $matriz_item[$i][1];
		printf("<td>%s</td>", $matriz_item[$i][9]);//unidad de compra
		printf("<td>%s</td>", $matriz_item[$i][4]);//proveedor
		$cod_pro2 = $matriz_item[$i][3]; //cod proveedor
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7],$n_cantidad));//saldo cant
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7] - $matriz_item[$i][11],$n_cantidad));//saldo no recepcionado
		//es la resta para la diferencia cantidad generada - cantidad recibida
		$suma_saldo_no_recep = $suma_saldo_no_recep + $matriz_item[$i][7] - $matriz_item[$i][11];
		$suma_saldo_no_recep_par = $suma_saldo_no_recep_par + $matriz_item[$i][7] - $matriz_item[$i][11];
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][8],$n_decimales));//saldo precio x cant
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][5],$n_cantidad));//cantidad
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][5] - $matriz_item[$i][10],$n_cantidad));//periodo no recepcionado
		$suma_periodo_no_recep = $suma_periodo_no_recep + $matriz_item[$i][5] - $matriz_item[$i][10];
		$suma_periodo_no_recep_par = $suma_periodo_no_recep_par + $matriz_item[$i][5] - $matriz_item[$i][10];
				
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=1&cod_pro_det=$cod_pro2&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Proveedor del Periodo'>%s</a></td>", number_format($matriz_item[$i][6],$n_decimales));//precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=1&cod_pro_det=$cod_pro2&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Proveedor del Periodo'>%s</a></td>", number_format($matriz_item[$i][6],$n_decimales));//precio x cant
		}
		$total_cantidad = $matriz_item[$i][7] + $matriz_item[$i][5];
		printf("<td align='right'>%s</td>", number_format($total_cantidad,$n_cantidad));// total cantidad
		$total_precio = $matriz_item[$i][8] + $matriz_item[$i][6];
		
		if($total_cantidad != 0) {
		   	$precio_unitario = $total_precio / $total_cantidad;
		} else { 
			$precio_unitario = 0;
		}
		printf("<td align='right'>%s</td>", number_format($precio_unitario,$n_decimales));// precio unitario
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=1&cod_pro_det=$cod_pro2&periodo_det=0&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Proveedor'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=1&cod_pro_det=$cod_pro2&periodo_det=0&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Proveedor'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant	
		}
		
		$suma_cant = $suma_cant + $matriz_item[$i][5];
		$suma_precio = $suma_precio + $matriz_item[$i][6];
	    
		$suma_cant_sal = $suma_cant_sal + $matriz_item[$i][7];
		$suma_precio_sal = $suma_precio_sal + $matriz_item[$i][8];
		
		$suma_cant_tot = $suma_cant_tot + $total_cantidad;
		$suma_precio_tot = $suma_precio_tot + $total_precio;
		
		$suma_cant_par = $suma_cant_par + $matriz_item[$i][5];
		$suma_precio_par = $suma_precio_par + $matriz_item[$i][6];
	    
		$suma_cant_sal_par = $suma_cant_sal_par + $matriz_item[$i][7];
		$suma_precio_sal_par = $suma_precio_sal_par + $matriz_item[$i][8];
		
		$suma_cant_tot_par = $suma_cant_tot_par + $total_cantidad;
		$suma_precio_tot_par = $suma_precio_tot_par + $total_precio;
	  	$color++;
		$i++;
		$k++;
	}//fin while
	$j++;
	?>
<?php if($item == 0) { ?>
<tr BGCOLOR='#ffcccc'>
<td colspan="6"><b>Total Periodo Proveedor <?php echo $matriz_item[$i-1][4]; ?></b></td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_saldo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal_par,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_periodo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_par,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot_par,$n_decimales)); ?></td>
</tr>

<?php } else { ?>
<tr BGCOLOR='#ffcccc'>
<td colspan="5"><b>Total Periodo Proveedor <?php echo $matriz_item[$i-1][4]; ?></b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_sal_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_saldo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal_par,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_periodo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_par,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_tot_par,$n_cantidad)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot_par,$n_decimales)); ?></td>
</tr>
<?php } ?>

 <?php
	$suma_cant_par = 0;
	$suma_precio_par = 0;
	
	$suma_cant_sal_par = 0;
	$suma_precio_sal_par = 0;
	
	$suma_cant_tot_par = 0;
	$suma_precio_tot_par = 0;	
	
	$suma_saldo_no_recep_par = 0;
	$suma_periodo_no_recep_par = 0;
	}//fin while $fin_it
	

?>
<?php if($item == 0) { ?> 
<tr BGCOLOR='#ffcccc'><td colspan="6"><b>Totales</b></td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_saldo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_periodo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot,$n_decimales)); ?></td>
</tr>
</tbody>
</table>
<?php } else { ?>
<tr BGCOLOR='#ffcccc'><td colspan="5"><b>Totales</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_sal,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_saldo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_periodo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_tot,$n_cantidad)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot,$n_decimales)); ?></td>
</tr>
</tbody>
</table>
<?php } ?>            

<?php
	
}//fin if combinar = 1
if ($combinar == 2) { // if combinar = 2
	
	//si combinar = 2 => mostrar almacen
	?>
	<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Uni. Compra</b></TD>
    <TD align="center"><b>Almacen</b></TD>
    <TD align="center"><b>Cant. Saldo</b></TD>
    <TD align="center"><b>Cant. No Recep. Saldo</b></TD>
    <TD align="center"><b>Precio x Cant. Saldo</b></TD>
    <TD align="center"><b>Cant. Periodo</b></TD>
    <TD align="center"><b>Cant. No Recep. Periodo</b></TD>
    <TD align="center"><b>Precio x Cant. Periodo</b></TD>
    <TD align="center"><b>Cant. Total</b></TD>
    <TD align="center"><b>Precio Uni.</b></TD>
    <TD align="center"><b>Precio x Cant. Total</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">
    
    <?php
	
	// cargar listado ventas del periodo 
		$matriz_item = array ();
		$i = 1;
		while ($row = mysqli_fetch_array($result)) {
			$matriz_item[$i][0] = $row['cod_fabrica'];
			$matriz_item[$i][1] = $row['cod_item'];
			$matriz_item[$i][2] = $row['item'];
			$matriz_item[$i][3] = $row['cod_alm'];
			$matriz_item[$i][4] = $row['almacen'];
			$matriz_item[$i][5] = $row['cantidad'];
			$matriz_item[$i][6] = $row['precio_total_fin'];
			$matriz_item[$i][7] = 0;// cantidad saldo inicial
			$matriz_item[$i][8] = 0;// precio saldo inicial
			$matriz_item[$i][9] = $row['unidad_compra'];
			$matriz_item[$i][10] = $row['cantidad_recib_fin'];
			$i++;
			}
			mysqli_free_result($result);
		
		$fin_item = $i - 1;
		
	// cargar saldos iniciales por almacen
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item'] && $matriz_item[$i][3] == $row['cod_alm']) {
					 $matriz_item[$i][7] = $row['cantidad'];
					 $matriz_item[$i][8] = $row['precio_total_fin'];
					 $matriz_item[$i][11] = $row['cantidad_recib_fin'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
		
if($mostrar == 1) {//if mostrar 1
//query con codStatus = 1 OC generadas solamente
$result_it = mysqli_query($link, "select fin2.cod_item as cod_item, fin2.cod_alm as cod_alm,  count(fin2.cod_item) as num_reg
from(
select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar 
$valor_ordenar ) fin2
$valor_agrupar2 
$valor_ordenar2;");
} else {//else if mostrar 1
//query que hace un union all del de arriba para mostrar los generados y los recibidos
$result_it = mysqli_query($link, "select fin2.cod_item as cod_item, fin2.cod_alm as cod_alm,  count(fin2.cod_item) as num_reg
from(
select total.cod_item as cod_item, total.item as item, total.proveedor as proveedor, sum(total.cantidad) as cantidad, sum(total.precio_total_fin) as precio_total_fin, total.cod_pro as cod_pro, 
total.unidad_compra as unidad_compra, total.cod_alm as cod_alm, total.almacen as almacen, 
sum(total.cantidad_recib_fin) as cantidad_recib_fin
from
(
select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, 
sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 2 and 
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, 
t.cantidad_recib as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 2 and
a.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
h.codItem = l. codItem and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar

UNION ALL

select fin.cod_item as cod_item, fin.item as item, 
fin.proveedor as proveedor, sum(fin.cantidad) as cantidad, 
sum(fin.precio_total_fin) as precio_total_fin, fin.cod_pro as cod_pro, 
fin.unidad_compra as unidad_compra, fin.cod_alm as cod_alm, fin.almacen as almacen, sum(fin.cantidad_recib_fin) as cantidad_recib_fin
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm,  
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
tc.fldRate as tasa, t.cod_pro as cod_pro, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm,  
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc, h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and 
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_compra and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_compra

union all

select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, 
t.proveedor as proveedor, t.almacen as almacen, t.cod_alm as cod_alm, 
t.moneda_compra as moneda_compra, t.cod_tc_compra as cod_tc_compra, 
t.cantidad as cantidad, t.precio as precio, 
t.desc_porc as desc_porc, t.precio_total as precio_total,
t.cod_cxp as cod_cxp, t.cod_moneda_compra as cod_moneda_compra, 
1 as tasa, t.cod_pro as cod_pro, t.precio * 1 as precio_fin,
t.precio_total * 1 as precio_total_fin, t.unidad_compra as unidad_compra, t.cantidad_recib_fin as cantidad_recib_fin
from
(select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as proveedor, d.fldName as almacen, a.codWarehouse as cod_alm, 
f.fldName as moneda_compra, a.codExchangeRate as cod_tc_compra, 
h.fldQuantity as cantidad, h.fldPrice as precio, 
h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountPayable as cod_cxp, 
a.codCurrency as cod_moneda_compra, 
a.codSupplier as cod_pro, j.fldName as unidad_compra, 0 as cantidad_recib_fin
from pchPurchaseOrder a, agnCompany c, invWarehouse d, 
actCurrency f, pchPurchaseOrderDetail h, invItem i, invStorageUnit j
where 
$valor_item 
$valor_proveedor 
$valor_almacen 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_contexto 
a.fldDate >= '$fechaini' and
a.fldDate <= '$fechafin' and
a.codStatus = 1 and 
a.codSupplier = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codCurrency = f.pkyCurrency and 
h.codPurchaseOrder = a.pkyPurchaseOrder and 
i.pkyItem = h.codItem and 
h.codMaximumStorageUnit = j.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_compra = '$otra_moneda') fin 
$valor_agrupar) total
$valor_agrupar3 
$valor_ordenar3 ) fin2
$valor_agrupar2 
$valor_ordenar2;");
}//fin if mostrar 1
	
	$matriz_it = array ();
	$i = 1;
	//verifica cuantos registros mostrara en el while de abajo para proveedor
	while ($row = mysqli_fetch_array($result_it)) {
	$matriz_it[$i][1] = $row['cod_alm'];
	$matriz_it[$i][2] = $row['num_reg'];
	$i++;
	}
	
	$fin_it = $i - 1;
	
	mysqli_free_result($result_it);
	
	$color = 2;
	$suma_cant = 0;
	$suma_precio = 0;
	
	$suma_cant_sal = 0;
	$suma_precio_sal = 0;
	
	$suma_cant_tot = 0;
	$suma_precio_tot = 0;
	$suma_saldo_no_recep = 0;
	$suma_periodo_no_recep = 0;
	
	
	$suma_cant_par = 0;
	$suma_precio_par = 0;
	
	$suma_cant_sal_par = 0;
	$suma_precio_sal_par = 0;
	
	$suma_cant_tot_par = 0;
	$suma_precio_tot_par = 0;
	
	$suma_saldo_no_recep_par = 0;
	$suma_periodo_no_recep_par = 0;
	$i = 1;
	$j = 1;
	
	while($j <= $fin_it){//while $fin_it
		$k = 1;
	while($k <= $matriz_it[$j][2]) { //while
		if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		} else {
		printf("<tr><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		}//cierra if color
		printf("<td align='center'>%s</td>", $matriz_item[$i][0]);//cod fabrica
		printf("<td>%s</td>", $matriz_item[$i][2]);//item
		$cod_item_det = $matriz_item[$i][1];
		printf("<td>%s</td>", $matriz_item[$i][9]);//unidad de compra
		printf("<td>%s</td>", $matriz_item[$i][4]);//almacen
		$cod_alm2 = $matriz_item[$i][3]; //cod almacen
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7],$n_cantidad));//saldo cant
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7] - $matriz_item[$i][11],$n_cantidad));//saldo no recepcionado
		//es la resta para la diferencia cantidad generada - cantidad recibida
		$suma_saldo_no_recep = $suma_saldo_no_recep + $matriz_item[$i][7] - $matriz_item[$i][11];
		$suma_saldo_no_recep_par = $suma_saldo_no_recep_par + $matriz_item[$i][7] - $matriz_item[$i][11];
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][8],$n_decimales));//saldo precio x cant
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][5],$n_cantidad));//cantidad
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][5] - $matriz_item[$i][10],$n_cantidad));//saldo no recepcionado
		//es la resta para la diferencia cantidad generada - cantidad recibida
		$suma_saldo_no_recep = $suma_saldo_no_recep + $matriz_item[$i][5] - $matriz_item[$i][10];
		$suma_saldo_no_recep_par = $suma_saldo_no_recep_par + $matriz_item[$i][5] - $matriz_item[$i][10];
		
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=2&cod_alm_det=$cod_alm2&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Almacen del Periodo'>%s</a></td>", number_format($matriz_item[$i][6],$n_decimales));//precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=2&cod_alm_det=$cod_alm2&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Almacen del Periodo'>%s</a></td>", number_format($matriz_item[$i][6],$n_decimales));//precio x cant
		}
		$total_cantidad = $matriz_item[$i][7] + $matriz_item[$i][5];
		printf("<td align='right'>%s</td>", number_format($total_cantidad,$n_cantidad));// total cantidad
		$total_precio = $matriz_item[$i][8] + $matriz_item[$i][6];
		
		if($total_cantidad != 0) {
		   	$precio_unitario = $total_precio / $total_cantidad;
		} else { 
			$precio_unitario = 0;
		}
		printf("<td align='right'>%s</td>", number_format($precio_unitario,$n_decimales));// precio unitario
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=2&cod_alm_det=$cod_alm2&periodo_det=0&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Almacen'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=13&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=2&cod_alm_det=$cod_alm2&periodo_det=0&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&usuario_det=$usuario&token=$token&mostrar_det=$mostrar&contexto_det=$cod_contexto&asientocc_det=$asientocc' title='Kardex de Compras por Almacen'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant	
		}
		
		$suma_cant = $suma_cant + $matriz_item[$i][5];
		$suma_precio = $suma_precio + $matriz_item[$i][6];
	    
		$suma_cant_sal = $suma_cant_sal + $matriz_item[$i][7];
		$suma_precio_sal = $suma_precio_sal + $matriz_item[$i][8];
		
		$suma_cant_tot = $suma_cant_tot + $total_cantidad;
		$suma_precio_tot = $suma_precio_tot + $total_precio;
		
		$suma_cant_par = $suma_cant_par + $matriz_item[$i][5];
		$suma_precio_par = $suma_precio_par + $matriz_item[$i][6];
	    
		$suma_cant_sal_par = $suma_cant_sal_par + $matriz_item[$i][7];
		$suma_precio_sal_par = $suma_precio_sal_par + $matriz_item[$i][8];
		
		$suma_cant_tot_par = $suma_cant_tot_par + $total_cantidad;
		$suma_precio_tot_par = $suma_precio_tot_par + $total_precio;
	  	$color++;
		$i++;
		$k++;
	}//fin while
	$j++;
	?>
<?php if($item == 0) { ?>
<tr BGCOLOR='#ffcccc'>
<td colspan="6"><b>Total Periodo Almacen <?php echo $matriz_item[$i-1][4]; ?></b></td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_saldo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal_par,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_periodo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_par,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot_par,$n_decimales)); ?></td>
</tr>

<?php } else { ?>
<tr BGCOLOR='#ffcccc'>
<td colspan="5"><b>Total Periodo Almacen <?php echo $matriz_item[$i-1][4]; ?></b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_sal_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_saldo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal_par,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_periodo_no_recep_par,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_par,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_tot_par,$n_cantidad)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot_par,$n_decimales)); ?></td>
</tr>
<?php } ?>

 <?php
	$suma_cant_par = 0;
	$suma_precio_par = 0;
	
	$suma_cant_sal_par = 0;
	$suma_precio_sal_par = 0;
	
	$suma_cant_tot_par = 0;
	$suma_precio_tot_par = 0;	
	
	$suma_saldo_no_recep_par = 0;
	$suma_periodo_no_recep_par = 0;
	}//fin while $fin_it
	

?>
<?php if($item == 0) { ?> 
<tr BGCOLOR='#ffcccc'><td colspan="6"><b>Totales</b></td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_saldo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php //printf("<b>%s</b>", number_format($suma_periodo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot,$n_decimales)); ?></td>
</tr>
</tbody>
</table>
<?php } else { ?>
<tr BGCOLOR='#ffcccc'><td colspan="5"><b>Totales</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_sal,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_saldo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_sal,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_periodo_no_recep,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_tot,$n_cantidad)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio_tot,$n_decimales)); ?></td>
</tr>
</tbody>
</table>
<?php } ?>            

<?php
	
	}//fin if combinar = 2
} //fin if 2



//Inicio muestra detalle


if($rep == 13 && $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 = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);

if ($combinar_det == 0) { //if combinar_det = 0
$valor_pro_det = ' ';
$valor_alm_det = ' ';
$nom_pro_o_alm = 'Item';
}//fin if combinar_det = 0
if ($combinar_det == 1) { //if combinar_det = 1
$valor_pro_det = ' c.codSupplier = ' .$cod_pro_det. ' and ';
$valor_alm_det = ' ';
$nom_pro_o_alm = 'Proveedor';
}//fin if combinar_det = 1
if ($combinar_det == 2) { //if combinar_det = 2
$valor_pro_det = ' ';
$valor_alm_det = ' c.codWarehouse = ' .$cod_alm_det. ' and ';
$nom_pro_o_alm = 'Almacen';
}//fin if combinar_det = 2

if ($periodo_det == 0) { //if periodo_det = 0
$valor_fecha_ini_det = ' ';
$valor_fecha_fin_det = ' ';
$nom_fecha_det = '<b>Kardex Completo</b>';
} //fin if periodo_det = 0
if ($periodo_det == 1) { //if periodo_det = 1
$comilla = "'" ;
$valor_fecha_ini_det = ' c.fldDate >= '.$comilla.$fechaini_det.$comilla.' and ';
$valor_fecha_fin_det = ' c.fldDate <= '.$comilla.$fechafin_det.$comilla.' and ';
$nom_fecha_det = '<b>De Fecha: </b>'.$fechaini_det.' <b>a Fecha: </b>'.$fechafin_det;
} //fin if periodo_det = 1

if($mostrar_det == 1) {
	$nom_mostrar_det = 'Solo Ordenes de compra pendientes';
} else {
	$nom_mostrar_det = 'Todas las Ordenes de compra';
}

if ($familia_det == 0) { // if familia
		$nom_familia_det = 'Todos';
		$valor_familia_det = ' ';
	} else {
		//nombre familia
		$resultfam = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$familia_det' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultfam)) {
			$nom_familia_det = $row['nombre'];
		}
		mysqli_free_result($resultfam);
		$valor_familia_det = ' b.codFamily = ' .$familia_det. ' and ';
} //fin if familia

if ($subfamilia_det == 0) { // if subfamilia
		$nom_subfamilia_det = 'Todos';
		$valor_subfamilia_det = ' ';
	} else {
		//nombre sub familia
		$resultsubf = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$subfamilia_det' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultsubf)) {
			$nom_subfamilia_det = $row['nombre'];
		}
		mysqli_free_result($resultsubf);
		$valor_subfamilia_det = ' b.codSubFamily = ' .$subfamilia_det. ' and ';
} //fin if subfamilia
	
if ($grupo_det == 0) { // if grupo
		$nom_grupo_det = 'Todos';
		$valor_grupo_det = ' ';
	} else {
		//nombre grupo
		$resultgru = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$grupo_det' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultgru)) {
			$nom_grupo_det = $row['nombre'];
		}
		mysqli_free_result($resultgru);
		$valor_grupo_det = ' b.codGroup = ' .$grupo_det. ' and ';
} //fin if grupo
	
if ($subgrupo_det == 0) { // if subgrupo
		$nom_subgrupo_det = 'Todos';
		$valor_subgrupo_det = ' ';
	} else {
		//nombre sub grupo
		$resultsubg = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
							from 
							invItemCategory
							where
							pkyItemCategory = '$subgrupo_det' and 
							sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($resultsubg)) {
			$nom_subgrupo_det = $row['nombre'];
		}
		mysqli_free_result($resultsubg);
		$valor_subgrupo_det = ' b.codSubGroup = ' .$subgrupo_det. ' and ';
} //fin if subgrupo

//contexto
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 = ' c.sysContext = '.$cod_contexto_det.' and ';	
}

if($mostrar_det == 1) {
$resultdet = mysqli_query($link, "select c.pkyPurchaseOrder as codigo, a.fldQuantity as cantidad,
a.fldPrice as precio, a.fldDiscount as descuento, b.fldFactoryKey as cod_fabrica, 
a.fldTotalNetPrice as total, b.fldName as item, 
c.fldDate as fecha, c.fldNumber as nro_doc, 
d.fldName as proveedor, c.codAccountPayable as cod_cxp, c.codAccountEntry as cod_asiento,
e.fldName as moneda, c.codCurrency as cod_moneda, 
c.codExchangeRate as cod_tc, c.codWarehouse as cod_alm, 
f.fldName as almacen, c.codSupplier as cod_pro, 0 as cantidad_recib
from
pchPurchaseOrderDetail a, invItem b, pchPurchaseOrder c, 
agnCompany d, actCurrency e, invWarehouse f
where 
$valor_fecha_ini_det 
$valor_fecha_fin_det 
$valor_pro_det 
$valor_alm_det 
$valor_familia_det  
$valor_subfamilia_det 
$valor_grupo_det 
$valor_subgrupo_det 
$valor_contexto_det 
c.codStatus = 1 and 
a.codItem = b.pkyItem and 
a.codItem = '$cod_item_det' and 
a.codPurchaseOrder = c.pkyPurchaseOrder and 
c.codSupplier = d.pkyCompany and 
c.codCurrency = e.pkyCurrency and 
c.codWarehouse = f.pkyWarehouse and 
c.sysEnabled = 1 and c.sysAuthorized = 1
order by fecha;");
} else {
$resultdet = mysqli_query($link, "select t.codigo as codigo, t.cantidad as cantidad,
t.precio as precio, t.descuento as descuento, t.cod_fabrica as cod_fabrica, t.total as total, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, t.proveedor as proveedor, t.cod_cxp as cod_cxp, t.cod_asiento as cod_asiento, t.moneda as moneda, t.cod_moneda as cod_moneda, t.cod_tc as  cod_tc, t.cod_alm as cod_alm, t.almacen as almacen, t.cod_pro as cod_pro, t.cantidad_recib as cantidad_recib
from (
select c.pkyPurchaseOrder as codigo, a.fldQuantity as cantidad,
a.fldPrice as precio, a.fldDiscount as descuento, b.fldFactoryKey as cod_fabrica,
a.fldTotalNetPrice as total, b.fldName as item, 
c.fldDate as fecha, c.fldNumber as nro_doc, 
d.fldName as proveedor, c.codAccountPayable as cod_cxp, c.codAccountEntry as cod_asiento,
e.fldName as moneda, c.codCurrency as cod_moneda, 
c.codExchangeRate as cod_tc, c.codWarehouse as cod_alm, 
f.fldName as almacen, c.codSupplier as cod_pro, 0 as cantidad_recib
from
pchPurchaseOrderDetail a, invItem b, pchPurchaseOrder c, 
agnCompany d, actCurrency e, invWarehouse f
where 
$valor_fecha_ini_det 
$valor_fecha_fin_det 
$valor_pro_det 
$valor_alm_det 
$valor_familia_det  
$valor_subfamilia_det 
$valor_grupo_det 
$valor_subgrupo_det 
$valor_contexto_det 
c.codStatus = 1 and 
a.codItem = b.pkyItem and 
a.codItem = '$cod_item_det' and 
a.codPurchaseOrder = c.pkyPurchaseOrder and 
c.codSupplier = d.pkyCompany and 
c.codCurrency = e.pkyCurrency and 
c.codWarehouse = f.pkyWarehouse and 
c.sysEnabled = 1 and c.sysAuthorized = 1

union all

select c.pkyPurchaseOrder as codigo, a.fldQuantity as cantidad,
a.fldPrice as precio, a.fldDiscount as descuento, b.fldFactoryKey as cod_fabrica,
a.fldTotalNetPrice as total, b.fldName as item, 
c.fldDate as fecha, c.fldNumber as nro_doc, 
d.fldName as proveedor, c.codAccountPayable as cod_cxp, c.codAccountEntry as cod_asiento,
e.fldName as moneda, c.codCurrency as cod_moneda, 
c.codExchangeRate as cod_tc, c.codWarehouse as cod_alm, 
f.fldName as almacen, c.codSupplier as cod_pro, l.fldQuantity / l.fldStorageUnitCoefficient as cantidad_recib
from
pchPurchaseOrderDetail a, invItem b, pchPurchaseOrder c, 
agnCompany d, actCurrency e, invWarehouse f, pchReceiptOfGoods k, pchReceiptOfGoodsDetail l
where 
$valor_fecha_ini_det 
$valor_fecha_fin_det 
$valor_pro_det 
$valor_alm_det 
$valor_familia_det  
$valor_subfamilia_det 
$valor_grupo_det 
$valor_subgrupo_det 
$valor_contexto_det 
c.codStatus = 2 and 
c.pkyPurchaseOrder = k.codPurchaseOrder and 
k.pkyReceiptOfGoods = l.codReceiptOfGoods and 
a.codItem = l.codItem and 
a.codItem = b.pkyItem and 
a.codItem = '$cod_item_det' and 
a.codPurchaseOrder = c.pkyPurchaseOrder and 
c.codSupplier = d.pkyCompany and 
c.codCurrency = e.pkyCurrency and 
c.codWarehouse = f.pkyWarehouse and 
c.sysEnabled = 1 and c.sysAuthorized = 1 and 
k.sysEnabled = 1 and k.sysAuthorized = 1) t
order by t.fecha;");	
}
$matriz_det = array();
$i = 1;
		while ($row = mysqli_fetch_array($resultdet)) {
		$matriz_det[$i][0] = $row['cod_fabrica'];
		$matriz_det[$i][1] = $row['codigo'];
		$matriz_det[$i][2] = $row['nro_doc'];
		$matriz_det[$i][3] = $row['item'];
		$matriz_det[$i][4] = $row['fecha'];
		$matriz_det[$i][5] = $row['proveedor'];
		$matriz_det[$i][6] = $row['cod_cxp'];
		$matriz_det[$i][7] = $row['cantidad'];
		$matriz_det[$i][8] = $row['precio'];
		$matriz_det[$i][9] = $row['descuento'];
		$matriz_det[$i][10] = $row['total'];
		$matriz_det[$i][11] = $row['moneda'];
		$matriz_det[$i][12] = $row['cod_moneda'];
		$matriz_det[$i][13] = $row['cod_tc'];
		$matriz_det[$i][16] = $row['cod_asiento'];
		$matriz_det[$i][17] = $row['cantidad_recib'];
		$cod_tc = $matriz_det[$i][13];
		$cod_moneda_base = $matriz_det[$i][12];
		if($matriz_det[$i][12] != $otra_moneda_det) {
			//valores de conversion tipo de cambio a cada fecha de compra
			$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
			from
			actExchangeRateDetail
			where
			codExchangeRate = '$cod_tc' and
			codBaseCurrency = '$otra_moneda_det' and
			codTargetCurrency = '$cod_moneda_base' and
			sysEnabled = 1 AND sysAuthorized = 1;");
			while ($row = mysqli_fetch_array($resulttc)) {
				$matriz_det [$i][14] = $row['tc'];//valor a multiplicar del tc 
				}
				mysqli_free_result($resulttc);
		} else {
			$matriz_det[$i][14] = 1;
		}
		$matriz_det[$i][15] = $row['almacen'];
		$i++;
		}
		mysqli_free_result($resultdet);
		$fin_det = $i - 1;
?>
<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 Compras por <?php echo $nom_pro_o_alm; ?></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>Item: </b><?php echo $cod_item_det; ?> - <?php echo $matriz_det[1][0]; ?> - <?php echo $matriz_det[1][3]; ?></TD>
        <TD width="25%"><?php echo $nom_fecha_det; ?></TD>
        <TD width="25%"><b>Mostrar: </b><?php echo $nom_mostrar_det; ?></TD>
        <TD width="25%"><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
        <TR> 
        <TD><b>Familia: </b><?php echo $nom_familia_det; ?></TD>
        <TD><b>Sub Familia: </b><?php echo $nom_subfamilia_det; ?></TD>
        <TD><b>Grupo: </b><?php echo $nom_grupo_det; ?></TD>
        <TD><b>Sub Grupo: </b><?php echo $nom_subgrupo_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; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td>", 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>Nro. Doc.</b></TD>
    <TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Proveedor</b></TD>
    <TD align="center"><b>Almac&eacute;n</b></TD>
    <TD align="center"><b>CxP</b></TD>
    <TD align="center"><b>Asiento</b></TD>
    <TD align="center"><b>Cant.</b></TD>
    <TD align="center"><b>Cant. No Recib.</b></TD>
    <TD align="center"><b>Mon.</b></TD>
    <TD align="center"><b>Precio</b></TD>
    <TD align="center"><b>Desc. %</b></TD>
    <TD align="center"><b>Total</b></TD>
    <?php if($otra_moneda_det != 0){ ?>
    <TD align="center"><b>Tasa a <?php echo $nom_otra_moneda; ?></b></TD>
    <TD align="center"><b>Saldo en <?php echo $nom_otra_moneda; ?></b></TD>
    <?php } ?>
    </TR>
    </thead>
    <tbody class="marcafila">

    <?php
	$suma_total = 0;
	$suma_total_om = 0;
	$suma_cant = 0;
	$suma_cant_no_recib = 0;
	$suma_precio = 0;
	$color = 2;
	for ($i = 1; $i <= $fin_det; $i++) { //for
		$codigo_oc = $matriz_det[$i][1];
		$codigo = $matriz_det[$i][6];
		$codigo_asiento = $matriz_det[$i][16];
		if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModulePurchases/VoucherPurchaseOrder/index.php?pkyPurchaseOrder=$codigo_oc&user=$usuario_det&token=$token' title='Nota de Orden de Compra'>%s</a></td>", $matriz_det[$i][1]);//cod
		} else {
		printf("<tr><td align='center'><a href='../../ModulePurchases/VoucherPurchaseOrder/index.php?pkyPurchaseOrder=$codigo_oc&user=$usuario_det&token=$token' title='Nota de Orden de Compra'>%s</a></td>", $matriz_det[$i][1]);//cod
		}//fin if color
		printf("<td align='center'>%s</td>", $matriz_det[$i][2]);//numero documento
		printf("<td align='right'>%s</td>", $matriz_det[$i][4]);//fecha
		printf("<td>%s</td>", $matriz_det[$i][3]);//item
		printf("<td>%s</td>", $matriz_det[$i][5]);//proveedor
		printf("<td>%s</td>", $matriz_det[$i][15]);//almacen
		/*
		if($otra_moneda_det != 0){
		printf("<td align='right'><a href='../../ModulePayments/ReportAccountsPayable/report.php?rep=5&tipo=2&cod_cxp=$codigo&empresa=1&otra_moneda_det=$otra_moneda_det&usuario_det=$usuario_det&token=$token' title='Kardex de Cuenta por Pagar'>%s</a></td>", $matriz_det[$i][6]);//cxp
		} else {
		printf("<td align='right'><a href='../../ModulePayments/ReportAccountsPayable/report.php?rep=5&tipo=2&cod_cxp=$codigo&empresa=1&otra_moneda_det=0&usuario_det=$usuario_det&token=$token' title='Kardex de Cuenta por Pagar'>%s</a></td>", $matriz_det[$i][6]);//cxp
		}
		*/
		printf("<td align='right'><a href='../../ModulePayments/VoucherAccountsPayable/index.php?pkyAccountsPayable=$codigo&user=$usuario_det&token=$token' title='Nota de Cuenta por Pagar'>%s</a></td>", $matriz_det[$i][6]);//cxp
		printf("<td align='right'><a href='../../ModuleAccounting/VoucherAccountEntry/index.php?pkyAccountEntry=$codigo_asiento&showCC=$asientocc_det&user=$usuario_det&token=$token' title='Asiento Contable'>%s</a></td>", $matriz_det[$i][16]);//asiento
		printf("<td align='right'>%s</td>", number_format($matriz_det[$i][7],$n_cantidad));//cantidad
		printf("<td align='right'>%s</td>", number_format($matriz_det[$i][7] - $matriz_det[$i][17],$n_cantidad));//cantidad no recibida
		printf("<td>%s</td>", $matriz_det[$i][11]);//moneda
		printf("<td align='right'>%s</td>", number_format($matriz_det[$i][8],$n_decimales));//precio
		printf("<td align='right'>%s</td>", number_format($matriz_det[$i][9], $n_descuento));//descuento
				
		if($otra_moneda_det != 0){ //if otra moneda
			printf("<td align='right'>%s</td>", number_format($matriz_det[$i][10], $n_decimales));//total
			printf("<td align='right'>%s</td>", number_format($matriz_det[$i][14], $n_tipocambio));//tasa
			printf("<td align='right'>%s</td></tr>", number_format($matriz_det[$i][10] * $matriz_det[$i][14], $n_decimales));//total otra moneda
			}//fin if otra moneda 
			else { //else otra moneda
		 	printf("<td align='right'>%s</td></tr>", number_format($matriz_det[$i][10], $n_decimales));//total
		 }//fin if otra moneda
		 $suma_total = $suma_total + $matriz_det[$i][10];
		 $suma_total_om = $suma_total_om + $matriz_det[$i][10] * $matriz_det[$i][14];
		 $suma_cant = $suma_cant + $matriz_det[$i][7];
		 $suma_cant_no_recib = $suma_cant_no_recib + $matriz_det[$i][7] - $matriz_det[$i][17];
		 $suma_precio = $suma_precio + $matriz_det[$i][8];
		 $color++;
		}//fin for

if($otra_moneda_det != 0){ ?>
<tr BGCOLOR='#ffcccc'><td colspan="8"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_no_recib,$n_cantidad)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_total,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_om,$n_decimales)); ?></td></tr>
<?php } else { ?>
<tr BGCOLOR='#ffcccc'><td colspan="8"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_no_recib,$n_cantidad)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_total,$n_decimales)); ?></td>
</tr>
<?php } ?>

<tr BGCOLOR='#ffcccc'><td colspan="8"><b>Promedio</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant/$fin_det,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant_no_recib/$fin_det,$n_cantidad)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_precio/$fin_det,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_total/$fin_det,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_om/$fin_det,$n_decimales)); ?></td></tr>	
<?php
} //fin if 3
?>
</tbody>
</table>

</body>
</html>
