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

</head>
<?php
include "../../conn.php";
include "../../general.php";
$rep=$_GET["rep"];
$tipo=$_GET["tipo"];
$familia=$_POST["familia"];
$subfamilia=$_POST["subfamilia"];
$grupo=$_POST["grupo"];
$subgrupo=$_POST["subgrupo"];
$itemini=$_POST["itemini"];
$itemfin=$_POST["itemfin"];
$orden=$_POST["orden"];
$fechaini=$_POST["fechaini"];
$fechafin=$_POST["fechafin"];
$otra_moneda=$_POST["otra_moneda"];
$almacen=$_POST["almacen"];
$cuenta_almacen=$_POST["cuenta_almacen"];
$empresa=$_POST["empresa"];
$concepto=$_POST["concepto"];
$cod_contexto=$_POST["contexto"];
$mostrar=$_POST["mostrar"];
$mostrar_lotes=$_POST["mostrar_lotes"];
$mostrar_cant=$_POST["mostrar_cant"];
$mostrar_saldo_cero=$_POST["mostrar_saldo_cero"];
$mostrar_todo_alm=$_POST["mostrar_todo_alm"];
$agrupar_items=$_POST["agrupar_items"];
$num_doc=$_POST["num_doc"]; //se controla solo desde if agrupar items 3
$lista_precio=$_POST["lista_precio"];
$usuario=$_POST["usuario"];

$codfab_ver=$_POST["codfab_ver"];
$familia_ver=$_POST["familia_ver"];
$subfamilia_ver=$_POST["subfamilia_ver"];
$grupo_ver=$_POST["grupo_ver"];
$subgrupo_ver=$_POST["subgrupo_ver"];
$tipo_ver=$_POST["tipo_ver"];
$umen_ver=$_POST["umen_ver"];
$glosa_ver=$_POST["glosa_ver"];
$empresa_ver=$_POST["empresa_ver"];


$fechainidet=$_GET["fechainidet"];
$fechafindet=$_GET["fechafindet"];
$totalcantdet=$_GET["totalcantdet"];
$totalcostodet=$_GET["totalcostodet"];
$itemdet=$_GET["itemdet"];
$otra_monedadet=$_GET["otra_monedadet"];
$usuario_det=$_GET["usuario_det"];
$almacen_det=$_GET["almacen_det"];
$cuenta_almacen_det=$_GET["cuenta_almacen_det"];
$empresa_det=$_GET["empresa_det"];
$concepto_det=$_GET["concepto_det"];
$cod_contexto_det=$_GET["contexto_det"];
$mostrar_cant_det=$_GET["mostrar_cant_det"];
$mostrar_lotes_det=$_GET["mostrar_lotes_det"];
$glosa_ver_det=$_GET["glosa_ver_det"];
$empresa_ver_det=$_GET["empresa_ver_det"];
$cod_tipo_det=$_GET["cod_tipo_det"];

//envio de $agrupar_items >= 2 para mostrar el mismo reporte con la familia
$familia_rev=$_GET["familia_rev"];
$orden_rev=$_GET["orden_rev"];
$fechaini_rev=$_GET["fechaini_rev"];
$fechafin_rev=$_GET["fechafin_rev"];
$otra_moneda_rev=$_GET["otra_moneda_rev"];
$almacen_rev=$_GET["almacen_rev"];
$cuenta_almacen_rev=$_GET["cuenta_almacen_rev"];
$empresa_rev=$_GET["empresa_rev"];
$concepto_rev=$_GET["concepto_rev"];
$cod_contexto_rev=$_GET["contexto_rev"];
$mostrar_rev=$_GET["mostrar_rev"];
$mostrar_cant_rev=$_GET["mostrar_cant_rev"];
$mostrar_saldo_cero_rev=$_GET["mostrar_saldo_cero_rev"];
$mostrar_lotes_rev=$_GET["mostrar_lotes_rev"];
$mostrar_todo_alm_rev=$_GET["mostrar_todo_alm_rev"];
$agrupar_items_rev=$_GET["agrupar_items_rev"];
$usuario_rev=$_GET["usuario_rev"];

$codfab_ver_rev=$_GET["codfab_ver_rev"];
$familia_ver_rev=$_GET["familia_ver_rev"];
$subfamilia_ver_rev=$_GET["subfamilia_ver_rev"];
$grupo_ver_rev=$_GET["grupo_ver_rev"];
$subgrupo_ver_rev=$_GET["subgrupo_ver_rev"];
$tipo_ver_rev=$_GET["tipo_ver_rev"];
$umen_ver_rev=$_GET["umen_ver_rev"];

if($familia_rev != NULL) { $familia = $familia_rev; }
if($orden_rev != NULL) { $orden = $orden_rev; }
if($fechaini_rev != NULL) { $fechaini = $fechaini_rev; }
if($fechafin_rev != NULL) { $fechafin = $fechafin_rev; }
if($otra_moneda_rev != NULL) { $otra_moneda = $otra_moneda_rev; }
if($almacen_rev != NULL) { $almacen = $almacen_rev; }
if($empresa_rev != NULL) { $empresa = $empresa_rev; }
if($cuenta_empresa_rev != NULL) { $cuenta_empresa = $cuenta_empresa_rev; }
if($concepto_rev != NULL) { $concepto = $concepto_rev; }
if($cod_contexto_rev != NULL) { $cod_contexto = $cod_contexto_rev; }
if($mostrar_rev != NULL) { $mostrar = $mostrar_rev; }
if($mostrar_cant_rev != NULL) { $mostrar_cant = $mostrar_cant_rev; }
if($mostrar_saldo_cero_rev != NULL) { $mostrar_saldo_cero = $mostrar_saldo_cero_rev; }
if($mostrar_lotes_rev != NULL) { $mostrar_lotes = $mostrar_lotes_rev; }
if($mostrar_todo_alm_rev != NULL) { $mostrar_todo_alm = $mostrar_todo_alm_rev; }
if($agrupar_items_rev != NULL) { $agrupar_items = $agrupar_items_rev; }
if($usuario_rev != NULL) { $usuario = $usuario_rev; }

if($codfab_ver_rev != NULL) { $codfab_ver = $codfab_ver_rev; }
if($familia_ver_rev != NULL) { $familia_ver = $familia_ver_rev; }
if($subfamilia_ver_rev != NULL) { $subfamilia_ver = $subfamilia_ver_rev; }
if($grupo_ver_rev != NULL) { $grupo_ver = $grupo_ver_rev; }
if($subgrupo_ver_rev != NULL) { $subgrupo_ver = $subgrupo_ver_rev; }
if($tipo_ver_rev != NULL) { $tipo_ver = $tipo_ver_rev; }
if($umen_ver_rev != NULL) { $umen_ver = $umen_ver_rev; }



$nro_col = 2;

?>
<body>
<?php
if($familia == '') { $familia = 0;}
if($subfamilia == '') { $subfamilia = 0;}
if($grupo == '') { $grupo = 0;}
if($subgrupo == '') { $subgrupo = 0;}


//si mostrar es 0 no tomar en cuenta las familias y si es 1 no tomar los items
if($mostrar == 0) {
	$familia = 0;
	$subfamilia = 0;
	$grupo = 0;
	$subgrupo = 0;
	$nom_mostrar = 'Rango de Items';
} else {
	$itemini = 0;
	$itemfin = 0;
	$nom_mostrar = 'Familia';
}

//si se elige una cuenta contable entonces se muestran los items en cada almacén, no se puede consolidado por los costos en los traspasos
if($cuenta_almacen != 0){
	$mostrar_todo_alm = 1;
} 

//si mostrar cantidad es 0 ver todas las columnas
if($mostrar_cant == 0) {
	$nom_mostrar_cant = 'No';
} else {
	$nom_mostrar_cant = 'Si';
}

//lotes
if($mostrar_lotes == 0) {
	$nom_mostrar_lotes = 'No';
} else {
	$nom_mostrar_lotes = 'Si';
}

//mostrar saldo cero
if($mostrar_saldo_cero == 0) {
	$nom_mostrar_saldo_cero = 'Si';
} else {
	$nom_mostrar_saldo_cero = 'No';
}

//si mostrar por almacen es 1 ver todos los almacenes en la misma hoja (barre las veces que almacenes existan)
if($mostrar_todo_alm == 1) {//if mostrar todo 1
	//listado de almacenes si eligen ademas un almacen
	if($almacen == 0) {//if alm 0
		$resultalm = mysqli_query($link, "select pkyWarehouse, fldName 
		from invWarehouse 
		where sysEnabled = 1 and sysAuthorized = 1;");
		$mat_alm = array();
		$ma = 1;
		while ($row = mysqli_fetch_array($resultalm)) { 
		$mat_alm[$ma][1] = $row['pkyWarehouse'];
		$mat_alm[$ma][2] = $row['fldName'];
		$ma++;
		}
		$fin_mat = $ma - 1;
		mysqli_free_result($resultalm);
	} else {//else if alm 0
		$resultalm = mysqli_query($link, "select pkyWarehouse, fldName 
		from invWarehouse 
		where 
		pkyWarehouse = '$almacen' and 
		sysEnabled = 1 and sysAuthorized = 1;");
		$mat_alm = array();
		$ma = 1;
		while ($row = mysqli_fetch_array($resultalm)) { 
		$mat_alm[$ma][1] = $row['pkyWarehouse'];
		$mat_alm[$ma][2] = $row['fldName'];
		$ma++;
		}
		$fin_mat = $ma - 1;
		mysqli_free_result($resultalm);
	}//fin if alm 0
} else {//else if mostrar todo 1
	$fin_mat = 1;	
}//fin if mostrar todo 1

//si agrupar items es 0 muestra en detalle todos los items
if($agrupar_items == 0) {
	$nom_agrupar_items = 'No (Tipo Kardex)';
} 
if($agrupar_items == 1) {
	$nom_agrupar_items = 'Si (Por Item)';
}
if($agrupar_items == 2) {
	$nom_agrupar_items = 'Si (Por Familia)';
}
if($agrupar_items == 3) {
	$nom_agrupar_items = 'Si (Por Sub Familia)';
}
if($agrupar_items == 4) {
	$nom_agrupar_items = 'Si (Por Grupo)';
}
if($agrupar_items == 5) {
	$nom_agrupar_items = 'Si (Por Sub Grupo)';
}

//valor del codigo del ultimo tipo de cambio
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafin' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc = $row['tc'];
	}
	mysqli_free_result($resultom);

//tipo de cambio para la cabecera
$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc' and 
sysEnabled = 1 and sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

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

if($otra_moneda != 0){ //if otra moneda

//moneda
$result0 = mysqli_query($link, "select a.pkyCurrency as codigo, a.fldName as moneda
from actCurrency a, invInventoryConfig b
where
a.pkyCurrency = b.codCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($result0)) {
	$nom_moneda = $row['moneda'];
	$cod_moneda = $row['codigo'];
	}
	mysqli_free_result($result0);

//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);


//valor del codigo del ultimo tipo de cambio
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafin' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc = $row['tc'];
	}
	mysqli_free_result($resultom);

if($cod_moneda > $otra_moneda) {//if original > otra 
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc' and
codBaseCurrency = '$otra_moneda' and
codTargetCurrency = '$cod_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resulttc)) {
	$codigo_tc = $row['codigotc'];
	$moneda_base = $row['monedabase'];
	$moneda_cambio = $row['monedacambio'];
	$tasa_tc = $row['tc'];
	//$tasa_tc_valor = $tasa_tc;
	}
	mysqli_free_result($resulttc);
} else {//else if original > otra 
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc' and
codBaseCurrency = '$cod_moneda' and
codTargetCurrency = '$otra_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resulttc)) {
	$codigo_tc = $row['codigotc'];
	$moneda_base = $row['monedabase'];
	$moneda_cambio = $row['monedacambio'];
	$tasa_tc = $row['tc'];
	//$tasa_tc_valor = $tasa_tc;
	$tasa_tc = 1 / $tasa_tc;
	}
	mysqli_free_result($resulttc);	
}//fin if original > otra 


}//fin if otra moneda 

if($otra_moneda != 0){
	$texto_otra_moneda = $nom_otra_moneda;
} else{
	$texto_otra_moneda = 'Moneda original';
	//$tasa_tc = 1;
}

$suma_total_cant_salini2 = 0;
$suma_total_costo_salini2 = 0;
$suma_total_cant_ing2 = 0;
$suma_total_costo_ing2 = 0;
$suma_total_cant_egr2 = 0;
$suma_total_costo_egr2 = 0;
$suma_total_trasp2 = 0;
$suma_total_costo_extra_trasp2 = 0;
$suma_total_trasp_ing2 = 0;
$suma_total_trasp_egr2 = 0;
$suma_total_cant_periodo2 = 0;
$suma_total_costo_periodo2 = 0;
$suma_total_cant2 = 0;
$suma_total_costo2 = 0;
$suma_total_otra_moneda2 = 0; 


//Inicio reporte inventario valorado
//Inicio muestra todos los items
if($rep == 9 && $tipo == 1) { // if 2
	//para que en el nombre sea todos cuando $mostrar_todo_alm == 1
	if($almacen == 0) { $var_alm = 0; } else { $var_alm = 1; }
 
	//agrupar por item
	if($agrupar_items == 1) { //if agrupar items 1
	
		for($ma = 1; $ma <= $fin_mat; $ma++) { //for repite almacen
		
			if($mostrar_todo_alm == 1) {//if 12
				$almacen = $mat_alm[$ma][1];
				$nom_mostrar_todo_alm = 'Si (Items en cada almacen)';
			} else { 
				$nom_mostrar_todo_alm = 'No (Consolidado) ';
			}//fin if 12
			
			if ($itemini == 0) { // if 2.0
					$nom_item_ini = 'Todos';
					$valor_item_ini = ' ';
					$nom_item_fin = 'Todos';
					$valor_item_fin = ' ';
				} else {
					//nombre item
					$result2 = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
											from
											invItem 
											where
											pkyItem = '$itemini' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_item_ini = $itemini.' - '.$row['cod_fabrica'].' - '.$row['item'];
					}
					mysqli_free_result($result2);
					$valor_item_ini = ' d.pkyItem >= ' .$itemini. ' and ';
				} //fin if 2.0
				
				if ($itemfin == 0) { // if 2.1
					$nom_item_fin = 'Todos';
					$valor_item_fin = ' ';
				} else {
					//nombre item
					$result2 = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
											from
											invItem 
											where
											pkyItem = '$itemfin' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_item_fin = $itemfin.' - '.$row['cod_fabrica'].' - '.$row['item'];
					}
					mysqli_free_result($result2);
					$valor_item_fin = ' d.pkyItem <= ' .$itemfin. ' and ';
				} //fin if 2.1
				
				if ($familia == 0) { // if 2.2
					$nom_familia = 'Todos';
					$valor_familia = ' ';
				} else {
					//nombre familia
					$result3 = 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($result3)) {
						$nom_familia = $row['nombre'];
					}
					mysqli_free_result($result3);
					$valor_familia = ' d.codFamily = ' .$familia. ' and ';
				} //fin if 2.2
				
				if ($subfamilia == 0) { // if 2.3
					$nom_subfamilia = 'Todos';
					$valor_subfamilia = ' ';
				} else {
					//nombre sub familia
					$result4 = 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($result4)) {
						$nom_subfamilia = $row['nombre'];
					}
					mysqli_free_result($result4);
					$valor_subfamilia = ' d.codSubFamily = ' .$subfamilia. ' and ';
				} //fin if 2.3
				
				if ($grupo == 0) { // if 2.4
					$nom_grupo = 'Todos';
					$valor_grupo = ' ';
				} else {
					//nombre grupo
					$result5 = 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($result5)) {
						$nom_grupo = $row['nombre'];
					}
					mysqli_free_result($result5);
					$valor_grupo = ' d.codGroup = ' .$grupo. ' and ';
				} //fin if 2.4
				
				if ($subgrupo == 0) { // if 2.5
					$nom_subgrupo = 'Todos';
					$valor_subgrupo = ' ';
				} else {
					//nombre sub grupo
					$result6 = 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($result6)) {
						$nom_subgrupo = $row['nombre'];
					}
					mysqli_free_result($result6);
					$valor_subgrupo = ' d.codSubGroup = ' .$subgrupo. ' and ';
				} //fin if 2.5
				
				if ($orden == 0) { 
					$nom_orden = 'Item (Nombre)';
					$valor_orden = ' order by d.fldName ';
					$valor_orden2 = ' order by item, fecha, cod_det ';
				}
				if ($orden == 1) {
					$nom_orden = 'Item (C&oacute;digo)';
					$valor_orden = ' order by d.pkyItem ';
					$valor_orden2 = ' order by codigo, fecha, cod_det ';
				} 
				if ($orden == 2) {
					$nom_orden = 'Item (C&oacute;digo de F&aacute;brica)';
					$valor_orden = ' order by d.fldFactoryKey ';
					$valor_orden2 = ' order by cod_fabrica, fecha, cod_det ';
				} 
				if ($orden == 3) {
					$nom_orden = 'Familia (C&oacute;digo)';
					$valor_orden = ' order by d.codFamily, d.codSubFamily, d.codGroup, d.codSubGroup, d.pkyItem ';
					$valor_orden2 = ' order by cod_familia, cod_subfamilia, cod_grupo, cod_subgrupo, fecha, cod_det ';
				} 
			/*  
				if ($item == 0) { // if 2.2
					$nom_orden = 'Item';
					$nom_item = 'Todos';
					$cod_item1 = ' ';
					$cod_item2 = ' ';
				} else {
					$nom_orden = 'Item';
					$cod_item1 = ' a.pkyItem = ' .$item. ' and ';
					$cod_item2 = ' a.codItem = ' .$item. ' and ';
				} //fin if 2.2
			*/	
				if ($almacen == 0) { // if 2.3
					//$nom_orden = Item;
					$nom_almacen = 'Todos';
					$valor_almacen1 = ' ';
					$valor_almacen2 = ' ';
				} else {
					//$nom_orden = Item;
					$valor_almacen1 = ' b.codTargetWarehouse = ' .$almacen. ' and ';
					$valor_almacen2 = ' b.codSourceWarehouse = ' .$almacen. ' and ';
					//nombre de almacen
					$result2 = mysqli_query($link, "select pkyWarehouse, fldName 
											from invWarehouse 
											where 
											pkyWarehouse = '$almacen' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_almacen = $row['fldName'];
					}
					mysqli_free_result($result2);
				} //fin if 2.3

				if ($cuenta_almacen == 0) { // if 2.3.1
					$nom_cuenta_almacen = 'Todos';
					$valor_cuenta_almacen = ' ';
					//$valor_cuenta_almacen2 = ' ';
				} else {
					$valor_cuenta_almacen = ' e.codAccount = ' .$cuenta_almacen. ' and ';
					//$valor_cuenta_almacen2 = ' e.codAccount = ' .$cuenta_almacen. ' and ';
					//nombre de la cuenta contable del almacen
					$result2 = mysqli_query($link, "select pkyAccount, fldName 
											from actAccount 
											where 
											pkyAccount = '$cuenta_almacen' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_cuenta_almacen = $row['fldName'];
					}
					mysqli_free_result($result2);
				} //fin if 2.3.1
				
				if ($empresa == 0) { // if 2.3.2
					$nom_empresa = 'Todos';
					$valor_empresa = ' ';
				} else {
					//nombre concepto
					$result2 = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
								from agnCompany
								where
								pkyCompany = '$empresa';");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_empresa = $row['codigo'].' - '.$row['empresa'];
					}
					mysqli_free_result($result2);
					$valor_empresa = ' b.codSupplier = ' .$empresa. ' and ';
				} //fin if 2.3.2

				if ($concepto == 0) { // if 2.4
					$nom_concepto = 'Todos';
					$valor_concepto = ' ';
				} else {
					//nombre concepto
					$result2 = mysqli_query($link, "select a.pkyItemMovementTypeConcept as cod_concepto, a.fldName as concepto, b.fldName as tipo
								from invItemMovementTypeConcept a, invItemMovementType b 
								where 
								a.pkyItemMovementTypeConcept = '$concepto' and
								a.codItemMovementType = b.pkyItemMovementType;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_concepto = $row['concepto'].' - '.$row['tipo'];
					}
					mysqli_free_result($result2);
					$valor_concepto = ' b.codTypeConcept = ' .$concepto. ' and ';
				} //fin if 2.4
				
				if ($lista_precio == NULL) { // if 2.5
					$nom_lista_precio = 'Sin lista';
				} else {
					//nombre lista
					$result2 = mysqli_query($link, "select a.pkyPriceList as cod_lista, a.fldName as lista, b.fldName as moneda
								from 
								slsPriceList a, actCurrency b
								where
								a.codCurrency = b.pkyCurrency and 
								a.pkyPriceList = '$lista_precio';");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_lista_precio = $row['cod_lista'].' - '.$row['lista'].' ('.$row['moneda'].')';
					}
					mysqli_free_result($result2);
				} //fin if 2.5
					
				//moneda
				$result0 = mysqli_query($link, "select a.pkyCurrency as codigo, a.fldName as moneda
				from actCurrency a, invInventoryConfig b
				where
				a.pkyCurrency = b.codCurrency and
				a.sysEnabled = 1 and a.sysAuthorized = 1;");
					
				while ($row = mysqli_fetch_array($result0)) {
				$nom_moneda = $row['moneda'];
				$cod_moneda = $row['codigo'];
				}
				mysqli_free_result($result0);
				
				//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 = ' b.sysContext = '.$cod_contexto.' and ';	
				}

					//listado de items
					$result = mysqli_query($link, "select d.pkyItem as codigo, d.fldName as item, b.fldName as tipo, c.fldName as unidad, d.codFamily as cod_familia, d.codSubFamily as cod_subfamilia, d.codGroup as cod_grupo, d.codSubGroup as cod_subgrupo, d.fldFactoryKey as cod_fabrica
					from invItem d, invItemType b, invStorageUnit c
					where
					$valor_item_ini 
					$valor_item_fin 
					$valor_familia 
					$valor_subfamilia 
					$valor_grupo 
					$valor_subgrupo 
					d.codType = b.pkyItemType and
					d.codMinimumStorageUnit = c.pkyStorageUnit and
					d.sysEnabled = 1 and d.sysAuthorized = 1
					$valor_orden;");
					
							
					//inicio calculo saldo inicial
					//ingresos
					$result2 = mysqli_query($link, "select fin.codigo as codigo, sum(fin.cant_ing) as cant_ing, sum(fin.costo) as costo
					from(
					select t.codigo as codigo, t.cant_ing as cant_ing, t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, t.costo as costopre, tc.fldRate as tasa, t.costo * tc.fldRate as costo
					from(
					select a.codItem as codigo, sum(a.fldQuantity) as cant_ing, b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc, sum(a.fldTotaCost) as costo, b.codSupplier as cod_cli
					from
					invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e
					where 
					$valor_item_ini 
					$valor_item_fin  
					$valor_familia 
					$valor_subfamilia 
					$valor_grupo 
					$valor_subgrupo 
					$valor_almacen1 
					$valor_cuenta_almacen 
					$valor_empresa 
					$valor_concepto 
					$valor_contexto 
					a.codItem = d.pkyItem and 
					b.fldDate < '$fechaini' and
					a.codItemMovement = b.pkyItemMovement and
					b.codType = c.pkyItemMovementType and
					b.codType = 1 and 
					b.codTargetWarehouse = e.pkyWarehouse and 
					b.sysEnabled = 1 and b.sysAuthorized = 1
					group by codigo, cod_moneda, cod_tc) t, actExchangeRateDetail tc
					where
					tc.codTargetCurrency = t.cod_moneda and
					tc.codBaseCurrency = '$cod_moneda' and
					tc.codExchangeRate = t.cod_tc
					union all
					select t.codigo as codigo, t.cant_ing as cant_ing, t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, t.costo as costopre, 1 as tasa, 
					t.costo as costo
					from(
					select a.codItem as codigo, sum(a.fldQuantity) as cant_ing, b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
					sum(a.fldTotaCost) as costo
					from
					invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
					where 
					$valor_item_ini 
					$valor_item_fin  
					$valor_familia 
					$valor_subfamilia 
					$valor_grupo 
					$valor_subgrupo 
					$valor_almacen1 
					$valor_cuenta_almacen 
					$valor_empresa 
					$valor_concepto 
					$valor_contexto 
					a.codItem = d.pkyItem and  
					b.fldDate < '$fechaini' and
					a.codItemMovement = b.pkyItemMovement and
					b.codType = c.pkyItemMovementType and
					b.codType = 1 and 
					b.codTargetWarehouse = e.pkyWarehouse and 
					b.sysEnabled = 1 and b.sysAuthorized = 1
					group by codigo, cod_moneda, cod_tc) t
					where
					t.cod_moneda = '$cod_moneda') fin
					group by fin.codigo;");
					
					//egresos
					$result3 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_egr, sum(a.fldTotaCost) as costo
					from
					invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
					where 
					$valor_item_ini 
					$valor_item_fin  
					$valor_familia 
					$valor_subfamilia 
					$valor_grupo 
					$valor_subgrupo 
					$valor_almacen2 
					$valor_cuenta_almacen 
					$valor_empresa 
					$valor_concepto 
					$valor_contexto 
					a.codItem = d.pkyItem and 
					b.fldDate < '$fechaini' and
					a.codItemMovement = b.pkyItemMovement and
					b.codType = c.pkyItemMovementType and
					b.codType = 2 and 
					b.codSourceWarehouse = e.pkyWarehouse and 
					b.sysEnabled = 1 and b.sysAuthorized = 1
					group by a.codItem;");
					
					//traspasos
					$result44 = mysqli_query($link, "select a.codItem as codigo, count(1) as nro_traspasos, sum(a.fldExtraCost) as costo_extra
					from
					invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d
					where 
					$valor_item_ini 
					$valor_item_fin  
					$valor_familia 
					$valor_subfamilia 
					$valor_grupo 
					$valor_subgrupo 
					$valor_empresa 
					$valor_concepto 
					$valor_contexto 
					a.codItem = d.pkyItem and  
					b.fldDate < '$fechaini' and
					a.codItemMovement = b.pkyItemMovement and
					b.codType = c.pkyItemMovementType and
					b.codType = 3 and
					b.sysEnabled = 1 and b.sysAuthorized = 1
					group by a.codItem;");
					
				if ($almacen != 0) { //if almacen
					//traspasos egresos
					$result4 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost - a.fldExtraCost) as costo
					from
					invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
					where
					$valor_item_ini 
					$valor_item_fin 
					$valor_familia 
					$valor_subfamilia 
					$valor_grupo 
					$valor_subgrupo 
					$valor_empresa 
					$valor_cuenta_almacen 
					$valor_concepto 
					$valor_contexto 
					a.codItem = d.pkyItem and 
					b.codSourceWarehouse = '$almacen' and
					b.fldDate < '$fechaini' and
					a.codItemMovement = b.pkyItemMovement and
					b.codType = c.pkyItemMovementType and
					b.codType = 3 and 
					b.codSourceWarehouse = e.pkyWarehouse and 
					a.sysEnabled = 1 and a.sysAuthorized = 1
					group by a.codItem;");
					//traspasos ingresos
					$result5 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost) as costo
					from
					invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
					where
					$valor_item_ini 
					$valor_item_fin 
					$valor_familia 
					$valor_subfamilia 
					$valor_grupo 
					$valor_subgrupo 
					$valor_empresa 
					$valor_cuenta_almacen 
					$valor_concepto 
					$valor_contexto 
					a.codItem = d.pkyItem and  
					b.codTargetWarehouse = '$almacen' and
					b.fldDate < '$fechaini' and
					a.codItemMovement = b.pkyItemMovement and
					b.codType = c.pkyItemMovementType and
					b.codType = 3 and 
					b.codTargetWarehouse = e.pkyWarehouse and 
					a.sysEnabled = 1 and a.sysAuthorized = 1
					group by a.codItem;");
				}//fin if almacen

			$matriz_salini = array();
			$i = 1;
			while ($row = mysqli_fetch_array($result)) {
				$matriz_salini [$i][0] = $row['cod_fabrica'];
				$matriz_salini [$i][1] = $row['codigo'];
				$matriz_salini [$i][2] = $row['item'];
				$matriz_salini [$i][3] = $row['tipo'];
				$matriz_salini [$i][4] = $row['unidad'];
				$i++;
			}
			$fin = $i - 1;
			mysqli_free_result($result);

			// nombre del item
			if($item != 0) { $nom_item = $matriz_salini [1][2]; }

			//ingresos
			while ($row = mysqli_fetch_array($result2)) {
				$i = 1;
				$cod_item = $row['codigo'];
				while ($cod_item <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][5] = $row['cant_ing'];
				$matriz_salini [$i][6] = $row['costo'];
			}
			mysqli_free_result($result2);
			//egresos
			while ($row = mysqli_fetch_array($result3)) {
				$i = 1;
				$cod_item = $row['codigo'];
				while ($cod_item <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][7] = $row['cant_egr'];
				$matriz_salini [$i][8] = $row['costo'];
			}
			mysqli_free_result($result3);

			//traspasos
			while ($row = mysqli_fetch_array($result44)) {
				$i = 1;
				$cod_item = $row['codigo'];
				while ($cod_item <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][29] = $row['costo_extra'];
			}
			mysqli_free_result($result44);

			if ($almacen != 0) {//if almacen 2
				//traspasos egresos
				while ($row = mysqli_fetch_array($result4)) {
					$i = 1;
					$cod_item = $row['codigo'];
					while ($cod_item <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][20] = $row['cant_tras'];
					$matriz_salini [$i][21] = $row['costo'];
				}
				mysqli_free_result($result4);
				
				//traspasos ingresos
				while ($row = mysqli_fetch_array($result5)) {
					$i = 1;
					$cod_item = $row['codigo'];
					while ($cod_item <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][22] = $row['cant_tras'];
					$matriz_salini [$i][23] = $row['costo'];
				}
				mysqli_free_result($result5);
			}//fin if almacen 2

			$i = 1;
			while($i <= $fin) {
				$cantidad_ing = $matriz_salini [$i][5];
				$costo_ing = $matriz_salini [$i][6];
				$cantidad_egr = $matriz_salini [$i][7];
				$costo_egr = $matriz_salini [$i][8];
				$costo_extra_trasp = $matriz_salini [$i][29];
				if ($almacen == 0) {//if almacen 3
					$matriz_salini [$i][9] = $cantidad_ing - $cantidad_egr; //cantidad saldo inicial
					$matriz_salini [$i][10] = $costo_ing - $costo_egr + $costo_extra_trasp; //costo saldo inicial
				} else { 
					$matriz_salini [$i][9] = $cantidad_ing - $cantidad_egr + $matriz_salini [$i][22] - $matriz_salini [$i][20]; //cantidad saldo inicial
					$matriz_salini [$i][10] = $costo_ing - $costo_egr + $matriz_salini [$i][23] - $matriz_salini [$i][21]; //costo saldo inicial
				} //fin almacen 3
				$i++;
			}

			//fin calculo saldo inicial


			//inicio calculo periodo


					//ingresos
					$result2 = mysqli_query($link, "select fin.codigo as codigo, sum(fin.cant_ing) as cant_ing, 
			sum(fin.costo) as costo
			from(
			select t.codigo as codigo, t.cant_ing as cant_ing,
			t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
			t.costo as costopre, tc.fldRate as tasa, 
			t.costo * tc.fldRate as costo
			from(
			select a.codItem as codigo, sum(a.fldQuantity) as cant_ing, 
			b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where 
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen1 
			$valor_cuenta_almacen
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 1 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by codigo, cod_moneda, cod_tc) t, actExchangeRateDetail tc
			where
			tc.codTargetCurrency = t.cod_moneda and
			tc.codBaseCurrency = '$cod_moneda' and
			tc.codExchangeRate = t.cod_tc
			union all
			select t.codigo as codigo, t.cant_ing as cant_ing,
			t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
			t.costo as costopre, 1 as tasa, 
			t.costo as costo
			from(
			select a.codItem as codigo, sum(a.fldQuantity) as cant_ing, 
			b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where 
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen1 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 1 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by codigo, cod_moneda, cod_tc) t
			where
			t.cod_moneda = '$cod_moneda') fin
			group by fin.codigo;");
					//egresos
					$result3 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_egr, 
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where 
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen2 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 2 and 
			b.codSourceWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by a.codItem;");
					//traspasos
					$result4 = mysqli_query($link, "select a.codItem as codigo, count(1) as nro_traspasos, sum(a.fldExtraCost) as costo_extra
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d  
			where 
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by a.codItem;");

			if ($almacen != 0) { //if almacen
					//traspasos egresos
					$result5 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost - a.fldExtraCost) as costo, sum(a.fldExtraCost) as costo_extra
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_cuenta_almacen 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and   
			b.codSourceWarehouse = '$almacen' and
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and 
			b.codSourceWarehouse = e.pkyWarehouse and 
			a.sysEnabled = 1 and a.sysAuthorized = 1
			group by a.codItem;");
					//traspasos ingresos
					$result6 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost) as costo, sum(a.fldExtraCost) as costo_extra
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_cuenta_almacen 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and 
			b.codTargetWarehouse = '$almacen' and
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			a.sysEnabled = 1 and a.sysAuthorized = 1
			group by a.codItem;");
				}//fin if almacen

			//ingresos
			while ($row = mysqli_fetch_array($result2)) {
				$i = 1;
				$cod_item = $row['codigo'];
				while ($cod_item <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][11] = $row['cant_ing'];
				$matriz_salini [$i][12] = $row['costo'];
			}
			mysqli_free_result($result2);
			//egresos
			while ($row = mysqli_fetch_array($result3)) {
				$i = 1;
				$cod_item = $row['codigo'];
				while ($cod_item <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][13] = $row['cant_egr'];
				$matriz_salini [$i][14] = $row['costo'];
			}
			mysqli_free_result($result3);
			//traspasos
			while ($row = mysqli_fetch_array($result4)) {
				$i = 1;
				$cod_item = $row['codigo'];
				while ($cod_item <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][15] = $row['nro_traspasos'];
				$matriz_salini [$i][28] = $row['costo_extra'];
			}
			mysqli_free_result($result4);

			if ($almacen != 0) {//if almacen 2
				//traspasos egresos
				while ($row = mysqli_fetch_array($result5)) {
					$i = 1;
					$cod_item = $row['codigo'];
					while ($cod_item <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][24] = $row['cant_tras'];
					$matriz_salini [$i][25] = $row['costo'];
					$matriz_salini [$i][28] = 0;
				}
				mysqli_free_result($result5);
				
				//traspasos ingresos
				while ($row = mysqli_fetch_array($result6)) {
					$i = 1;
					$cod_item = $row['codigo'];
					while ($cod_item <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][26] = $row['cant_tras'];
					$matriz_salini [$i][27] = $row['costo'];
					$matriz_salini [$i][28] = $row['costo_extra'];
				}
				mysqli_free_result($result6);
			}//fin if almacen 2

			$i = 1;
			while($i <= $fin) {
				$cant_ing = $matriz_salini [$i][11];
				$costo_ing = $matriz_salini [$i][12];
				$cant_egr = $matriz_salini [$i][13];
				$costo_egr = $matriz_salini [$i][14];
				$costo_extra_trasp = $matriz_salini [$i][28];
				if($almacen == 0) {//if almacen 4
					$matriz_salini [$i][16] = $cant_ing - $cant_egr; //total cantidad periodo
					$matriz_salini [$i][17] = $costo_ing - $costo_egr + $costo_extra_trasp; //total costo periodo
				} else {
					$matriz_salini [$i][16] = $cant_ing - $cant_egr + $matriz_salini [$i][26] - $matriz_salini [$i][24]; //total cantidad periodo
					$matriz_salini [$i][17] = $costo_ing - $costo_egr + $matriz_salini [$i][27] - $matriz_salini [$i][25]; //total costo periodo
				}//fin if almacen 4
				$cant_salini = $matriz_salini [$i][9];
				$costo_salini = $matriz_salini [$i][10];
				$cant_periodo = $matriz_salini [$i][16];
				$costo_periodo = $matriz_salini [$i][17];
				
				$matriz_salini [$i][18] = $cant_salini + $cant_periodo; //total cantidad
				$matriz_salini [$i][19] = $costo_salini + $costo_periodo; //total costo
				$i++;
			}


				
			//fin calculo periodo
					?>
			<?php if($ma == 1) {//if 13, muestra solo una vez por la iteracion de almacenes ?>
			<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>Inventario Valorado</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 inicial: </b><?php echo $nom_item_ini; ?></TD>
					<TD width="25%"><b>Item final: </b><?php echo $nom_item_fin; ?></TD>
					<?php if($var_alm == 0) { ?>
					<TD width="25%"><b>Almac&eacute;n: </b>Todos</TD>
					<?php } else { ?>
					<TD width="25%"><b>Almac&eacute;n: </b><?php echo $nom_almacen; ?></TD>
					<?php } ?>
					<TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></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>Mostrar todos los almacenes: </b><?php echo $nom_mostrar_todo_alm; ?></TD>
					<TD><b>Lista de Precio: </b><?php echo $nom_lista_precio; ?></TD>
					<TD><b>Concepto: </b><?php echo $nom_concepto; ?></TD>
					<TD><b>Mostrar solo cantidades: </b><?php echo $nom_mostrar_cant; ?></TD>
					</TR>
					<TR>
					<TD><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
					<TD><b>Items agrupados: </b><?php echo $nom_agrupar_items; ?></TD>
					<TD><b>Mostrar por: </b><?php echo $nom_mostrar; ?></TD>
					<TD><b>Mostrar Lotes: </b><?php echo $nom_mostrar_lotes; ?></TD>
					</TR>
					<TR>
					<TD><b>Empresa: </b><?php echo $nom_empresa; ?></TD>
					<TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
					<TD><b>Mostrar saldo cero: </b><?php echo $nom_mostrar_saldo_cero; ?></TD>
					<TD><b>Cuenta Contable del Almac&eacute;n: </b><?php echo $nom_cuenta_almacen; ?></TD>
					</TR>
					<?php if($mostrar_cant == 0) { ?>
					<TR>
					<TD colspan="2"><b>Expresado en: </b><?php echo $nom_moneda; ?></TD>
					<TD colspan="2"><b>Valorado tambi&eacute;n en: </b><?php echo $texto_otra_moneda; ?></TD>
					</TR>
					<?php } ?>
					
				</table>

			</td>

			<td valign="top" width="150">

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

			</tr>
			</table>
			<br /> 
			<table border="1" align="center" cellpadding="2" width="100%">
				<thead>
				<TR> 
				<TD align="center"><b>Cod.</b></TD>
				<?php if($codfab_ver == 1) { $nro_col++; ?>
				<TD align="center"><b>Cod. Fab.</b></TD>
				<?php } ?>
				<TD align="center"><b>Item</b></TD>
				<?php if($familia_ver == 1) { $nro_col++; ?>
				<TD align="center"><b>Familia</b></TD>
				<?php } ?>
				<?php if($subfamilia_ver == 1) { $nro_col++; ?>
				<TD align="center"><b>Sub Familia</b></TD>
				<?php } ?>
				<?php if($grupo_ver == 1) { $nro_col++; ?>
				<TD align="center"><b>Grupo</b></TD>
				<?php } ?>
				<?php if($subgrupo_ver == 1) { $nro_col++; ?>
				<TD align="center"><b>Sub Grupo</b></TD>
				<?php } ?>
				<?php if($tipo_ver == 1) { $nro_col++; ?>
				<TD align="center"><b>Tipo</b></TD>
				<?php } ?>
				<?php if($umen_ver == 1) { $nro_col++; ?>
				<TD align="center"><b>Uni. Men.</b></TD>
				<?php } ?>
				<TD align="center"><b>Cant. Saldo Inicial</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Costo Saldo Inicial</b></TD>
				<?php } ?>
				<TD align="center"><b>Cant. Ingresos</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Costo Ingresos</b></TD>
				<?php } ?>
				<TD align="center"><b>Cant. Egresos</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Costo Egresos</b></TD>
				<?php } ?>
				<?php if($almacen == 0) { ?>
				<TD align="center"><b>No. Trasp.</b></TD>
				<TD align="center"><b>Costo Extra Trasp.</b></TD>
				<?php } else { ?>
				<TD align="center"><b>Cant. Trasp. Ing.</b></TD>
				<TD align="center"><b>Costo Trasp. Ing.</b></TD>
				<TD align="center"><b>Costo Extra Trasp.</b></TD>
				<TD align="center"><b>Cant. Trasp. Egr.</b></TD>
				<TD align="center"><b>Costo Trasp. Egr.</b></TD>
				<?php } ?>
				<TD align="center"><b>Total Cant. Periodo</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Total Costo Periodo</b></TD>
				<?php } ?>
				<TD align="center"><b>Total Cant.</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Total Costo</b></TD>
				
				<?php if($otra_moneda != 0){ ?>
				<TD align="center"><b>Total Costo en <?php echo $nom_otra_moneda; ?></b></TD>
				<?php } ?>
				
				<?php } ?>
				<TD align="center"><b>Precio</b></TD>
				<?php if($otra_moneda != 0){ ?>
				<TD align="center"><b>Precio en <?php echo $nom_otra_moneda; ?></b></TD>
				<?php } ?>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Margen</b></TD>
				
				<?php if($otra_moneda != 0){ ?>
				<TD align="center"><b>Margen en <?php echo $nom_otra_moneda; ?></b></TD>
				<?php } ?>
				
				<?php } ?>
				</TR>
				</thead>
				<tbody class="marcafila">
			<?php } //fin if 13 ?>
			<?php
			$color = 2;
			$suma_total_cant_salini = 0;
			$suma_total_costo_salini = 0;
			$suma_total_cant_ing = 0;
			$suma_total_costo_ing = 0;
			$suma_total_cant_egr = 0;
			$suma_total_costo_egr = 0;
			$suma_total_trasp = 0;
			$suma_total_costo_extra_trasp = 0;
			$suma_total_trasp_ing = 0;
			$suma_total_costo_trasp_ing = 0;
			$suma_total_trasp_egr = 0;
			$suma_total_costo_trasp_egr = 0;
			$suma_total_cant_periodo = 0;
			$suma_total_costo_periodo = 0;
			$suma_total_cant = 0;
			$suma_total_costo = 0;
			$suma_total_otra_moneda = 0;
			$suma_total_margen = 0;
			$suma_total_margen_otra_moneda = 0;

			
			$j = 1;
			while ($j <= $fin) { //while
				
				//mostrar saldo 0
				if($mostrar_saldo_cero == 1) {//if saldo 0
					while($matriz_salini [$j][18] == 0 && $j <= $fin)
					{ $j++; }
				}//fin if saldo 0
				
				if($almacen == 0) { //if almacen por el 15
					while($matriz_salini [$j][9] == 0 && $matriz_salini [$j][10] == 0 && $matriz_salini [$j][11] == 0 && $matriz_salini [$j][12] == 0 && $matriz_salini [$j][13] == 0 && $matriz_salini [$j][14] == 0 && $matriz_salini [$j][15] == 0 && $j <= $fin)
					{ $j++; }
				} else { //else if almacen por el 15
					while($matriz_salini [$j][9] == 0 && $matriz_salini [$j][10] == 0 && $matriz_salini [$j][11] == 0 && $matriz_salini [$j][12] == 0 && $matriz_salini [$j][13] == 0 && $matriz_salini [$j][14] == 0 && $matriz_salini [$j][24] == 0 && $matriz_salini [$j][26] == 0 && $j <= $fin)
					{ $j++; }
				} //fin if almacen por el 15
				
				if($j > $fin) { //if ultimo 0
				} else { //else ultimo 0
				
				$codigo = $matriz_salini [$j][1];
				$totalcantdet = $matriz_salini [$j][9];
				$totalcostodet = $matriz_salini [$j][10];
				if($color % 2 == 0) { //if color
				printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
				} else {
				printf("<tr><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
				}//fin if color
				if($codfab_ver == 1) {
					printf("<td align='center'>%s</td>", $matriz_salini [$j][0]);//cod fabrica
				}
				printf("<td align='left'>%s</td>", $matriz_salini [$j][2]);//item
				//codigos de familia, subfamilia, grupo, subgrupo
					$result11 = mysqli_query($link, "select codFamily, codSubFamily, codGroup, codSubGroup
										from 
										invItem
										where
										pkyItem = '$codigo' and 
										sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result11)) {
						$cod_familia2 = $row['codFamily'];
						$cod_subfamilia2 = $row['codSubFamily'];
						$cod_grupo2 = $row['codGroup'];
						$cod_subgrupo2 = $row['codSubGroup'];
					}
					mysqli_free_result($result11);
					
					//nombre familia
					$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
										from 
										invItemCategory
										where
										pkyItemCategory = '$cod_familia2' and 
										sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result3)) {
						$nom_familia2 = $row['nombre'];
					}
					mysqli_free_result($result3);
					
					//nombre sub familia
					$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
										from 
										invItemCategory
										where
										pkyItemCategory = '$cod_subfamilia2' and 
										sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result3)) {
						$nom_subfamilia2 = $row['nombre'];
					}
					mysqli_free_result($result3);
					
					//nombre grupo
					$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
										from 
										invItemCategory
										where
										pkyItemCategory = '$cod_grupo2' and 
										sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result3)) {
						$nom_grupo2 = $row['nombre'];
					}
					mysqli_free_result($result3);
					
					//nombre sub grupo
					$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
										from 
										invItemCategory
										where
										pkyItemCategory = '$cod_subgrupo2' and 
										sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result3)) {
						$nom_subgrupo2 = $row['nombre'];
					}
					mysqli_free_result($result3);
					
					//precio
					$result4 = mysqli_query($link, "select a.pkyPriceList as cod_lista, a.codCurrency as cod_moneda,  b.fldPrice * tc.fldRate as precio, b.fldDiscount as descuento
						from slsPriceList a, slsPriceListDetail b, actExchangeRateDetail tc
						where 
						a.pkyPriceList = b.codPriceList and 
						b.codPriceList = '$lista_precio' and 
						b.codItem = '$codigo' and 
						tc.codTargetCurrency = a.codCurrency and
						tc.codBaseCurrency = '$cod_moneda' and
						tc.codExchangeRate = '$ultimo_tc' and 
						a.sysEnabled = 1 and a.sysAuthorized = 1
						union all 
						select a.pkyPriceList as cod_lista, a.codCurrency as cod_moneda, b.fldPrice as precio, b.fldDiscount as descuento
						from slsPriceList a, slsPriceListDetail b
						where 
						a.pkyPriceList = b.codPriceList and 
						b.codPriceList = '$lista_precio' and 
						b.codItem = '$codigo' and 
						a.codCurrency = '$cod_moneda' and
						a.sysEnabled = 1 and a.sysAuthorized = 1;");
					//$p = 0;
					while ($row = mysqli_fetch_array($result4)) {
						$precio = $row['precio'];
						//$p++;
					}
					mysqli_free_result($result4);
					/*
					if($p == 0) {
						$precio = 0;	
					}*/
				
					if($familia_ver == 1) {
					printf("<td>%s</td>", $nom_familia2);//familia
					}
					if($subfamilia_ver == 1) {
					printf("<td>%s</td>", $nom_subfamilia2);//sub familia
					}
					if($grupo_ver == 1) {
					printf("<td>%s</td>", $nom_grupo2);//grupo
					}
					if($subgrupo_ver == 1) {
					printf("<td>%s</td>", $nom_subgrupo2);//sub grupo
					}
					if($tipo_ver == 1) {
					printf("<td>%s</td>", $matriz_salini [$j][3]);//tipo
					}
					if($umen_ver == 1) {
					printf("<td>%s</td>", $matriz_salini [$j][4]);//unidad menor
					}
				
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][9],$n_cantidad));//cantidad saldo inicial
				if($mostrar_cant == 0) {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][10],$n_decimales));// costo saldo inicial
				}
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=1&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=1&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Cantidades Ingresos'>%s</a></td>", number_format($matriz_salini [$j][11],$n_cantidad));// cantidad ingresos
				if($mostrar_cant == 0) {
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=1&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Ingresos'>%s</a></td>", number_format($matriz_salini [$j][12],$n_decimales));// costo ingresos
				}
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=1&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=2&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Cantidades Egresos'>%s</a></td>", number_format($matriz_salini [$j][13],$n_cantidad));// cantidad egresos
				if($mostrar_cant == 0) {
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=2&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Egresos'>%s</a></td>", number_format($matriz_salini [$j][14],$n_decimales));// costo egresos
				}
				if($almacen == 0) {
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=1&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=3&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Cantidades Traspasos'>%s</a></td>", number_format($matriz_salini [$j][15],0));// cantidad traspasos
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=3&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Traspasos'>%s</a></td>", number_format($matriz_salini [$j][28],$n_decimales));// costo extra traspasos
				} else {
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=1&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=4&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Cantidades Traspasos Ing.'>%s</a></td>", number_format($matriz_salini [$j][26],0));// cantidad traspasos ingresos
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=4&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Traspasos Ing.'>%s</a></td>", number_format($matriz_salini [$j][27],$n_decimales));// costo traspasos ingresos	
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][28],$n_decimales));// costo extra traspasos
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=1&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=5&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Cantidades Traspasos Egr.'>%s</a></td>", number_format($matriz_salini [$j][24],0));// cantidad traspasos egresos
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=5&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Traspasos Egr.'>%s</a></td>", number_format($matriz_salini [$j][25],$n_decimales));// costo traspasos egresos
				}
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][16],$n_cantidad));// total cantidad periodo
				if($mostrar_cant == 0) {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][17],$n_decimales));// total costo periodo
				}
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=1&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=0&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item Cantidades'>%s</a></td>", number_format($matriz_salini [$j][18],$n_cantidad));// total cantidad 
				if($mostrar_cant == 0) { //if mostrar_cant
					if($otra_moneda != 0){
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=0&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item'>%s</a></td>", number_format($matriz_salini [$j][19],$n_decimales));//total costo
				
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=$otra_moneda&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=0&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item en $nom_otra_moneda'>%s</a></td>", number_format($matriz_salini [$j][19] * $tasa_tc,$n_decimales));// total otra moneda
					} else {
				printf("<td align='right'><a href='report.php?rep=9&tipo=2&itemdet=$codigo&fechainidet=$fechaini&fechafindet=$fechafin&totalcantdet=$totalcantdet&totalcostodet=$totalcostodet&otra_monedadet=0&almacen_det=$almacen&cuenta_almacen_det=$cuenta_almacen&empresa_det=$empresa&mostrar_cant_det=$mostrar_cant&concepto_det=$concepto&empresa_ver_det=$empresa_ver&cod_tipo_det=0&mostrar_lotes_det=$mostrar_lotes&glosa_ver_det=$glosa_ver&contexto_det=$cod_contexto&usuario_det=$usuario' title='Kardex de Item'>%s</a></td>", number_format($matriz_salini [$j][19],$n_decimales));//total costo
					}
				} //fin if mostrar_cant
				
				printf("<td align='right'>%s</td>", number_format($precio,$n_cantidad));// precio
				if($otra_moneda != 0){
				printf("<td align='right'>%s</td>", number_format($precio * $tasa_tc,$n_cantidad));// precio otra moneda	
				}
				if($mostrar_cant == 0) {
					if($matriz_salini [$j][18] != 0) { //controlar que no sea 0
						$margen = $precio - ($matriz_salini [$j][19] / $matriz_salini [$j][18]);
					}
					printf("<td align='right'>%s</td>", number_format($margen,$n_decimales));// margen
					if($otra_moneda != 0){
					printf("<td align='right'>%s</td>", number_format($margen * $tasa_tc,$n_decimales));// margen otra moneda	
					}	
				}
				} //cierra else ultimo 0
				
				echo '</tr>'; 
				$suma_total_cant_salini = $suma_total_cant_salini + $matriz_salini [$j][9];
				$suma_total_costo_salini = $suma_total_costo_salini + $matriz_salini [$j][10];
				$suma_total_cant_ing = $suma_total_cant_ing + $matriz_salini [$j][11];
				$suma_total_costo_ing = $suma_total_costo_ing + $matriz_salini [$j][12];
				$suma_total_cant_egr = $suma_total_cant_egr + $matriz_salini [$j][13];
				$suma_total_costo_egr = $suma_total_costo_egr + $matriz_salini [$j][14];
				$suma_total_trasp = $suma_total_trasp + $matriz_salini [$j][15];
				$suma_total_costo_extra_trasp = $suma_total_costo_extra_trasp + $matriz_salini [$j][28];
				$suma_total_trasp_ing = $suma_total_trasp_ing + $matriz_salini [$j][26];
				$suma_total_costo_trasp_ing = $suma_total_costo_trasp_ing + $matriz_salini [$j][27];
				$suma_total_trasp_egr = $suma_total_trasp_egr + $matriz_salini [$j][24];
				$suma_total_costo_trasp_egr = $suma_total_costo_trasp_egr + $matriz_salini [$j][25];
				$suma_total_cant_periodo = $suma_total_cant_periodo + $matriz_salini [$j][16];
				$suma_total_costo_periodo = $suma_total_costo_periodo + $matriz_salini [$j][17];
				$suma_total_cant = $suma_total_cant + $matriz_salini [$j][18];
				$suma_total_costo = $suma_total_costo + $matriz_salini [$j][19];
				$suma_total_otra_moneda = $suma_total_otra_moneda + $matriz_salini [$j][19] * $tasa_tc; 
				$suma_total_margen = $suma_total_margen + $margen;
				$suma_total_margen_otra_moneda = $suma_total_margen_otra_moneda + $margen * $tasa_tc;
				
				$nom_familia2 = '';//familia
				$nom_subfamilia2 = '';//sub familia
				$nom_grupo2 = '';//grupo
				$nom_subgrupo2 = '';//sub grupo
				$precio = 0;
				$margen = 0;
				$color++;
				$j++;
			}//fin while

			//acumulamos para el total de todos los almacenes
				$suma_total_cant_salini2 = $suma_total_cant_salini2 + $suma_total_cant_salini;
				$suma_total_costo_salini2 = $suma_total_costo_salini2 + $suma_total_costo_salini;
				$suma_total_cant_ing2 = $suma_total_cant_ing2 + $suma_total_cant_ing;
				$suma_total_costo_ing2 = $suma_total_costo_ing2 + $suma_total_costo_ing;
				$suma_total_cant_egr2 = $suma_total_cant_egr2 + $suma_total_cant_egr;
				$suma_total_costo_egr2 = $suma_total_costo_egr2 + $suma_total_costo_egr;
				$suma_total_trasp2 = $suma_total_trasp2 + $suma_total_trasp;
				$suma_total_costo_extra_trasp2 = $suma_total_costo_extra_trasp2 + $suma_total_costo_extra_trasp;
				$suma_total_trasp_ing2 = $suma_total_trasp_ing2 + $suma_total_trasp_ing;
				$suma_total_costo_trasp_ing2 = $suma_total_costo_trasp_ing2 + $suma_total_costo_trasp_ing;
				$suma_total_trasp_egr2 = $suma_total_trasp_egr2 + $suma_total_trasp_egr;
				$suma_total_costo_trasp_egr2 = $suma_total_costo_trasp_egr2 + $suma_total_costo_trasp_egr;
				$suma_total_cant_periodo2 = $suma_total_cant_periodo2 + $suma_total_cant_periodo;
				$suma_total_costo_periodo2 = $suma_total_costo_periodo2 + $suma_total_costo_periodo;
				$suma_total_cant2 = $suma_total_cant2 + $suma_total_cant;
				$suma_total_costo2 = $suma_total_costo2 + $suma_total_costo;
				$suma_total_otra_moneda2 = $suma_total_otra_moneda2 + $suma_total_otra_moneda;
				$suma_total_margen2 = $suma_total_margen2 + $suma_total_margen;
				$suma_total_margen_otra_moneda2 = $suma_total_margen_otra_moneda2 + $suma_total_margen_otra_moneda;

				//controlar la suma para saber si se muestra sumas con cero
				$suma_para_mostar_cero = $suma_total_cant_salini + $suma_total_costo_salini + $suma_total_cant_ing + $suma_total_costo_ing + $suma_total_cant_egr + $suma_total_costo_egr + $suma_total_trasp + $suma_total_costo_extra_trasp + $suma_total_trasp_ing + $suma_total_costo_trasp_ing + $suma_total_costo_extra_trasp + $suma_total_trasp_egr + $suma_total_costo_trasp_egr + $suma_total_cant_periodo + $suma_total_costo_periodo;
			?>

			<?php if($suma_para_mostar_cero != 0) { //if muestra cero ?>
				<?php if($mostrar_todo_alm == 1) { //if mostrar alm 1 ?>
					<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total <?php echo $mat_alm[$ma][2]; ?></b></td>
				<?php } else { ?>
					<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total</b></td>
				<?php } //fin if mostrar alm 1 ?>
				<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_salini,$n_cantidad)); ?></td>
				<?php if($mostrar_cant == 0) { ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_salini,$n_decimales)); ?></td>
				<?php } ?>
				<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_ing,$n_cantidad)); ?></td>
				<?php if($mostrar_cant == 0) { ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_ing,$n_decimales)); ?></td>
				<?php } ?>
				<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_egr,$n_cantidad)); ?></td>
				<?php if($mostrar_cant == 0) { ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_egr,$n_decimales)); ?></td>
				<?php } ?>
				<?php if($almacen == 0) { ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp,0)); ?></td>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp,$n_decimales)); ?></td>
				<?php } else { ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_ing,0)); ?></td>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_trasp_ing,$n_decimales)); ?></td>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp,$n_decimales)); ?></td>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_egr,0)); ?></td>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_trasp_egr,$n_decimales)); ?></td>
				<?php } ?>
				<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_periodo,$n_cantidad)); ?></td>
				<?php if($mostrar_cant == 0) { ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_periodo,$n_decimales)); ?></td>
				<?php } ?>
				<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant,$n_cantidad)); ?></td>
				<?php if($mostrar_cant == 0) { //if cant 01 ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo,$n_decimales)); ?></td>
					<?php if($otra_moneda != 0){ //if mon 01 ?>
						<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_otra_moneda,$n_decimales)); ?></td>
						<?php $total_otra_moneda = 0; ?>
					<?php } //fin if mon 01 ?>
				<?php } //fin if cant 01 ?>
				<td>&nbsp;</td>
				<?php if($otra_moneda != 0){ //if mon 031 ?>
					<td>&nbsp;</td>
				<?php } //fin if mon 031 ?>
				<?php if($mostrar_cant == 0) { //if cant 03 ?>
					<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_margen,$n_decimales)); ?></td>
					<?php if($otra_moneda != 0){ //if mon 03 ?>
						<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_margen_otra_moneda,$n_decimales)); ?></td>
					<?php } //fin if mon 03 ?>
				<?php } //fin if cant 03 ?>
				</tr>
			<?php } //fin if muestra cero ?>
		<?php } //fin for repite almacen ?>

		<?php if($mostrar_todo_alm == 1) { //if mostrar alm 1.1 ?>
		<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total Almacenes</b></td>

		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_salini2,$n_cantidad)); ?></td>
		<?php if($mostrar_cant == 0) { ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_salini2,$n_decimales)); ?></td>
		<?php } ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_ing2,$n_cantidad)); ?></td>
		<?php if($mostrar_cant == 0) { ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_ing2,$n_decimales)); ?></td>
		<?php } ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_egr2,$n_cantidad)); ?></td>
		<?php if($mostrar_cant == 0) { ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_egr2,$n_decimales)); ?></td>
		<?php } ?>
		<?php if($almacen == 0) { ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp2,0)); ?></td>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp2,$n_decimales)); ?></td>
		<?php } else { ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_ing2,0)); ?></td>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_trasp_ing2,$n_decimales)); ?></td>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp2,$n_decimales)); ?></td>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_egr2,0)); ?></td>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_trasp_egr2,$n_decimales)); ?></td>
		<?php } ?>
		</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_periodo2,$n_cantidad)); ?>
		<?php if($mostrar_cant == 0) { ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_periodo2,$n_decimales)); ?></td>
		<?php } ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant2,$n_cantidad)); ?></td>
		<?php if($mostrar_cant == 0) { //if cant 02 ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo2,$n_decimales)); ?></td>
		<?php if($otra_moneda != 0){ //if mon 02 ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_otra_moneda2,$n_decimales)); ?></td>
		<td>&nbsp;</td>
		<?php } //fin if mon 02 ?>
		<?php } //fin if cant 02 ?>

		<?php if($mostrar_cant == 0) { //if cant 03 ?>
		<td>&nbsp;</td>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_margen2,$n_decimales)); ?></td>
		<?php if($otra_moneda != 0){ //if mon 03 ?>
		<td align="right"><?php printf("<b>%s</b>", number_format($suma_total_margen_otra_moneda2,$n_decimales)); ?></td>
		<?php } //fin if mon 03 ?>
		<?php } //fin if cant 03 ?>
		<?php } //fin if mostrar alm 1.1 ?>
		</tr>
		</tbody>
		</table>
		<?php

	}//fin if agrupar items 1



	//aprupar por familia, subfamilia, grupo, subgrupo
	if($agrupar_items >= 2) { //if agrupar items 2
	
		for($ma = 1; $ma <= $fin_mat; $ma++) { //for repite almacen
		
			if($mostrar_todo_alm == 1) {//if 12
				$almacen = $mat_alm[$ma][1];
				$nom_mostrar_todo_alm = 'Si (Items en cada almacen)';
			} else { 
				$nom_mostrar_todo_alm = 'No (Consolidado) ';
			}//fin if 12
			
			if ($itemini == 0) { // if 2.0
					$nom_item_ini = 'Todos';
					$valor_item_ini = ' ';
					$nom_item_fin = 'Todos';
					$valor_item_fin = ' ';
				} else {
					//nombre item
					$result2 = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
											from
											invItem 
											where
											pkyItem = '$itemini' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_item_ini = $itemini.' - '.$row['cod_fabrica'].' - '.$row['item'];
					}
					mysqli_free_result($result2);
					$valor_item_ini = ' d.pkyItem >= ' .$itemini. ' and ';
				} //fin if 2.0
				
				if ($itemfin == 0) { // if 2.1
					$nom_item_fin = 'Todos';
					$valor_item_fin = ' ';
				} else {
					//nombre item
					$result2 = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
											from
											invItem 
											where
											pkyItem = '$itemfin' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_item_fin = $itemfin.' - '.$row['cod_fabrica'].' - '.$row['item'];
					}
					mysqli_free_result($result2);
					$valor_item_fin = ' d.pkyItem <= ' .$itemfin. ' and ';
				} //fin if 2.1
				
				if ($familia == 0) { // if 2.2
					$nom_familia = 'Todos';
					$valor_familia = ' ';
				} else {
					//nombre familia
					$result3 = 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($result3)) {
						$nom_familia = $row['nombre'];
					}
					mysqli_free_result($result3);
					$valor_familia = ' d.codFamily = ' .$familia. ' and ';
				} //fin if 2.2
				
				if ($subfamilia == 0) { // if 2.3
					$nom_subfamilia = 'Todos';
					$valor_subfamilia = ' ';
				} else {
					//nombre sub familia
					$result4 = 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($result4)) {
						$nom_subfamilia = $row['nombre'];
					}
					mysqli_free_result($result4);
					$valor_subfamilia = ' d.codSubFamily = ' .$subfamilia. ' and ';
				} //fin if 2.3
				
				if ($grupo == 0) { // if 2.4
					$nom_grupo = 'Todos';
					$valor_grupo = ' ';
				} else {
					//nombre grupo
					$result5 = 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($result5)) {
						$nom_grupo = $row['nombre'];
					}
					mysqli_free_result($result5);
					$valor_grupo = ' d.codGroup = ' .$grupo. ' and ';
				} //fin if 2.4
				
				if ($subgrupo == 0) { // if 2.5
					$nom_subgrupo = 'Todos';
					$valor_subgrupo = ' ';
				} else {
					//nombre sub grupo
					$result6 = 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($result6)) {
						$nom_subgrupo = $row['nombre'];
					}
					mysqli_free_result($result6);
					$valor_subgrupo = ' d.codSubGroup = ' .$subgrupo. ' and ';
				} //fin if 2.5
				
				
				if ($agrupar_items == 2) {
					$nom_orden = 'Familia';
					$valor_f = 'd.codFamily';
				} 
				if ($agrupar_items == 3) {
					$nom_orden = 'Sub Familia';
					$valor_f = 'd.codSubFamily';
				} 
				if ($agrupar_items == 4) {
					$nom_orden = 'Grupo';
					$valor_f = 'd.codGroup';
				} 
				if ($agrupar_items == 5) {
					$nom_orden = 'Sub Grupo';
					$valor_f = 'd.codSubGroup';
				} 
			/*  
				if ($item == 0) { // if 2.2
					$nom_orden = 'Item';
					$nom_item = 'Todos';
					$cod_item1 = ' ';
					$cod_item2 = ' ';
				} else {
					$nom_orden = 'Item';
					$cod_item1 = ' a.pkyItem = ' .$item. ' and ';
					$cod_item2 = ' a.codItem = ' .$item. ' and ';
				} //fin if 2.2
			*/	
				if ($almacen == 0) { // if 2.3
					//$nom_orden = Item;
					$nom_almacen = 'Todos';
					$valor_almacen1 = ' ';
					$valor_almacen2 = ' ';
				} else {
					//$nom_orden = Item;
					$valor_almacen1 = ' b.codTargetWarehouse = ' .$almacen. ' and ';
					$valor_almacen2 = ' b.codSourceWarehouse = ' .$almacen. ' and ';
					//nombre de almacen
					$result2 = mysqli_query($link, "select pkyWarehouse, fldName 
											from invWarehouse 
											where 
											pkyWarehouse = '$almacen' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_almacen = $row['fldName'];
					}
					mysqli_free_result($result2);
				} //fin if 2.3

				if ($cuenta_almacen == 0) { // if 2.3.1
					$nom_cuenta_almacen = 'Todos';
					$valor_cuenta_almacen = ' ';
					//$valor_cuenta_almacen2 = ' ';
				} else {
					$valor_cuenta_almacen = ' e.codAccount = ' .$cuenta_almacen. ' and ';
					//$valor_cuenta_almacen2 = ' e.codAccount = ' .$cuenta_almacen. ' and ';
					//nombre de la cuenta contable del almacen
					$result2 = mysqli_query($link, "select pkyAccount, fldName 
											from actAccount 
											where 
											pkyAccount = '$cuenta_almacen' and
											sysEnabled = 1 and sysAuthorized = 1;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_cuenta_almacen = $row['fldName'];
					}
					mysqli_free_result($result2);
				} //fin if 2.3.1

				if ($empresa == 0) { // if 2.3.2
					$nom_empresa = 'Todos';
					$valor_empresa = ' ';
				} else {
					//nombre concepto
					$result2 = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
								from agnCompany
								where
								pkyCompany = '$empresa';");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_empresa = $row['codigo'].' - '.$row['empresa'];
					}
					mysqli_free_result($result2);
					$valor_empresa = ' b.codSupplier = ' .$empresa. ' and ';
				} //fin if 2.3.2
				
				if ($concepto == 0) { // if 2.4
					$nom_concepto = 'Todos';
					$valor_concepto = ' ';
				} else {
					//nombre concepto
					$result2 = mysqli_query($link, "select a.pkyItemMovementTypeConcept as cod_concepto, a.fldName as concepto, b.fldName as tipo
								from invItemMovementTypeConcept a, invItemMovementType b 
								where 
								a.pkyItemMovementTypeConcept = '$concepto' and
								a.codItemMovementType = b.pkyItemMovementType;");
					while ($row = mysqli_fetch_array($result2)) {
						$nom_concepto = $row['concepto'].' - '.$row['tipo'];
					}
					mysqli_free_result($result2);
					$valor_concepto = ' b.codTypeConcept = ' .$concepto. ' and ';
				} //fin if 2.4
					
				//moneda
				$result0 = mysqli_query($link, "select a.pkyCurrency as codigo, a.fldName as moneda
			from actCurrency a, invInventoryConfig b
			where
			a.pkyCurrency = b.codCurrency and
			a.sysEnabled = 1 and a.sysAuthorized = 1;");
					
				while ($row = mysqli_fetch_array($result0)) {
				$nom_moneda = $row['moneda'];
				$cod_moneda = $row['codigo'];
				}
				mysqli_free_result($result0);
				
				//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 = ' b.sysContext = '.$cod_contexto.' and ';	
			}

					//listado de familias, subfamilias, grupo y subgrupo
					$result = mysqli_query($link, "select $valor_f as cod_f, e.fldName as nombre
			from invItem d, invItemType b, invStorageUnit c, invItemCategory e
			where
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			d.codType = b.pkyItemType and
			d.codMinimumStorageUnit = c.pkyStorageUnit and 
			$valor_f = e.pkyItemCategory and 
			d.sysEnabled = 1 and d.sysAuthorized = 1
			group by cod_f 
			order by nombre;");
					
							
					//inicio calculo saldo inicial por familia
					//ingresos
					$result2 = mysqli_query($link, "select fin.codigo as codigo, sum(fin.cant_ing) as cant_ing, 
			sum(fin.costo) as costo
			from(
			select t.codigo as codigo, t.cant_ing as cant_ing,
			t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
			t.costo as costopre, tc.fldRate as tasa, 
			t.costo * tc.fldRate as costo
			from(
			select $valor_f as codigo, sum(a.fldQuantity) as cant_ing, 
			b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where 
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen1 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and 
			b.fldDate < '$fechaini' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 1 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by codigo, cod_moneda, cod_tc) t, actExchangeRateDetail tc
			where
			tc.codTargetCurrency = t.cod_moneda and
			tc.codBaseCurrency = '$cod_moneda' and
			tc.codExchangeRate = t.cod_tc
			union all
			select t.codigo as codigo, t.cant_ing as cant_ing,
			t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
			t.costo as costopre, 1 as tasa, 
			t.costo as costo
			from(
			select $valor_f as codigo, sum(a.fldQuantity) as cant_ing, 
			b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
			where 
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen1 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate < '$fechaini' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 1 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by codigo, cod_moneda, cod_tc) t
			where
			t.cod_moneda = '$cod_moneda') fin
			group by fin.codigo;");
					//egresos
					$result3 = mysqli_query($link, "select $valor_f as codigo, sum(a.fldQuantity) as cant_egr, 
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
			where 
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen2 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and 
			b.fldDate < '$fechaini' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 2 and 
			b.codSourceWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by $valor_f;");
					//traspasos
					$result44 = mysqli_query($link, "select $valor_f as codigo, count(1) as nro_traspasos, sum(a.fldExtraCost) as costo_extra
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d
			where 
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate < '$fechaini' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by $valor_f;");
					
				if ($almacen != 0) { //if almacen
					//traspasos egresos
					$result4 = mysqli_query($link, "select $valor_f as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost - a.fldExtraCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
			where
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_cuenta_almacen 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and 
			b.codSourceWarehouse = '$almacen' and
			b.fldDate < '$fechaini' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and 
			b.codSourceWarehouse = e.pkyWarehouse and 
			a.sysEnabled = 1 and a.sysAuthorized = 1
			group by $valor_f;");
					//traspasos ingresos
					$result5 = mysqli_query($link, "select $valor_f as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
			where
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_cuenta_almacen 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.codTargetWarehouse = '$almacen' and
			b.fldDate < '$fechaini' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			a.sysEnabled = 1 and a.sysAuthorized = 1
			group by $valor_f;");
				}//fin if almacen

			$matriz_salini = array();
			$i = 1;
			while ($row = mysqli_fetch_array($result)) {
				$matriz_salini [$i][1] = $row['cod_f'];
				$matriz_salini [$i][2] = $row['nombre'];
				$i++;
			}
			$fin = $i - 1;
			mysqli_free_result($result);


			//ingresos
			while ($row = mysqli_fetch_array($result2)) {
				$i = 1;
				$cod_a = $row['codigo'];
				while ($cod_a <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][5] = $row['cant_ing'];
				$matriz_salini [$i][6] = $row['costo'];
			}
			mysqli_free_result($result2);
			//egresos
			while ($row = mysqli_fetch_array($result3)) {
				$i = 1;
				$cod_a = $row['codigo'];
				while ($cod_a <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][7] = $row['cant_egr'];
				$matriz_salini [$i][8] = $row['costo'];
			}
			mysqli_free_result($result3);

			//traspasos
			while ($row = mysqli_fetch_array($result44)) {
				$i = 1;
				$cod_a = $row['codigo'];
				while ($cod_a <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][29] = $row['costo_extra'];
			}
			mysqli_free_result($result44);

			if ($almacen != 0) {//if almacen 2
				//traspasos egresos
				while ($row = mysqli_fetch_array($result4)) {
					$i = 1;
					$cod_a = $row['codigo'];
					while ($cod_a <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][20] = $row['cant_tras'];
					$matriz_salini [$i][21] = $row['costo'];
				}
				mysqli_free_result($result4);
				
				//traspasos ingresos
				while ($row = mysqli_fetch_array($result5)) {
					$i = 1;
					$cod_a = $row['codigo'];
					while ($cod_a <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][22] = $row['cant_tras'];
					$matriz_salini [$i][23] = $row['costo'];
				}
				mysqli_free_result($result5);
			}//fin if almacen 2

			$i = 1;
			while($i <= $fin) {
				$cantidad_ing = $matriz_salini [$i][5];
				$costo_ing = $matriz_salini [$i][6];
				$cantidad_egr = $matriz_salini [$i][7];
				$costo_egr = $matriz_salini [$i][8];
				$costo_extra_trasp = $matriz_salini [$i][29];
				if ($almacen == 0) {//if almacen 3
					$matriz_salini [$i][9] = $cantidad_ing - $cantidad_egr; //cantidad saldo inicial
					$matriz_salini [$i][10] = $costo_ing - $costo_egr + $costo_extra_trasp; //costo saldo inicial
				} else { 
					$matriz_salini [$i][9] = $cantidad_ing - $cantidad_egr + $matriz_salini [$i][22] - $matriz_salini [$i][20]; //cantidad saldo inicial
					$matriz_salini [$i][10] = $costo_ing - $costo_egr + $matriz_salini [$i][23] - $matriz_salini [$i][21]; //costo saldo inicial
				} //fin almacen 3
				$i++;
			}

			//fin calculo saldo inicial


			//inicio calculo periodo


					//ingresos
					$result2 = mysqli_query($link, "select fin.codigo as codigo, sum(fin.cant_ing) as cant_ing, 
			sum(fin.costo) as costo
			from(
			select t.codigo as codigo, t.cant_ing as cant_ing,
			t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
			t.costo as costopre, tc.fldRate as tasa, 
			t.costo * tc.fldRate as costo
			from(
			select $valor_f as codigo, sum(a.fldQuantity) as cant_ing, 
			b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where 
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen1 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 1 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by codigo, cod_moneda, cod_tc) t, actExchangeRateDetail tc
			where
			tc.codTargetCurrency = t.cod_moneda and
			tc.codBaseCurrency = '$cod_moneda' and
			tc.codExchangeRate = t.cod_tc
			union all
			select t.codigo as codigo, t.cant_ing as cant_ing,
			t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
			t.costo as costopre, 1 as tasa, 
			t.costo as costo
			from(
			select $valor_f as codigo, sum(a.fldQuantity) as cant_ing, 
			b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where 
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen1 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 1 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by codigo, cod_moneda, cod_tc) t
			where
			t.cod_moneda = '$cod_moneda') fin
			group by fin.codigo;");
					//egresos
					$result3 = mysqli_query($link, "select $valor_f as codigo, sum(a.fldQuantity) as cant_egr, 
			sum(a.fldTotaCost) as costo
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where 
			$valor_item_ini 
			$valor_item_fin 
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_almacen2 
			$valor_cuenta_almacen 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 2 and 
			b.codSourceWarehouse = e.pkyWarehouse and 
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by $valor_f;");
					//traspasos
					$result4 = mysqli_query($link, "select $valor_f as codigo, count(1) as nro_traspasos, sum(a.fldExtraCost) as costo_extra
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d
			where 
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and  
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and
			b.sysEnabled = 1 and b.sysAuthorized = 1
			group by $valor_f;");

			if ($almacen != 0) { //if almacen
					//traspasos egresos
					$result5 = mysqli_query($link, "select $valor_f as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost - a.fldExtraCost) as costo, sum(a.fldExtraCost) as costo_extra
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
			where
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_cuenta_almacen 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and   
			b.codSourceWarehouse = '$almacen' and
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and 
			b.codSourceWarehouse = e.pkyWarehouse and 
			a.sysEnabled = 1 and a.sysAuthorized = 1
			group by $valor_f;");
					//traspasos ingresos
					$result6 = mysqli_query($link, "select $valor_f as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost) as costo, sum(a.fldExtraCost) as costo_extra
			from
			invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
			where
			$valor_item_ini 
			$valor_item_fin  
			$valor_familia 
			$valor_subfamilia 
			$valor_grupo 
			$valor_subgrupo 
			$valor_empresa 
			$valor_cuenta_almacen 
			$valor_concepto 
			$valor_contexto 
			a.codItem = d.pkyItem and 
			b.codTargetWarehouse = '$almacen' and
			b.fldDate >= '$fechaini' and
			b.fldDate <= '$fechafin' and
			a.codItemMovement = b.pkyItemMovement and
			b.codType = c.pkyItemMovementType and
			b.codType = 3 and 
			b.codTargetWarehouse = e.pkyWarehouse and 
			a.sysEnabled = 1 and a.sysAuthorized = 1
			group by $valor_f;");
				}//fin if almacen

			//ingresos
			while ($row = mysqli_fetch_array($result2)) {
				$i = 1;
				$cod_a = $row['codigo'];
				while ($cod_a <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][11] = $row['cant_ing'];
				$matriz_salini [$i][12] = $row['costo'];
			}
			mysqli_free_result($result2);
			//egresos
			while ($row = mysqli_fetch_array($result3)) {
				$i = 1;
				$cod_a = $row['codigo'];
				while ($cod_a <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][13] = $row['cant_egr'];
				$matriz_salini [$i][14] = $row['costo'];
			}
			mysqli_free_result($result3);
			//traspasos
			while ($row = mysqli_fetch_array($result4)) {
				$i = 1;
				$cod_a = $row['codigo'];
				while ($cod_a <> $matriz_salini [$i][1]) {
					$i++;
				}
				$matriz_salini [$i][15] = $row['nro_traspasos'];
				$matriz_salini [$i][28] = $row['costo_extra'];
			}
			mysqli_free_result($result4);

			if ($almacen != 0) {//if almacen 2
				//traspasos egresos
				while ($row = mysqli_fetch_array($result5)) {
					$i = 1;
					$cod_a = $row['codigo'];
					while ($cod_a <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][24] = $row['cant_tras'];
					$matriz_salini [$i][25] = $row['costo'];
					$matriz_salini [$i][28] = 0;
				}
				mysqli_free_result($result5);
				
				//traspasos ingresos
				while ($row = mysqli_fetch_array($result6)) {
					$i = 1;
					$cod_a = $row['codigo'];
					while ($cod_a <> $matriz_salini [$i][1]) {
						$i++;
					}
					$matriz_salini [$i][26] = $row['cant_tras'];
					$matriz_salini [$i][27] = $row['costo'];
					$matriz_salini [$i][28] = $row['costo_extra'];
				}
				mysqli_free_result($result6);
			}//fin if almacen 2

			$i = 1;
			while($i <= $fin) {
				$cant_ing = $matriz_salini [$i][11];
				$costo_ing = $matriz_salini [$i][12];
				$cant_egr = $matriz_salini [$i][13];
				$costo_egr = $matriz_salini [$i][14];
				$costo_extra_trasp = $matriz_salini [$i][28];
				if($almacen == 0) {//if almacen 4
					$matriz_salini [$i][16] = $cant_ing - $cant_egr; //total cantidad periodo
					$matriz_salini [$i][17] = $costo_ing - $costo_egr + $costo_extra_trasp; //total costo periodo
				} else {
					$matriz_salini [$i][16] = $cant_ing - $cant_egr + $matriz_salini [$i][26] - $matriz_salini [$i][24]; //total cantidad periodo
					$matriz_salini [$i][17] = $costo_ing - $costo_egr + $matriz_salini [$i][27] - $matriz_salini [$i][25]; //total costo periodo
				}//fin if almacen 4
				$cant_salini = $matriz_salini [$i][9];
				$costo_salini = $matriz_salini [$i][10];
				$cant_periodo = $matriz_salini [$i][16];
				$costo_periodo = $matriz_salini [$i][17];
				
				$matriz_salini [$i][18] = $cant_salini + $cant_periodo; //total cantidad
				$matriz_salini [$i][19] = $costo_salini + $costo_periodo; //total costo
				$i++;
			}


				
			//fin calculo periodo
					?>
			<?php if($ma == 1) {//if 13, muestra solo una vez por la iteracion de almacenes ?>
			<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>Inventario Valorado</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 inicial: </b><?php echo $nom_item_ini; ?></TD>
					<TD width="25%"><b>Item final: </b><?php echo $nom_item_fin; ?></TD>
					<?php if($var_alm == 0) { ?>
					<TD width="25%"><b>Almac&eacute;n: </b>Todos</TD>
					<?php } else { ?>
					<TD width="25%"><b>Almac&eacute;n: </b><?php echo $nom_almacen; ?></TD>
					<?php } ?>
					<TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></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>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
					<TD><b>Empresa: </b><?php echo $nom_empresa; ?></TD>
					<TD><b>Concepto: </b><?php echo $nom_concepto; ?></TD>
					<TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
					</TR>
					<TR>
					<TD><b>Mostrar solo cantidades: </b><?php echo $nom_mostrar_cant; ?></TD>
					<TD><b>Mostrar saldos en cero: </b><?php echo $nom_mostrar_saldo_cero; ?></TD>
					<TD colspan="2"><b>Cuenta Contable del Almac&eacute;n: </b><?php echo $nom_cuenta_almacen; ?></TD>
					</TR>
					<TR>
					<?php if($agrupar_items == 2) { ?>
					<TD><b>Mostrar todos los almacenes: </b><?php echo $nom_mostrar_todo_alm; ?></TD>
					<TD><b>Mostrar Lotes: </b><?php echo $nom_mostrar_lotes; ?></TD>
					<?php } else { ?>
					<TD colspan="2"><b>Mostrar todos los almacenes: </b><?php echo $nom_mostrar_todo_alm; ?></TD>
					<?php } ?>
					<TD><b>Items agrupados: </b><?php echo $nom_agrupar_items; ?></TD>
					<TD><b>Mostrar por: </b><?php echo $nom_mostrar; ?></TD>
					</TR>
					<?php if($mostrar_cant == 0) { ?>
					<TR>
					<TD colspan="2"><b>Expresado en: </b><?php echo $nom_moneda; ?></TD>
					<TD colspan="2"><b>Valorado tambi&eacute;n en: </b><?php echo $texto_otra_moneda; ?></TD>
					</TR>
					<?php } ?>
					
				</table>

			</td>

			<td valign="top" width="150">

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

			</tr>
			</table>
			<br /> 
			<table border="1" align="center" cellpadding="2" width="100%">
				<thead>
				<TR> 
				<TD align="center"><b>Cod.</b></TD>
				<TD align="center"><b><?php echo $nom_orden; ?></b></TD>
				<TD align="center"><b>Cant. Saldo Inicial</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Costo Saldo Inicial</b></TD>
				<?php } ?>
				<TD align="center"><b>Cant. Ingresos</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Costo Ingresos</b></TD>
				<?php } ?>
				<TD align="center"><b>Cant. Egresos</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Costo Egresos</b></TD>
				<?php } ?>
				<?php if($almacen == 0) { ?>
				<TD align="center"><b>Cant. Trasp.</b></TD>
				<TD align="center"><b>Costo Extra Trasp.</b></TD>
				<?php } else { ?>
				<TD align="center"><b>Cant. Trasp. Ing.</b></TD>
				<TD align="center"><b>Cant. Trasp. Egr.</b></TD>
				<TD align="center"><b>Costo Extra Trasp.</b></TD>
				<?php } ?>
				<TD align="center"><b>Total Cant. Periodo</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Total Costo Periodo</b></TD>
				<?php } ?>
				<TD align="center"><b>Total Cant.</b></TD>
				<?php if($mostrar_cant == 0) { ?>
				<TD align="center"><b>Total Costo</b></TD>
				
				<?php if($otra_moneda != 0){ ?>
				<TD align="center"><b>Total Costo en <?php echo $nom_otra_moneda; ?></b></TD>
				<?php } ?>
				
				<?php } ?>
				</TR>
				</thead>
				<tbody class="marcafila">
			<?php } //fin if 13 ?>
			<?php
			$color = 2;
			$suma_total_cant_salini = 0;
			$suma_total_costo_salini = 0;
			$suma_total_cant_ing = 0;
			$suma_total_costo_ing = 0;
			$suma_total_cant_egr = 0;
			$suma_total_costo_egr = 0;
			$suma_total_trasp = 0;
			$suma_total_costo_extra_trasp = 0;
			$suma_total_trasp_ing = 0;
			$suma_total_trasp_egr = 0;
			$suma_total_cant_periodo = 0;
			$suma_total_costo_periodo = 0;
			$suma_total_cant = 0;
			$suma_total_costo = 0;
			$suma_total_otra_moneda = 0;
			
			$j = 1;
			while ($j <= $fin) { //while
				
				//mostrar saldo 0
				if($mostrar_saldo_cero == 1) {//if saldo 0
					while($matriz_salini [$j][18] == 0 && $j <= $fin)
					{ $j++; }
				}//fin if saldo 0
				
				if($almacen == 0) { //if almacen por el 15
					while($matriz_salini [$j][9] == 0 && $matriz_salini [$j][10] == 0 && $matriz_salini [$j][11] == 0 && $matriz_salini [$j][12] == 0 && $matriz_salini [$j][13] == 0 && $matriz_salini [$j][14] == 0 && $matriz_salini [$j][15] == 0 && $j <= $fin)
				{ $j++; }
				} else { //else if almacen por el 15
					while($matriz_salini [$j][9] == 0 && $matriz_salini [$j][10] == 0 && $matriz_salini [$j][11] == 0 && $matriz_salini [$j][12] == 0 && $matriz_salini [$j][13] == 0 && $matriz_salini [$j][14] == 0 && $matriz_salini [$j][24] == 0 && $matriz_salini [$j][26] == 0 && $j <= $fin)
					{ $j++; }
				} //fin if almacen por el 15
				
				if($j > $fin) { //if ultimo 0
				} else { //else ultimo 0
				
				$codigo = $matriz_salini [$j][1];
				$totalcantdet = $matriz_salini [$j][9];
				$totalcostodet = $matriz_salini [$j][10];
				if($color % 2 == 0) { //if color
				printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
				} else {
				printf("<tr><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
				}//fin if color
				
				printf("<td align='left'>%s</td>", $matriz_salini [$j][2]);//nombre
					
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][9],$n_cantidad));//cantidad saldo inicial
				if($mostrar_cant == 0) {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][10],$n_decimales));// costo saldo inicial
				}
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][11],$n_cantidad));// cantidad ingresos
				if($mostrar_cant == 0) {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][12],$n_decimales));// costo ingresos
				}
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][13],$n_cantidad));// cantidad egresos
				if($mostrar_cant == 0) {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][14],$n_decimales));// costo egresos
				}
				if($almacen == 0) {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][15],0));// cantidad traspasos
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][28],$n_decimales));// costo extra traspasos
				} else {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][26],0));// cantidad traspasos ingresos	
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][24],0));// cantidad traspasos egresos
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][28],$n_decimales));// costo extra traspasos
				}
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][16],$n_cantidad));// total cantidad periodo
				if($mostrar_cant == 0) {
				printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][17],$n_decimales));// total costo periodo
				}
				if($agrupar_items == 2) {//if familia
					printf("<td align='right'><a href='report.php?rep=9&tipo=1&familia_rev=$codigo&fechaini_rev=$fechaini&fechafin_rev=$fechafin&almacen_rev=$almacen&cuenta_almacen_rev=$cuenta_almacen&empresa_rev=$empresa&concepto_rev=$concepto&otra_moneda_rev=$otra_moneda&mostrar_cant_rev=$mostrar_cant&mostrar_saldo_cero_rev=$mostrar_saldo_cero&mostrar_rev=1&mostrar_todo_alm_rev=$mostrar_todo_alm&agrupar_items_rev=1&mostrar_lotes_rev=$mostrar_lotes&codfab_ver_rev=$codfab_ver&familia_ver_rev=$familia_ver&subfamilia_ver_rev=$subfamilia_ver&grupo_ver_rev=$grupo_ver&subgrupo_ver_rev=$subgrupo_ver&tipo_ver_rev=$tipo_ver&umen_ver_rev=$umen_ver&contexto_rev=$cod_contexto&usuario_rev=$usuario' title='Reporte Valorado por Items'>%s</a></td>", number_format($matriz_salini [$j][18],$n_cantidad));// total cantidad 
				
				if($mostrar_cant == 0) { //if mostrar_cant
					if($otra_moneda != 0){
				printf("<td align='right'><a href='report.php?rep=9&tipo=1&familia_rev=$codigo&fechaini_rev=$fechaini&fechafin_rev=$fechafin&almacen_rev=$almacen&cuenta_almacen_rev=$cuenta_almacen&empresa_rev=$empresa&concepto_rev=$concepto&otra_moneda_rev=$otra_moneda&mostrar_cant_rev=$mostrar_cant&mostrar_saldo_cero_rev=$mostrar_saldo_cero&mostrar_rev=1&mostrar_todo_alm_rev=$mostrar_todo_alm&agrupar_items_rev=1&mostrar_lotes_rev=$mostrar_lotes&codfab_ver_rev=$codfab_ver&familia_ver_rev=$familia_ver&subfamilia_ver_rev=$subfamilia_ver&grupo_ver_rev=$grupo_ver&subgrupo_ver_rev=$subgrupo_ver&tipo_ver_rev=$tipo_ver&umen_ver_rev=$umen_ver&contexto_rev=$cod_contexto&usuario_rev=$usuario' title='Reporte Valorado por Items'>%s</a></td>", number_format($matriz_salini [$j][19],$n_decimales));//total costo
				
				printf("<td align='right'><a href='report.php?rep=9&tipo=1&familia_rev=$codigo&fechaini_rev=$fechaini&fechafin_rev=$fechafin&almacen_rev=$almacen&cuenta_almacen_rev=$cuenta_almacen&empresa_rev=$empresa&concepto_rev=$concepto&otra_moneda_rev=$otra_moneda&mostrar_cant_rev=$mostrar_cant&mostrar_saldo_cero_rev=$mostrar_saldo_cero&mostrar_rev=1&mostrar_todo_alm_rev=$mostrar_todo_alm&agrupar_items_rev=1&mostrar_lotes_rev=$mostrar_lotes&codfab_ver_rev=$codfab_ver&familia_ver_rev=$familia_ver&subfamilia_ver_rev=$subfamilia_ver&grupo_ver_rev=$grupo_ver&subgrupo_ver_rev=$subgrupo_ver&tipo_ver_rev=$tipo_ver&umen_ver_rev=$umen_ver&contexto_rev=$cod_contexto&usuario_rev=$usuario' title='Reporte Valorado por Items'>%s</a></td>", number_format($matriz_salini [$j][19] * $tasa_tc,$n_decimales));// total otra moneda
					} else {
				printf("<td align='right'><a href='report.php?rep=9&tipo=1&familia_rev=$codigo&fechaini_rev=$fechaini&fechafin_rev=$fechafin&almacen_rev=$almacen&cuenta_almacen_rev=$cuenta_almacen&empresa_rev=$empresa&concepto_rev=$concepto&otra_moneda_rev=$otra_moneda&mostrar_cant_rev=$mostrar_cant&mostrar_saldo_cero_rev=$mostrar_saldo_cero&mostrar_rev=1&mostrar_todo_alm_rev=$mostrar_todo_alm&agrupar_items_rev=1&mostrar_lotes_rev=$mostrar_lotes&codfab_ver_rev=$codfab_ver&familia_ver_rev=$familia_ver&subfamilia_ver_rev=$subfamilia_ver&grupo_ver_rev=$grupo_ver&subgrupo_ver_rev=$subgrupo_ver&tipo_ver_rev=$tipo_ver&umen_ver_rev=$umen_ver&contexto_rev=$cod_contexto&usuario_rev=$usuario' title='Reporte Valorado por Items'>%s</a></td>", number_format($matriz_salini [$j][19],$n_decimales));//total costo
					}
				} //fin if mostrar_cant
				
				} else {//else if familia
					printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][18],$n_cantidad));// total cantidad
					if($mostrar_cant == 0) { //if mostrar_cant
					if($otra_moneda != 0){
					printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][19],$n_decimales));//total costo
				
					printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][19] * $tasa_tc,$n_decimales));// total otra moneda
					} else {
					printf("<td align='right'>%s</td>", number_format($matriz_salini [$j][19],$n_decimales));//total costo
					}
				} //fin if mostrar_cant
				}//fin if familia
				} //cierra else ultimo 0
				echo '</tr>';
				$suma_total_cant_salini = $suma_total_cant_salini + $matriz_salini [$j][9];
				$suma_total_costo_salini = $suma_total_costo_salini + $matriz_salini [$j][10];
				$suma_total_cant_ing = $suma_total_cant_ing + $matriz_salini [$j][11];
				$suma_total_costo_ing = $suma_total_costo_ing + $matriz_salini [$j][12];
				$suma_total_cant_egr = $suma_total_cant_egr + $matriz_salini [$j][13];
				$suma_total_costo_egr = $suma_total_costo_egr + $matriz_salini [$j][14];
				$suma_total_trasp = $suma_total_trasp + $matriz_salini [$j][15];
				$suma_total_costo_extra_trasp = $suma_total_costo_extra_trasp + $matriz_salini [$j][28];
				$suma_total_trasp_ing = $suma_total_trasp_ing + $matriz_salini [$j][26];
				$suma_total_trasp_egr = $suma_total_trasp_egr + $matriz_salini [$j][24];
				$suma_total_cant_periodo = $suma_total_cant_periodo + $matriz_salini [$j][16];
				$suma_total_costo_periodo = $suma_total_costo_periodo + $matriz_salini [$j][17];
				$suma_total_cant = $suma_total_cant + $matriz_salini [$j][18];
				$suma_total_costo = $suma_total_costo + $matriz_salini [$j][19];
				$suma_total_otra_moneda = $suma_total_otra_moneda + $matriz_salini [$j][19] * $tasa_tc; 
				
				$nom_familia2 = '';//familia
				$nom_subfamilia2 = '';//sub familia
				$nom_grupo2 = '';//grupo
				$nom_subgrupo2 = '';//sub grupo
				$color++;
				$j++;
			}//fin while

			//acumulamos para el total de todos los almacenes
				$suma_total_cant_salini2 = $suma_total_cant_salini2 + $suma_total_cant_salini;
				$suma_total_costo_salini2 = $suma_total_costo_salini2 + $suma_total_costo_salini;
				$suma_total_cant_ing2 = $suma_total_cant_ing2 + $suma_total_cant_ing;
				$suma_total_costo_ing2 = $suma_total_costo_ing2 + $suma_total_costo_ing;
				$suma_total_cant_egr2 = $suma_total_cant_egr2 + $suma_total_cant_egr;
				$suma_total_costo_egr2 = $suma_total_costo_egr2 + $suma_total_costo_egr;
				$suma_total_trasp2 = $suma_total_trasp2 + $suma_total_trasp;
				$suma_total_costo_extra_trasp2 = $suma_total_costo_extra_trasp2 + $suma_total_costo_extra_trasp;
				$suma_total_trasp_ing2 = $suma_total_trasp_ing2 + $suma_total_trasp_ing;
				$suma_total_trasp_egr2 = $suma_total_trasp_egr2 + $suma_total_trasp_egr;
				$suma_total_cant_periodo2 = $suma_total_cant_periodo2 + $suma_total_cant_periodo;
				$suma_total_costo_periodo2 = $suma_total_costo_periodo2 + $suma_total_costo_periodo;
				$suma_total_cant2 = $suma_total_cant2 + $suma_total_cant;
				$suma_total_costo2 = $suma_total_costo2 + $suma_total_costo;
				$suma_total_otra_moneda2 = $suma_total_otra_moneda2 + $suma_total_otra_moneda;

				//controlar la suma para saber si se muestra sumas con cero
				$suma_para_mostar_cero = $suma_total_cant_salini + $suma_total_costo_salini + $suma_total_cant_ing + $suma_total_costo_ing + $suma_total_cant_egr + $suma_total_costo_egr + $suma_total_trasp + $suma_total_costo_extra_trasp + $suma_total_trasp_ing + $suma_total_costo_trasp_ing + $suma_total_costo_extra_trasp + $suma_total_trasp_egr + $suma_total_costo_trasp_egr + $suma_total_cant_periodo + $suma_total_costo_periodo;

			?>
			<?php if($suma_para_mostar_cero != 0) { //if muestra cero ?>
				<?php if($mostrar_todo_alm == 1) { //if mostrar alm 1 ?>
				<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total <?php echo $mat_alm[$ma][2]; ?></b>
				<?php } else { ?>
				<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total</b>
				<?php } //fin if mostrar alm 1 ?>

				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_salini,$n_cantidad)); ?>
				<?php if($mostrar_cant == 0) { ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_salini,$n_decimales)); ?>
				<?php } ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_ing,$n_cantidad)); ?>
				<?php if($mostrar_cant == 0) { ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_ing,$n_decimales)); ?>
				<?php } ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_egr,$n_cantidad)); ?>
				<?php if($mostrar_cant == 0) { ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_egr,$n_decimales)); ?>
				<?php } ?>
				<?php if($almacen == 0) { ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp,0)); ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp,$n_decimales)); ?>
				<?php } else { ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_ing,0)); ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_egr,0)); ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp,$n_decimales)); ?>
				<?php } ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_periodo,$n_cantidad)); ?>
				<?php if($mostrar_cant == 0) { ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_periodo,$n_decimales)); ?>
				<?php } ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant,$n_cantidad)); ?>
				<?php if($mostrar_cant == 0) { //if cant 01 ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo,$n_decimales)); ?>
				<?php if($otra_moneda != 0){ //if mon 01 ?>
				</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_otra_moneda,$n_decimales)); ?>
				<?php $total_otra_moneda = 0; ?>
				<?php } //fin if mon 01 ?>
				<?php } //fin if cant 01 ?>
				</td></tr>
			<?php } //fin if muestra cero ?>
		<?php } //fin for repite almacen ?>

	<?php if($mostrar_todo_alm == 1) { //if mostrar alm 1.1 ?>
	<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total Almacenes</b>

	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_salini2,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_salini2,$n_decimales)); ?>
	<?php } ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_ing2,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_ing2,$n_decimales)); ?>
	<?php } ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_egr2,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_egr2,$n_decimales)); ?>
	<?php } ?>
	<?php if($almacen == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp2,0)); ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp2,$n_decimales)); ?>
	<?php } else { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_ing2,0)); ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_trasp_egr2,0)); ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_extra_trasp2,$n_decimales)); ?>
	<?php } ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_periodo2,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_periodo2,$n_decimales)); ?>
	<?php } ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant2,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { //if cant 02 ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo2,$n_decimales)); ?>
	<?php if($otra_moneda != 0){ //if mon 02 ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_otra_moneda2,$n_decimales)); ?>
	<?php } //fin if mon 02 ?>
	<?php } //fin if cant 02 ?>
	<?php } //fin if mostrar alm 1.1 ?>
	</tbody>
	</table>
	<?php

	}//fin if agrupar items 2


//no agrupar tipo kardex
if($agrupar_items == 0) { //if agrupar items 3
 
 $nro_col = 9;
 
 for($ma = 1; $ma <= $fin_mat; $ma++) { //for repite almacen
  
  if($mostrar_todo_alm == 1) {//if 12
 	$almacen = $mat_alm[$ma][1];
	$nom_mostrar_todo_alm = 'Si (Items en cada almacen)';
  } else { 
  	$nom_mostrar_todo_alm = 'No (Consolidado)';
  }//fin if 12
  
  if ($itemini == 0) { // if 2.0
		$nom_item_ini = 'Todos';
		$valor_item_ini = ' ';
		$nom_item_fin = 'Todos';
		$valor_item_fin = ' ';
	} else {
		//nombre item
		$result2 = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
								from
								invItem 
								where
								pkyItem = '$itemini' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_item_ini = $itemini.' - '.$row['cod_fabrica'].' - '.$row['item'];
		}
		mysqli_free_result($result2);
		$valor_item_ini = ' d.pkyItem >= ' .$itemini. ' and ';
	} //fin if 2.0
	
	if ($itemfin == 0) { // if 2.1
		$nom_item_fin = 'Todos';
		$valor_item_fin = ' ';
	} else {
		//nombre item
		$result2 = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
								from
								invItem 
								where
								pkyItem = '$itemfin' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_item_fin = $itemfin.' - '.$row['cod_fabrica'].' - '.$row['item'];
		}
		mysqli_free_result($result2);
		$valor_item_fin = ' d.pkyItem <= ' .$itemfin. ' and ';
	} //fin if 2.1
	
	if ($familia == 0) { // if 2.2
		$nom_familia = 'Todos';
		$valor_familia = ' ';
	} else {
		//nombre familia
		$result3 = 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($result3)) {
			$nom_familia = $row['nombre'];
		}
		mysqli_free_result($result3);
		$valor_familia = ' d.codFamily = ' .$familia. ' and ';
	} //fin if 2.2
	
	if ($subfamilia == 0) { // if 2.3
		$nom_subfamilia = 'Todos';
		$valor_subfamilia = ' ';
	} else {
		//nombre sub familia
		$result4 = 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($result4)) {
			$nom_subfamilia = $row['nombre'];
		}
		mysqli_free_result($result4);
		$valor_subfamilia = ' d.codSubFamily = ' .$subfamilia. ' and ';
	} //fin if 2.3
	
	if ($grupo == 0) { // if 2.4
		$nom_grupo = 'Todos';
		$valor_grupo = ' ';
	} else {
		//nombre grupo
		$result5 = 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($result5)) {
			$nom_grupo = $row['nombre'];
		}
		mysqli_free_result($result5);
		$valor_grupo = ' d.codGroup = ' .$grupo. ' and ';
	} //fin if 2.4
	
	if ($subgrupo == 0) { // if 2.5
		$nom_subgrupo = 'Todos';
		$valor_subgrupo = ' ';
	} else {
		//nombre sub grupo
		$result6 = 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($result6)) {
			$nom_subgrupo = $row['nombre'];
		}
		mysqli_free_result($result6);
		$valor_subgrupo = ' d.codSubGroup = ' .$subgrupo. ' and ';
	} //fin if 2.5
	
	if ($orden == 0) { 
		$nom_orden = 'Item (Nombre)';
		$valor_orden = ' order by d.fldName ';
		$valor_orden2 = ' order by item, fecha, cod_det ';
	}
	if ($orden == 1) {
		$nom_orden = 'Item (C&oacute;digo)';
		$valor_orden = ' order by d.pkyItem ';
		$valor_orden2 = ' order by codigo, fecha, cod_det ';
	} 
	if ($orden == 2) {
		$nom_orden = 'Item (C&oacute;digo de F&aacute;brica)';
		$valor_orden = ' order by d.fldFactoryKey ';
		$valor_orden2 = ' order by cod_fabrica, fecha, cod_det ';
	} 
	if ($orden == 3) {
		$nom_orden = 'Familia (C&oacute;digo)';
		$valor_orden = ' order by d.codFamily, d.codSubFamily, d.codGroup, d.codSubGroup, d.pkyItem ';
		$valor_orden2 = ' order by cod_familia, cod_subfamilia, cod_grupo, cod_subgrupo, fecha, cod_det ';
	} 
/*  
	if ($item == 0) { // if 2.2
		$nom_orden = 'Item';
		$nom_item = 'Todos';
		$cod_item1 = ' ';
		$cod_item2 = ' ';
	} else {
		$nom_orden = 'Item';
		$cod_item1 = ' a.pkyItem = ' .$item. ' and ';
		$cod_item2 = ' a.codItem = ' .$item. ' and ';
	} //fin if 2.2
*/	
	if ($almacen == 0) { // if 2.3
		//$nom_orden = Item;
		$nom_almacen = 'Todos';
		$valor_almacen1 = ' ';
		$valor_almacen2 = ' ';
		$valor_almacen3 = ' ';
	} else {
		//$nom_orden = Item;
		$valor_almacen1 = ' b.codTargetWarehouse = ' .$almacen. ' and ';
		$valor_almacen2 = ' b.codSourceWarehouse = ' .$almacen. ' and ';
		$valor_almacen3 = ' (b.codTargetWarehouse = ' .$almacen. ' or b.codSourceWarehouse = ' .$almacen. ') and ';
		//nombre de almacen
		$result2 = mysqli_query($link, "select pkyWarehouse, fldName 
					   			from invWarehouse 
					   			where 
								pkyWarehouse = '$almacen' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_almacen = $row['fldName'];
		}
		mysqli_free_result($result2);
	} //fin if 2.3

	if ($cuenta_almacen == 0) { // if 2.3.1
		$nom_cuenta_almacen = 'Todos';
		$valor_cuenta_almacen = ' ';
		$valor_cuenta_almacen2 = ' ';
	} else {
		$valor_cuenta_almacen = ' e.codAccount = ' .$cuenta_almacen. ' and ';
		$valor_cuenta_almacen2 = ' g.codAccount = ' .$cuenta_almacen. ' and ';
		//nombre de la cuenta contable del almacen
		$result2 = mysqli_query($link, "select pkyAccount, fldName 
					   			from actAccount 
					   			where 
								pkyAccount = '$cuenta_almacen' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_cuenta_almacen = $row['fldName'];
		}
		mysqli_free_result($result2);
	} //fin if 2.3.1
	
	if ($empresa == 0) { // if 2.3.2
		$nom_empresa = 'Todos';
		$valor_empresa = ' ';
	} else {
		//nombre concepto
		$result2 = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
					from agnCompany
					where
					pkyCompany = '$empresa';");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_empresa = $row['codigo'].' - '.$row['empresa'];
		}
		mysqli_free_result($result2);
		$valor_empresa = ' b.codSupplier = ' .$empresa. ' and ';
	} //fin if 2.3.2

	if ($concepto == 0) { // if 2.4
		$nom_concepto = 'Todos';
		$valor_concepto = ' ';
	} else {
		//nombre concepto
		$result2 = mysqli_query($link, "select a.pkyItemMovementTypeConcept as cod_concepto, a.fldName as concepto, b.fldName as tipo
					from invItemMovementTypeConcept a, invItemMovementType b 
					where 
					a.pkyItemMovementTypeConcept = '$concepto' and
					a.codItemMovementType = b.pkyItemMovementType;");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_concepto = $row['concepto'].' - '.$row['tipo'];
		}
		mysqli_free_result($result2);
		$valor_concepto = ' b.codTypeConcept = ' .$concepto. ' and ';
	} //fin if 2.4
		
	//moneda
	$result0 = mysqli_query($link, "select a.pkyCurrency as codigo, a.fldName as moneda
from actCurrency a, invInventoryConfig b
where
a.pkyCurrency = b.codCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($result0)) {
	$nom_moneda = $row['moneda'];
	$cod_moneda = $row['codigo'];
	}
	mysqli_free_result($result0);

		//listado de items
		$result = mysqli_query($link, "select d.pkyItem as codigo, d.fldName as item, b.fldName as tipo, c.fldName as unidad, d.codFamily as cod_familia, d.codSubFamily as cod_subfamilia, d.codGroup as cod_grupo, d.codSubGroup as cod_subgrupo, d.fldFactoryKey as cod_fabrica
from invItem d, invItemType b, invStorageUnit c
where
$valor_item_ini 
$valor_item_fin 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
d.codType = b.pkyItemType and
d.codMinimumStorageUnit = c.pkyStorageUnit and
d.sysEnabled = 1 and d.sysAuthorized = 1
$valor_orden;");
		
				
		//inicio calculo saldo inicial
		//ingresos
		$result22 = mysqli_query($link, "select fin.codigo as codigo, sum(fin.cant_ing) as cant_ing, 
sum(fin.costo) as costo
from(
select t.codigo as codigo, t.cant_ing as cant_ing,
t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
t.costo as costopre, tc.fldRate as tasa, 
t.costo * tc.fldRate as costo
from(
select a.codItem as codigo, sum(a.fldQuantity) as cant_ing, 
b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
sum(a.fldTotaCost) as costo
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
where 
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_almacen1 
$valor_cuenta_almacen 
$valor_empresa 
$valor_concepto 
$valor_contexto 
a.codItem = d.pkyItem and 
b.fldDate < '$fechaini' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.codType = 1 and 
b.codTargetWarehouse = e.pkyWarehouse and 
b.sysEnabled = 1 and b.sysAuthorized = 1
group by codigo, cod_moneda, cod_tc) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda and
tc.codBaseCurrency = '$cod_moneda' and
tc.codExchangeRate = t.cod_tc
union all
select t.codigo as codigo, t.cant_ing as cant_ing,
t.cod_moneda as cod_moneda, t.cod_tc as cod_tc, 
t.costo as costopre, 1 as tasa, 
t.costo as costo
from(
select a.codItem as codigo, sum(a.fldQuantity) as cant_ing, 
b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc,
sum(a.fldTotaCost) as costo
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e  
where 
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_almacen1 
$valor_cuenta_almacen 
$valor_empresa 
$valor_concepto 
$valor_contexto 
a.codItem = d.pkyItem and  
b.fldDate < '$fechaini' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.codType = 1 and 
b.codTargetWarehouse = e.pkyWarehouse and 
b.sysEnabled = 1 and b.sysAuthorized = 1
group by codigo, cod_moneda, cod_tc) t
where
t.cod_moneda = '$cod_moneda') fin
group by fin.codigo;");
		//egresos
		$result33 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_egr, 
sum(a.fldTotaCost) as costo
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
where 
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_almacen2 
$valor_cuenta_almacen 
$valor_empresa 
$valor_concepto 
$valor_contexto 
a.codItem = d.pkyItem and 
b.fldDate < '$fechaini' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.codType = 2 and 
b.codSourceWarehouse = e.pkyWarehouse and 
b.sysEnabled = 1 and b.sysAuthorized = 1
group by a.codItem;");

		//traspasos
		$result44 = mysqli_query($link, "select a.codItem as codigo, count(1) as nro_traspasos, sum(a.fldExtraCost) as costo_extra
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d
where 
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_empresa 
$valor_concepto 
$valor_contexto 
a.codItem = d.pkyItem and  
b.fldDate < '$fechaini' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.codType = 3 and
b.sysEnabled = 1 and b.sysAuthorized = 1
group by a.codItem;");
		
	if ($almacen != 0) { //if almacen
		//traspasos egresos
		$result444 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost - a.fldExtraCost) as costo
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
where
$valor_item_ini 
$valor_item_fin 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_empresa 
$valor_cuenta_almacen 
$valor_concepto 
$valor_contexto 
a.codItem = d.pkyItem and 
b.codSourceWarehouse = '$almacen' and
b.fldDate < '$fechaini' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.codType = 3 and 
b.codSourceWarehouse = e.pkyWarehouse and 
a.sysEnabled = 1 and a.sysAuthorized = 1
group by a.codItem;");
		//traspasos ingresos
		$result555 = mysqli_query($link, "select a.codItem as codigo, sum(a.fldQuantity) as cant_tras, sum(a.fldTotaCost) as costo
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c, invItem d, invWarehouse e 
where
$valor_item_ini 
$valor_item_fin 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_empresa 
$valor_cuenta_almacen 
$valor_concepto 
$valor_contexto 
a.codItem = d.pkyItem and  
b.codTargetWarehouse = '$almacen' and
b.fldDate < '$fechaini' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.codType = 3 and 
b.codTargetWarehouse = e.pkyWarehouse and 
a.sysEnabled = 1 and a.sysAuthorized = 1
group by a.codItem;");
	}//fin if almacen

$matriz_salini = array();
$i = 1;
while ($row = mysqli_fetch_array($result)) {//while res
	$matriz_salini [$i][0] = $row['cod_fabrica'];
	$matriz_salini [$i][1] = $row['codigo'];
	$matriz_salini [$i][2] = $row['item'];
	$matriz_salini [$i][3] = $row['tipo'];
	$matriz_salini [$i][4] = $row['unidad'];
	$matriz_salini [$i][5] = NULL;//familia
	$matriz_salini [$i][6] = NULL;//sub familia
	$matriz_salini [$i][7] = NULL;//grupo
	$matriz_salini [$i][8] = NULL;//sub grupo
	$matriz_salini [$i][18] = 0;//cantidad saldo inicial
	$matriz_salini [$i][19] = 0;//costo saldo inicial
	$cod_fam = $row['cod_familia'];
	$cod_subfam = $row['cod_subfamilia'];
	$cod_gru = $row['cod_grupo'];
	$cod_subgru = $row['cod_subgrupo'];
	//nombre familia
	$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
						from 
						invItemCategory
						where
						pkyItemCategory = '$cod_fam' and 
						sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result3)) {
		$matriz_salini [$i][5] = $row['nombre'];
	}
	mysqli_free_result($result3);
	
	//nombre sub familia
	$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
						from 
						invItemCategory
						where
						pkyItemCategory = '$cod_subfam' and 
						sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result3)) {
		$matriz_salini [$i][6] = $row['nombre'];
	}
	mysqli_free_result($result3);
	
	//nombre grupo
	$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
						from 
						invItemCategory
						where
						pkyItemCategory = '$cod_gru' and 
						sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result3)) {
		$matriz_salini [$i][7] = $row['nombre'];
	}
	mysqli_free_result($result3);
	
	//nombre sub grupo
	$result3 = mysqli_query($link, "select pkyItemCategory as cod, fldName as nombre
						from 
						invItemCategory
						where
						pkyItemCategory = '$cod_subgru' and 
						sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result3)) {
		$matriz_salini [$i][8] = $row['nombre'];
	}
	mysqli_free_result($result3);
	
	$i++;
}//fin while res
$fin = $i - 1;
mysqli_free_result($result);

// nombre del item
if($item != 0) { $nom_item = $matriz_salini [1][2]; }

//ingresos
while ($row = mysqli_fetch_array($result22)) {
	$i = 1;
	$cod_item = $row['codigo'];
	while ($cod_item <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][9] = $row['cant_ing'];
	$matriz_salini [$i][10] = $row['costo'];
}
mysqli_free_result($result22);
//egresos
while ($row = mysqli_fetch_array($result33)) {
	$i = 1;
	$cod_item = $row['codigo'];
	while ($cod_item <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][11] = $row['cant_egr'];
	$matriz_salini [$i][12] = $row['costo'];
}
mysqli_free_result($result33);

//traspasos
while ($row = mysqli_fetch_array($result44)) {
	$i = 1;
	$cod_item = $row['codigo'];
	while ($cod_item <> $matriz_salini [$i][1]) {
		$i++;
	}
	$matriz_salini [$i][13] = $row['costo_extra'];
}
mysqli_free_result($result44);

if ($almacen != 0) {//if almacen 2
	//traspasos egresos
	while ($row = mysqli_fetch_array($result444)) {
		$i = 1;
		$cod_item = $row['codigo'];
		while ($cod_item <> $matriz_salini [$i][1]) {
			$i++;
		}
		$matriz_salini [$i][14] = $row['cant_tras'];
		$matriz_salini [$i][15] = $row['costo'];
	}
	mysqli_free_result($result444);
	
	//traspasos ingresos
	while ($row = mysqli_fetch_array($result555)) {
		$i = 1;
		$cod_item = $row['codigo'];
		while ($cod_item <> $matriz_salini [$i][1]) {
			$i++;
		}
		$matriz_salini [$i][16] = $row['cant_tras'];
		$matriz_salini [$i][17] = $row['costo'];
	}
	mysqli_free_result($result555);
}//fin if almacen 2

$i = 1;
while($i <= $fin) {
	$cantidad_ing = $matriz_salini [$i][9];
	$costo_ing = $matriz_salini [$i][10];
	$cantidad_egr = $matriz_salini [$i][11];
	$costo_egr = $matriz_salini [$i][12];
	$costo_extra_trasp = $matriz_salini [$i][13];
	if ($almacen == 0) {//if almacen 3
		$matriz_salini [$i][18] = $cantidad_ing - $cantidad_egr; //cantidad saldo inicia
		$matriz_salini [$i][19] = $costo_ing - $costo_egr + $costo_extra_trasp; //costo saldo inicial
	} else { 
		$matriz_salini [$i][18] = $cantidad_ing - $cantidad_egr + $matriz_salini [$i][16] - $matriz_salini [$i][14]; //cantidad saldo inicial
		$matriz_salini [$i][19] = $costo_ing - $costo_egr + $matriz_salini [$i][17] - $matriz_salini [$i][15]; //costo saldo inicial
	} //fin almacen 3
	$i++;
}

//fin calculo saldo inicial


//inicio calculo periodo

//para mostrar detalle tipo kardex

if($num_doc == 'Todos') {
	$nom_num_doc = 'Todos';
	$valor_num_doc = '';
} else {
	$nom_num_doc = '%'.$num_doc.'%';
	$valor_num_doc = 'upper(b.fldDocumentNumber) like upper("%'.$num_doc.'%") and ';
}

$result666 = mysqli_query($link, "select t.codigo as codigo, t.item as item, t.cod_familia as cod_familia, t.cod_subfamilia as cod_subfamilia, t.cod_grupo as cod_grupo, t.cod_subgrupo as cod_subgrupo, t.cod_fabrica as cod_fabrica, t.unidad as unidad, t.nro_doc as nro_doc, t.fecha as fecha, t.cod_tipo_mov as cod_tipo_mov, t.tipo_mov as tipo_mov, 
t.concepto as concepto, t.empresa as empresa, t.cod_alm_orig as cod_alm_orig, t.cod_alm_dest as cod_alm_dest,t.almacen_orig as almacen_orig, t.almacen_dest as almacen_dest, t.cantidad as cantidad, 
t.costo_pre * tc.fldRate as costo, t.cod_det as cod_det, t.cod_mov as cod_mov, t.costo_extra as costo_extra, 
t.com_padre as com_padre, t.cod_padre as cod_padre, t.glosa as glosa, t.cod_empresa as cod_empresa
from (
select a.codItem as codigo, d.fldName as item, d.codFamily as cod_familia, d.codSubFamily as cod_subfamilia, d.codGroup as cod_grupo, d.codSubGroup as cod_subgrupo, d.fldFactoryKey as cod_fabrica, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, b.codType as cod_tipo_mov, c.fldName as tipo_mov, 
e.fldName as concepto, f.fldName as empresa, b.codSourceWarehouse as cod_alm_orig, b.codTargetWarehouse as cod_alm_dest, null as almacen_orig, g.fldName as almacen_dest, a.fldQuantity as cantidad, a.fldTotaCost as costo_pre, b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codSupplier as cod_empresa
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, agnCompany f, invWarehouse g,
invStorageUnit i
where
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_num_doc 
a.codItem = d.pkyItem and
b.codType = 1 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSupplier = f.pkyCompany and
b.codTargetWarehouse = g.pkyWarehouse and 
$valor_almacen1 
$valor_cuenta_almacen2 
$valor_empresa 
$valor_concepto 
$valor_contexto 
b.fldDate >= '$fechaini' and
b.fldDate <= '$fechafin' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda and
tc.codBaseCurrency = '$cod_moneda' and
tc.codExchangeRate = t.cod_tc
union all
select t.codigo as codigo, t.item as item, t.cod_familia as cod_familia, t.cod_subfamilia as cod_subfamilia, t.cod_grupo as cod_grupo, t.cod_subgrupo as cod_subgrupo, t.cod_fabrica as cod_fabrica, t.unidad as unidad, 
t.nro_doc as nro_doc, t.fecha as fecha, t.cod_tipo_mov as cod_tipo_mov, t.tipo_mov as tipo_mov, 
t.concepto as concepto, t.empresa as empresa, t.cod_alm_orig as cod_alm_orig, t.cod_alm_dest as cod_alm_dest, t.almacen_orig as almacen_orig, t.almacen_dest as almacen_dest, t.cantidad as cantidad, 
t.costo_pre as costo, t.cod_det as cod_det, t.cod_mov as cod_mov, t.costo_extra as costo_extra, 
t.com_padre as com_padre, t.cod_padre as cod_padre, t.glosa as glosa, t.cod_empresa as cod_empresa
from (
select a.codItem as codigo, d.fldName as item, d.codFamily as cod_familia, d.codSubFamily as cod_subfamilia, d.codGroup as cod_grupo, d.codSubGroup as cod_subgrupo, d.fldFactoryKey as cod_fabrica, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, b.codType as cod_tipo_mov, c.fldName as tipo_mov, 
e.fldName as concepto, f.fldName as empresa, b.codSourceWarehouse as cod_alm_orig, b.codTargetWarehouse as cod_alm_dest, null as almacen_orig, g.fldName as almacen_dest, a.fldQuantity as cantidad, a.fldTotaCost as costo_pre, b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codSupplier as cod_empresa 
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, agnCompany f, invWarehouse g,
invStorageUnit i
where
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_num_doc 
a.codItem = d.pkyItem and
b.codType = 1 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSupplier = f.pkyCompany and
b.codTargetWarehouse = g.pkyWarehouse and 
$valor_almacen1 
$valor_cuenta_almacen2 
$valor_empresa 
$valor_concepto 
$valor_contexto 
b.fldDate >= '$fechaini' and
b.fldDate <= '$fechafin' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1) t
where
t.cod_moneda = '$cod_moneda'

union all

select a.codItem as codigo, d.fldName as item, d.codFamily as cod_familia, d.codSubFamily as cod_subfamilia, d.codGroup as cod_grupo, d.codSubGroup as cod_subgrupo, d.fldFactoryKey as cod_fabrica, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, b.codType as cod_tipo_mov, c.fldName as tipo_mov, 
e.fldName as concepto, null as empresa, b.codSourceWarehouse as cod_alm_orig, b.codTargetWarehouse as cod_alm_dest, g.fldName as almacen_orig, null as almacen_dest, a.fldQuantity * (-1) as cantidad, a.fldTotaCost * (-1) as costo, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codSupplier as cod_empresa  
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, invWarehouse g, invStorageUnit i
where
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_num_doc 
a.codItem = d.pkyItem and
b.codType = 2 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSourceWarehouse = g.pkyWarehouse and 
$valor_almacen2 
$valor_cuenta_almacen2 
$valor_empresa 
$valor_concepto 
$valor_contexto 
b.fldDate >= '$fechaini' and
b.fldDate <= '$fechafin' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1

union all

select a.codItem as codigo, d.fldName as item, d.codFamily as cod_familia, d.codSubFamily as cod_subfamilia, d.codGroup as cod_grupo, d.codSubGroup as cod_subgrupo, d.fldFactoryKey as cod_fabrica, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, b.codType as cod_tipo_mov, c.fldName as tipo_mov, 
e.fldName as concepto, null as empresa, b.codSourceWarehouse as cod_alm_orig, b.codTargetWarehouse as cod_alm_dest, g.fldName as almacen_orig, h.fldName as almacen_dest, a.fldQuantity as cantidad, a.fldTotaCost as costo, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codSupplier as cod_empresa 
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, invWarehouse g, 
invWarehouse h, invStorageUnit i
where
$valor_item_ini 
$valor_item_fin  
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_num_doc 
a.codItem = d.pkyItem and
b.codType = 3 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSourceWarehouse = g.pkyWarehouse and
b.codTargetWarehouse = h.pkyWarehouse and 
$valor_almacen3 
$valor_cuenta_almacen2 
$valor_empresa 
$valor_concepto 
$valor_contexto 
b.fldDate >= '$fechaini' and
b.fldDate <= '$fechafin' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1
$valor_orden2;");


$mat_det = array();
$i = 1;
while ($row = mysqli_fetch_array($result666)) {//while det
	
$mat_det[$i][1] = $row['codigo'];
$mat_det[$i][2] = $row['cod_fabrica'];
$mat_det[$i][3] = $row['item'];
$mat_det[$i][4] = $row['fecha'];
$mat_det[$i][5] = $row['cod_mov'];
$mat_det[$i][6] = $row['nro_doc'];
$mat_det[$i][7] = $row['tipo_mov'];
$mat_det[$i][8] = $row['concepto'];
$mat_det[$i][9] = $row['almacen_orig'];
$mat_det[$i][10] = $row['almacen_dest'];
$mat_det[$i][11] = 0;//cantidad saldo inicial
$mat_det[$i][12] = 0;//costo saldo inicial
$mat_det[$i][13] = 0;//costo unitario
$mat_det[$i][14] = 0;//cantidad ingreso
$mat_det[$i][15] = 0;//costo ingreso
$mat_det[$i][16] = 0;//cantidad egreso
$mat_det[$i][17] = 0;//costo egreso
$mat_det[$i][18] = 0;//cantidad saldo
$mat_det[$i][19] = 0;//costo saldo
$mat_det[$i][20] = $row['glosa'];
$mat_det[$i][21] = $row['cod_empresa'];
$mat_det[$i][22] = $row['empresa'];

if($row['cod_tipo_mov'] == 1) {
	$mat_det[$i][13] = $row['costo'] / $row['cantidad'];//costo unitario
	$mat_det[$i][14] = $row['cantidad'];//cantidad ing
	$mat_det[$i][15] = $row['costo'];//costo ing
}

if($row['cod_tipo_mov'] == 2) {
	$mat_det[$i][13] = $row['costo'] / $row['cantidad'];//costo unitario
	$mat_det[$i][16] = $row['cantidad'] * -1;//cantidad egr
	$mat_det[$i][17] = $row['costo'] * -1;//costo egr
}

if($row['cod_tipo_mov'] == 3 && $almacen == 0) {//if tipo 3
	$mat_det[$i][13] = $row['costo'] / $row['cantidad'];//costo unitario
	$mat_det[$i][14] = $row['cantidad'];//cantidad ing
	$mat_det[$i][15] = $row['costo'];//costo ing
	
	$mat_det[$i][16] = $row['cantidad'];//cantidad egr
	$mat_det[$i][17] = $row['costo'] - $row['costo_extra'];//costo egr
}//fin if tipo 3 
if($row['cod_tipo_mov'] == 3 && $almacen != 0) {//if tipo 31
	if($almacen == $row['cod_alm_orig']) {
		$mat_det[$i][13] = ($row['costo'] - $row['costo_extra']) / $row['cantidad'];//costo unitario
		$mat_det[$i][16] = $row['cantidad'];//cantidad egr
		$mat_det[$i][17] = $row['costo'] - $row['costo_extra'];//costo egr
	}
	if($almacen == $row['cod_alm_dest']) {
		$mat_det[$i][13] = $row['costo'] / $row['cantidad'];//costo unitario
		$mat_det[$i][14] = $row['cantidad'];//cantidad ing
		$mat_det[$i][15] = $row['costo'];//costo ing
	}
	
}//fin if tipo 31
$i++;

}//fin while det
mysqli_free_result($result666);

$fin_det = $i - 1;	
//fin calculo periodo


		?>
<?php if($ma == 1) {//if 13, muestra solo una vez por la iteracion de almacenes ?>
<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>Inventario Valorado</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 inicial: </b><?php echo $nom_item_ini; ?></TD>
        <TD width="25%"><b>Item final: </b><?php echo $nom_item_fin; ?></TD>
        <TD width="25%"><b>Almac&eacute;n: </b><?php echo $nom_almacen; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></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>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Concepto: </b><?php echo $nom_concepto; ?></TD>
        <TD><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        <TD><b>Mostrar solo cantidades: </b><?php echo $nom_mostrar_cant; ?></TD>
        </TR>
        <TR>
        <TD><b>Mostrar todos los almacenes: </b><?php echo $nom_mostrar_todo_alm; ?></TD>
        <TD><b>Items agrupados: </b><?php echo $nom_agrupar_items; ?></TD>
        <TD><b>Nro. Documento: </b><?php echo $nom_num_doc; ?></TD>
        <TD><b>Mostrar Lotes: </b><?php echo $nom_mostrar_lotes; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Empresa: </b><?php echo $nom_empresa; ?></TD>
		<TD colspan="2"><b>Cuenta Contable del Almac&eacute;n: </b><?php echo $nom_cuenta_almacen; ?></TD>
		</TR>
        <?php if($mostrar_cant == 0) { ?>
        <TR>
        <TD colspan="2"><b>Expresado en: </b><?php echo $nom_moneda; ?></TD>
        <TD colspan="2"><b>Valorado tambi&eacute;n en: </b><?php echo $texto_otra_moneda; ?></TD>
        </TR>
		<?php } ?>
        
    </table>

</td>

<td valign="top" width="150">

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

</tr>
</table>
<br /> 
<table border="1" align="center" cellpadding="2" width="100%">
	<thead>
	<TR> 
	<TD align="center"><b>Cod.</b></TD>
    <?php if($codfab_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Cod. Fab.</b></TD>
    <?php } ?>
    <TD align="center"><b>Item</b></TD>
    <?php if($familia_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Familia</b></TD>
    <?php } ?>
    <?php if($subfamilia_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Sub Familia</b></TD>
    <?php } ?>
    <?php if($grupo_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Grupo</b></TD>
    <?php } ?>
    <?php if($subgrupo_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Sub Grupo</b></TD>
    <?php } ?>
    <?php if($tipo_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Tipo</b></TD>
    <?php } ?>
    <?php if($umen_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Uni. Men.</b></TD>
    <?php } ?>
    <TD align="center"><b>Cod. Mov.</b></TD>
    <TD align="center"><b>Nro. Doc.</b></TD>
    <TD align="center"><b>Tipo de Mov.</b></TD>
    <TD align="center"><b>Concepto</b></TD>
	<TD align="center"><b>Empresa</b></TD>
     <?php if($glosa_ver == 1) { $nro_col++; ?>
    <TD align="center"><b>Glosa</b></TD>
    <?php } ?>
    <TD align="center"><b>Alm. Origen</b></TD>
    <TD align="center"><b>Alm. Destino</b></TD>
    <TD align="center"><b>Cant. Saldo Inicial</b></TD>
    <?php if($mostrar_cant == 0) { ?>
    <TD align="center"><b>Costo Saldo Inicial</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <?php } ?>
    <TD align="center"><b>Cant. Ingreso</b></TD>
    <?php if($mostrar_cant == 0) { ?>
	<TD align="center"><b>Costo Ingreso</b></TD>
    <?php } ?>
    <TD align="center"><b>Cant. Egreso</b></TD>
    <?php if($mostrar_cant == 0) { ?>
	<TD align="center"><b>Costo Egreso</b></TD>
    <?php } ?>
	<TD align="center"><b>Cant. Saldo</b></TD>
    <?php if($mostrar_cant == 0) { ?>
    <TD align="center"><b>Costo Saldo</b></TD>
    
    <?php if($otra_moneda != 0){ ?>
    <TD align="center"><b>Costo Saldo en <?php echo $nom_otra_moneda; ?></b></TD>
    <?php } ?>
    <?php } ?>
    </TR>
    </thead>
    <tbody class="marcafila">
 <?php } //fin if 13 ?>
  <?php
  $color = 2;
  $suma_total_cant_salini = 0;
  $suma_total_costo_salini = 0;
  $suma_total_cant_ing = 0;
  $suma_total_costo_ing = 0;
  $suma_total_cant_egr = 0;
  $suma_total_costo_egr = 0;
  $suma_total_cantidad = 0;
  $suma_total_costo = 0;
  $suma_total_otra_moneda = 0;
 
  $j = 1;
  $i = 1;
  
  while ($j <= $fin) { //while j
	
	$mos_sal = 1;
	$total_cant_si = 0;
	$total_costo_si = 0;
	//echo $matriz_salini [$j][1] .' == '. $mat_det [$i][1] .'<br>';
	while($matriz_salini [$j][1] == $mat_det [$i][1] && $i <= $fin_det) { //while i
	
	$cod_mov = $mat_det[$i][5];
	if($color % 2 == 0) { //if color
	printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	} else {
	printf("<tr><td align='center'>%s</td>", $matriz_salini [$j][1]);//cod
	}//fin if color
	if($codfab_ver == 1) {
		printf("<td align='center'>%s</td>", $matriz_salini [$j][0]);//cod fabrica
	}
	printf("<td align='left'>%s</td>", $matriz_salini [$j][2]);//item
	if($familia_ver == 1) {
		printf("<td>%s</td>", $matriz_salini [$j][5]);//familia
	}
	if($subfamilia_ver == 1) {
		printf("<td>%s</td>", $matriz_salini [$j][6]);//sub familia
	}
	if($grupo_ver == 1) {
		printf("<td>%s</td>", $matriz_salini [$j][7]);//grupo
	}
	if($subgrupo_ver == 1) {
		printf("<td>%s</td>", $matriz_salini [$j][8]);//sub grupo
	}
	if($tipo_ver == 1) {
		printf("<td>%s</td>", $matriz_salini [$j][3]);//tipo
	}
	if($umen_ver == 1) {
		printf("<td>%s</td>", $matriz_salini [$j][4]);//unidad menor
	}
	
	printf("<td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov&showBatch=$mostrar_lotes&printAccountEntry=0&user=$usuario' title='Nota de Movimiento de Mercaderia'>%s</a></td>", $cod_mov);//cod mov merc
	printf("<td align='center'>%s</td>", $mat_det[$i][6]);//nro doc
	printf("<td align='left'>%s</td>", $mat_det[$i][7]);//tipo de mov
	printf("<td align='left'>%s</td>", $mat_det[$i][8]);//concepto

	//empresa nombre 
	if($mat_det[$i][22] == null && $mat_det[$i][21] != null) {
		$cod_empresa_query = $mat_det[$i][21];
		$result2 = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
					from agnCompany
					where
					pkyCompany = '$cod_empresa_query';");
		while ($row = mysqli_fetch_array($result2)) {
			$mat_det[$i][22] = $row['empresa'];
		}
		mysqli_free_result($result2);
	}
	printf("<td align='left'>%s</td>", $mat_det[$i][22]);//empresa

	if($glosa_ver == 1) {
	printf("<td align='left'>%s</td>", $mat_det[$i][20]);//glosa
	}
	printf("<td align='left'>%s</td>", $mat_det[$i][9]);//almacen orig
	printf("<td align='left'>%s</td>", $mat_det[$i][10]);//almacen dest
	if($mos_sal == 1) {//if mos
		printf("<td align='right'>%s</td>", number_format($matriz_salini[$j][18],$n_cantidad));//cant saldo ini
		if($mostrar_cant == 0) {
		printf("<td align='right'>%s</td>", number_format($matriz_salini[$j][19],$n_decimales));//costo saldo ini
		}
		$total_cant_si = $matriz_salini[$j][18] + $mat_det[$i][14] - $mat_det[$i][16];
		$total_costo_si = $matriz_salini[$j][19] + $mat_det[$i][15] - $mat_det[$i][17];
		//suma los saldos iniciales
		$suma_total_cant_salini = $suma_total_cant_salini + $matriz_salini[$j][18];
		$suma_total_costo_salini = $suma_total_costo_salini + $matriz_salini[$j][19];
		$mos_sal = 0;
	} else {//else if mos
		printf("<td>&nbsp;</td>");//cant saldo inicial
		if($mostrar_cant == 0) {
		printf("<td>&nbsp;</td>");//costo saldo inicial
		}
		$total_cant_si = $total_cant_si + $mat_det[$i][14] - $mat_det[$i][16];
		$total_costo_si = $total_costo_si + $mat_det[$i][15] - $mat_det[$i][17];
	}//fin if mos
	
	if($mostrar_cant == 0) {
	printf("<td align='right'>%s</td>", number_format($mat_det[$i][13],$n_decimales));//costo unitario
	}
	printf("<td align='right'>%s</td>", number_format($mat_det[$i][14],$n_cantidad));//cantidad ingresos
	if($mostrar_cant == 0) {
	printf("<td align='right'>%s</td>", number_format($mat_det[$i][15],$n_decimales));//costo ingresos
	}
	printf("<td align='right'>%s</td>", number_format($mat_det[$i][16],$n_cantidad));//cantidad egresos
	if($mostrar_cant == 0) {
	printf("<td align='right'>%s</td>", number_format($mat_det[$i][17],$n_decimales));//costo egresos
	}
	printf("<td align='right'>%s</td>", number_format($total_cant_si,$n_cantidad));//cantidad saldo

	if($mostrar_cant == 0) { //if mostrar_cant
		if($otra_moneda != 0){
			printf("<td align='right'>%s</td>", number_format($total_costo_si,$n_decimales));//costo saldo
			$total_otra_moneda = $total_costo_si * $tasa_tc;
			printf("<td align='right'>%s</td>", number_format($total_otra_moneda,$n_decimales));//costo otra moneda
		} else {
			printf("<td align='right'>%s</td>", number_format($total_costo_si,$n_decimales));//costo saldo
		}
	} //fin if mostrar_cant
	echo '</tr>';
	
	$suma_total_cant_ing = $suma_total_cant_ing + $mat_det[$i][14];
	$suma_total_costo_ing = $suma_total_costo_ing + $mat_det[$i][15];
	$suma_total_cant_egr = $suma_total_cant_egr + $mat_det[$i][16];
	$suma_total_costo_egr = $suma_total_costo_egr + $mat_det[$i][17];
	$suma_total_cantidad = $suma_total_cantidad + $total_cant_si;
	$suma_total_costo = $suma_total_costo + $total_costo_si;
	$suma_total_otra_moneda = $suma_total_otra_moneda + $total_otra_moneda;
	
	$color++;
	$i++;
	}//fin while i
	$j++;
}//fin while j

//acumulamos para el total de todos los almacenes
	$suma_total_cant_salini2 = $suma_total_cant_salini2 + $suma_total_cant_salini;
	$suma_total_costo_salini2 = $suma_total_costo_salini2 + $suma_total_costo_salini;
	$suma_total_cant_ing2 = $suma_total_cant_ing2 + $suma_total_cant_ing;
	$suma_total_costo_ing2 = $suma_total_costo_ing2 + $suma_total_costo_ing;
	$suma_total_cant_egr2 = $suma_total_cant_egr2 + $suma_total_cant_egr;
	$suma_total_costo_egr2 = $suma_total_costo_egr2 + $suma_total_costo_egr;
	$suma_total_cant2 = $suma_total_cant2 + $suma_total_cantidad;
	$suma_total_costo2 = $suma_total_costo2 + $suma_total_costo;
	$suma_total_otra_moneda2 = $suma_total_otra_moneda2 + $suma_total_otra_moneda; 

	//controlar la suma para saber si se muestra sumas con cero
	$suma_para_mostar_cero = $suma_total_cant_salini + $suma_total_costo_salini + $suma_total_cant_ing + $suma_total_costo_ing + $suma_total_cant_egr + $suma_total_costo_egr + $suma_total_trasp + $suma_total_costo_extra_trasp + $suma_total_trasp_ing + $suma_total_costo_trasp_ing + $suma_total_costo_extra_trasp + $suma_total_trasp_egr + $suma_total_costo_trasp_egr + $suma_total_cant_periodo + $suma_total_costo_periodo;

?>

<?php if($suma_para_mostar_cero != 0) { //if muestra cero ?>
	<?php if($mostrar_todo_alm == 1) { //if mostrar alm 1 ?>
	<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total <?php echo $mat_alm[$ma][2]; ?></b>
	<?php } else { ?>
	<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total</b>
	<?php } //fin if mostrar alm 1 ?>

	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_salini,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_salini,$n_decimales)); ?>
	</td><td>&nbsp;
	<?php } ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_ing,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_ing,$n_decimales)); ?>
	<?php } ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_egr,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_egr,$n_decimales)); ?>
	<?php } ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cantidad,$n_cantidad)); ?>
	<?php if($mostrar_cant == 0) { //if cant 01 ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo,$n_decimales)); ?>
	<?php if($otra_moneda != 0){ //if mon 01 ?>
	</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_otra_moneda,$n_decimales)); ?>
	<?php $total_otra_moneda = 0; ?>
	<?php } //fin if mon 01 ?>
	<?php } //fin if cant 01 ?>
	</td></tr>
<?php } //fin if muestra cero ?>
<?php } //fin for repite almacen ?>

<?php if($mostrar_todo_alm == 1) { //if mostrar alm 1.1 ?>
<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_col; ?>"><b>Total Almacenes</b>

</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_salini2,$n_cantidad)); ?>
<?php if($mostrar_cant == 0) { ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_salini2,$n_decimales)); ?>
</td><td>&nbsp;
<?php } ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_ing2,$n_cantidad)); ?>
<?php if($mostrar_cant == 0) { ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_ing2,$n_decimales)); ?>
<?php } ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant_egr2,$n_cantidad)); ?>
<?php if($mostrar_cant == 0) { ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo_egr2,$n_decimales)); ?>
<?php } ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_cant2,$n_cantidad)); ?>
<?php if($mostrar_cant == 0) { //if cant 02 ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_costo2,$n_decimales)); ?>
<?php if($otra_moneda != 0){ //if mon 02 ?>
</td><td align="right"><?php printf("<b>%s</b>", number_format($suma_total_otra_moneda2,$n_decimales)); ?>
<?php } //fin if mon 02 ?>
<?php } //fin if cant 02 ?>
<?php } //fin if mostrar alm 1.1 ?>
</tbody>
</table>
<?php
 
 }//fin if agrupar items 3

} //fin if 2






// inicio muestra detalle

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

//valor del codigo del ultimo tipo de cambio
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafindet' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc = $row['tc'];
	}
	mysqli_free_result($resultom);

//tipo de cambio para la cabecera
$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$ultimo_tc' and 
sysEnabled = 1 and sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

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

//almacen
if ($almacen_det == 0) { // if 2.3
		$nom_almacen_det = 'Todos';
		$valor_almacen_det1 = ' ';
		$valor_almacen_det2 = ' ';
		$valor_almacen_det3 = ' ';
	} else {
		$valor_almacen_det1 = ' b.codTargetWarehouse = ' .$almacen_det. ' and ';
		$valor_almacen_det2 = ' b.codSourceWarehouse = ' .$almacen_det. ' and ';
		$valor_almacen_det3 = ' (b.codTargetWarehouse = ' .$almacen_det. ' or b.codSourceWarehouse = ' .$almacen_det. ') and ';
		
		//nombre de almacen
		$result2 = mysqli_query($link, "select pkyWarehouse, fldName 
					   			from invWarehouse 
					   			where 
								pkyWarehouse = '$almacen_det' and
								sysEnabled = 1 and sysAuthorized = 1;");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_almacen_det = $row['fldName'];
		}
		mysqli_free_result($result2);
	} //fin if 2.3

if ($concepto_det == 0) { // if 2.4
		$nom_concepto_det = 'Todos';
		$valor_concepto_det = ' ';
	} else {
		//nombre concepto
		$result2 = mysqli_query($link, "select a.pkyItemMovementTypeConcept as cod_concepto, a.fldName as concepto, b.fldName as tipo
					from invItemMovementTypeConcept a, invItemMovementType b 
					where 
					a.pkyItemMovementTypeConcept = '$concepto_det' and
					a.codItemMovementType = b.pkyItemMovementType;");
		while ($row = mysqli_fetch_array($result2)) {
			$nom_concepto_det = $row['concepto'].' - '.$row['tipo'];
		}
		mysqli_free_result($result2);
		$valor_concepto_det = ' b.codTypeConcept = ' .$concepto_det. ' and ';
	} //fin if 2.4


//ingreso, egreso y traspaso
if ($cod_tipo_det == 0) { // if 2.5
	$valor_tipo_det = ' ';
} else {
	if ($cod_tipo_det == 1 || $cod_tipo_det == 2 || $cod_tipo_det == 3) { // if 2.5.1
		$valor_tipo_det = ' where fin.cod_tipo = ' .$cod_tipo_det;
	}//fin if 2.5.1
	if ($cod_tipo_det == 4) { // if 2.5.2
		$valor_almacen_det3 = ' b.codTargetWarehouse = ' .$almacen_det. ' and ';
		$valor_tipo_det = ' where fin.cod_tipo = 3 ';
	}//fin if 2.5.2
	if ($cod_tipo_det == 5) { // if 2.5.3
		$valor_almacen_det3 = ' b.codSourceWarehouse = ' .$almacen_det. ' and ';
		$valor_tipo_det = ' where fin.cod_tipo = 3 ';
	}//fin if 2.5.3
	
}//fin if 2.5


//moneda
	$result0 = mysqli_query($link, "select a.pkyCurrency as codigo, a.fldName as moneda
from actCurrency a, invInventoryConfig b
where
a.pkyCurrency = b.codCurrency and
a.sysEnabled = 1 and a.sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($result0)) {
	$nom_moneda = $row['moneda'];
	$cod_moneda = $row['codigo'];
	}
	mysqli_free_result($result0);
	
if($otra_monedadet != 0){ //if otra moneda

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

//valor del codigo del ultimo tipo de cambio
$resultom = mysqli_query($link, "SELECT T2.pkyExchangeRate as tc FROM 
(SELECT fldDate, MAX(fldTime) AS fldTime FROM actExchangeRate WHERE fldExclusive = '0' GROUP BY fldDate) as T1,
actExchangeRate T2 
WHERE 
T1.fldDate = (SELECT MAX(fldDate) FROM actExchangeRate WHERE fldDate <= '$fechafindet' AND fldExclusive = '0') AND 
T2.fldDate = T1.fldDate AND 
T2.fldTime = T1.fldTime AND 
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resultom)) {
	$ultimo_tc = $row['tc'];
	}
	mysqli_free_result($resultom);

if($cod_moneda > $otra_monedadet) {//if original > otra 
//valores de conversion tipo de cambio
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc' and
codBaseCurrency = '$otra_monedadet' and
codTargetCurrency = '$cod_moneda' and
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resulttc)) {
	$codigo_tc = $row['codigotc'];
	$moneda_base = $row['monedabase'];
	$moneda_cambio = $row['monedacambio'];
	$tasa_tc = $row['tc'];
	//$tasa_tc_valor = $tasa_tc;
	}
	mysqli_free_result($resulttc);
} else {//else if original > otra 
$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
from
actExchangeRateDetail
where
codExchangeRate = '$ultimo_tc' and
codBaseCurrency = '$cod_moneda' and
codTargetCurrency = '$otra_monedadet' and
sysEnabled = 1 AND sysAuthorized = 1;");
while ($row = mysqli_fetch_array($resulttc)) {
	$codigo_tc = $row['codigotc'];
	$moneda_base = $row['monedabase'];
	$moneda_cambio = $row['monedacambio'];
	$tasa_tc = $row['tc'];
	//$tasa_tc_valor = $tasa_tc;
	$tasa_tc = 1 / $tasa_tc;
	}
	mysqli_free_result($resulttc);	
}//fin if original > otra 


}//fin if otra moneda

if ($cuenta_almacen_det == 0) { // if 2.3.1
	$nom_cuenta_almacen_det = 'Todos';
	//$valor_cuenta_almacen_det = ' '; //no es necesario pasar la cuenta contable porque en el principal se filtra por almacen, por eso no esta en el query
} else {
	//$valor_cuenta_almacen_det = ' g.codAccount = ' .$cuenta_almacen_det. ' and '; //no es necesario pasar la cuenta contable porque en el principal se filtra por almacen, por eso no esta en el query
	//nombre de la cuenta contable del almacen
	$result2 = mysqli_query($link, "select pkyAccount, fldName 
							   from actAccount 
							   where 
							pkyAccount = '$cuenta_almacen_det' and
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result2)) {
		$nom_cuenta_almacen_det = $row['fldName'];
	}
	mysqli_free_result($result2);
} //fin if 2.3.1

//empresa
if ($empresa_det == 0) { // if 2.3.2
	$nom_empresa_det = 'Todos';
	$valor_empresa_det = ' ';
} else {
	//nombre concepto
	$result2 = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
				from agnCompany
				where
				pkyCompany = '$empresa_det';");
	while ($row = mysqli_fetch_array($result2)) {
		$nom_empresa_det = $row['codigo'].' - '.$row['empresa'];
	}
	mysqli_free_result($result2);
	$valor_empresa_det = ' b.codSupplier = ' .$empresa_det. ' and ';
} //fin if 2.3.2

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

// detalle item
 
 $result = mysqli_query($link, "select a.pkyItem as codigo, a.fldName as item, b.fldName as tipo, c.fldName as unidad, a.fldFactoryKey as cod_fabrica 
from invItem a, invItemType b, invStorageUnit c
where
a.pkyItem = '$itemdet' and
a.codType = b.pkyItemType and
a.codMinimumStorageUnit = c.pkyStorageUnit and
a.sysEnabled = 1 and a.sysAuthorized = 1;");
 
while ($row = mysqli_fetch_array($result)) {
	$coditemdet = $row['codigo'];
	$nomitemdet = $row['item'];
	$uniitemdet = $row['unidad'];
	$coditemfabdet = $row['cod_fabrica'];
}
mysqli_free_result($result);

 $result2 = mysqli_query($link, "select fin.codigo as codigo, fin.item as item, fin.unidad as unidad, fin.nro_doc as nro_doc, fin.fecha as fecha, fin.tipo_mov as tipo_mov, 
fin.concepto as concepto, fin.empresa as empresa, fin.almacen_orig as almacen_orig, 
fin.almacen_dest as almacen_dest, fin.cantidad as cantidad, 
fin.costo as costo, fin.cod_det as cod_det, fin.cod_mov as cod_mov, fin.costo_extra as costo_extra, 
fin.com_padre as papa, fin.cod_padre as cod_papa, fin.glosa as glosa, fin.cod_tipo as cod_tipo, fin.cod_empresa as cod_empresa
from (
select t.codigo as codigo, t.item as item, t.unidad as unidad, 
t.nro_doc as nro_doc, t.fecha as fecha, t.tipo_mov as tipo_mov, 
t.concepto as concepto, t.empresa as empresa, t.almacen_orig as almacen_orig, 
t.almacen_dest as almacen_dest, t.cantidad as cantidad, 
t.costo_pre * tc.fldRate as costo, t.cod_det as cod_det, t.cod_mov as cod_mov, t.costo_extra as costo_extra, 
t.com_padre as com_padre, t.cod_padre as cod_padre, t.glosa as glosa, t.cod_tipo as cod_tipo, t.cod_empresa as cod_empresa
from (
select a.codItem as codigo, d.fldName as item, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, c.fldName as tipo_mov, 
e.fldName as concepto, f.fldName as empresa, null as almacen_orig, 
g.fldName as almacen_dest, a.fldQuantity as cantidad, a.fldTotaCost as costo_pre, 
b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codType as cod_tipo, b.codSupplier as cod_empresa
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, agnCompany f, invWarehouse g, invStorageUnit i
where
a.codItem = '$itemdet' and
a.codItem = d.pkyItem and
b.codType = 1 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSupplier = f.pkyCompany and
b.codTargetWarehouse = g.pkyWarehouse and 
$valor_almacen_det1
$valor_empresa_det  
$valor_concepto_det 
$valor_contexto_det 
b.fldDate >= '$fechainidet' and
b.fldDate <= '$fechafindet' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda and
tc.codBaseCurrency = '$cod_moneda' and
tc.codExchangeRate = t.cod_tc
union all
select t.codigo as codigo, t.item as item, t.unidad as unidad, 
t.nro_doc as nro_doc, t.fecha as fecha, t.tipo_mov as tipo_mov, 
t.concepto as concepto, t.empresa as empresa, t.almacen_orig as almacen_orig, 
t.almacen_dest as almacen_dest, t.cantidad as cantidad, 
t.costo_pre as costo, t.cod_det as cod_det, t.cod_mov as cod_mov, t.costo_extra as costo_extra, 
t.com_padre as com_padre, t.cod_padre as cod_padre, t.glosa as glosa, t.cod_tipo as cod_tipo, t.cod_empresa as cod_empresa
from (
select a.codItem as codigo, d.fldName as item, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, c.fldName as tipo_mov, 
e.fldName as concepto, f.fldName as empresa, null as almacen_orig, 
g.fldName as almacen_dest, a.fldQuantity as cantidad, a.fldTotaCost as costo_pre, 
b.codCurrency as cod_moneda, b.codExchangeRate as cod_tc, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codType as cod_tipo, b.codsupplier as cod_empresa
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, agnCompany f, invWarehouse g, invStorageUnit i
where
a.codItem = '$itemdet' and
a.codItem = d.pkyItem and
b.codType = 1 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSupplier = f.pkyCompany and
b.codTargetWarehouse = g.pkyWarehouse and 
$valor_almacen_det1 
$valor_empresa_det 
$valor_concepto_det 
$valor_contexto_det 
b.fldDate >= '$fechainidet' and
b.fldDate <= '$fechafindet' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1) t
where
t.cod_moneda = '$cod_moneda'

union all

select a.codItem as codigo, d.fldName as item, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, c.fldName as tipo_mov, 
e.fldName as concepto, null as empresa, g.fldName as almacen_orig, 
null as almacen_dest, a.fldQuantity * (-1) as cantidad, a.fldTotaCost * (-1) as costo, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codType as cod_tipo, b.codSupplier as cod_empresa
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, invWarehouse g, invStorageUnit i
where
a.codItem = '$itemdet' and
a.codItem = d.pkyItem and
b.codType = 2 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSourceWarehouse = g.pkyWarehouse and 
$valor_almacen_det2 
$valor_empresa_det 
$valor_concepto_det 
$valor_contexto_det 
b.fldDate >= '$fechainidet' and
b.fldDate <= '$fechafindet' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1

union all

select a.codItem as codigo, d.fldName as item, i.fldName as unidad, 
b.fldDocumentNumber as nro_doc, b.fldDate as fecha, c.fldName as tipo_mov, 
e.fldName as concepto, null as empresa, g.fldName as almacen_orig, 
h.fldName as almacen_dest, a.fldQuantity as cantidad, a.fldTotaCost as costo, a.pkyItemMovementDetail as cod_det, b.pkyItemMovement as cod_mov, a.fldExtraCost as costo_extra, b.fldParentComponent as com_padre, b.cosComponentKey as cod_padre, b.txtDescription as glosa, b.codType as cod_tipo, b.codSupplier as cod_empresa
from
invItemMovementDetail a, invItemMovement b, invItemMovementType c,
invItem d, invItemMovementTypeConcept e, invWarehouse g, invWarehouse h, invStorageUnit i
where
a.codItem = '$itemdet' and
a.codItem = d.pkyItem and
b.codType = 3 and
b.codTypeConcept = e.pkyItemMovementTypeConcept and
d.codMinimumStorageUnit = i.pkyStorageUnit and
b.codSourceWarehouse = g.pkyWarehouse and
b.codTargetWarehouse = h.pkyWarehouse and 
$valor_almacen_det3 
$valor_empresa_det 
$valor_concepto_det 
$valor_contexto_det 
b.fldDate >= '$fechainidet' and
b.fldDate <= '$fechafindet' and
a.codItemMovement = b.pkyItemMovement and
b.codType = c.pkyItemMovementType and
b.sysEnabled = 1 and b.sysAuthorized = 1) fin 
$valor_tipo_det 
order by fin.fecha, fin.cod_det;");

if($mostrar_cant_det == 0) { 
	$titulo_det = ' Valorado';
} else {
	$titulo_det = ' Cantidades';
}

$num_col = 9;
if($empresa_ver_det == 1){ $num_col++; } 
if($glosa_ver_det == 1){ $num_col++; }
if($mostrar_lotes_det == 1){ $num_col++; }

 ?>
<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 Inventario <?php echo $titulo_det; ?></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>Cod. Item: </b><?php echo $coditemdet; ?></TD>
        <TD width="25%"><b>Cod. F&aacute;brica: </b><?php echo $coditemfabdet; ?></TD>
        <TD width="25%"><b>Item: </b><?php echo $nomitemdet; ?></TD>
        <TD width="25%"><b>Unidad Menor: </b><?php echo $uniitemdet; ?></TD>
        </TR>
        <TR>
        <TD><b>Almacen: </b><?php echo $nom_almacen_det; ?></TD>
        <TD><b>Concepto: </b><?php echo $nom_concepto_det; ?></TD>
		<TD><b>Empresa: </b><?php echo $nom_empresa_det; ?></TD>
        <TD><b>De Fecha: </b><?php echo $fechainidet; ?> <b>a Fecha: </b><?php echo $fechafindet; ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Cuenta Contable del Almac&eacute;n: </b><?php echo $nom_cuenta_almacen_det; ?></TD>
		<TD><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
		<TD><b>Expresado en: </b><?php echo $nom_moneda; ?></TD>
        </TR> 
    </table>

</td>

<td valign="top" width="150">

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

</tr>
</table>
<br />  
<table border="1" align="center" cellpadding="2" width="100%">
	<TR BGCOLOR='#ffcccc'> 
 	<TD align="left" colspan="<?php echo $num_col; ?>"><b>Cant. Saldo inicial</b></TD>
    <?php if($otra_monedadet != 0){ ?>
		<?php if($totalcantdet >= 0){ ?>
			<TD align="right"><b><?php echo number_format($totalcantdet,$n_cantidad); ?></b></TD>
			<TD>&nbsp;</TD>
		<?php } else { ?>
			<TD>&nbsp;</TD>
			<TD align="right"><b><?php echo number_format($totalcantdet,$n_cantidad); ?></b></TD>
		<?php } ?>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<?php if($mostrar_cant_det == 0){ ?>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<?php if($almacen_det == 0){ ?>
				<TD>&nbsp;</TD>
				<TD>&nbsp;</TD>
				<TD>&nbsp;</TD>
			<?php } ?>
		<?php } ?>
		</TR>
    <?php } else { ?>
		<?php if($totalcantdet >= 0){ ?>
			<TD align="right"><b><?php echo number_format($totalcantdet,$n_cantidad); ?></b></TD>
			<TD>&nbsp;</TD>
		<?php } else { ?>
			<TD>&nbsp;</TD>
			<TD align="right"><b><?php echo number_format($totalcantdet,$n_cantidad); ?></b></TD>
		<?php } ?>
		<TD>&nbsp;</TD>
		<?php if($mostrar_cant_det == 0){ ?>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<?php if($almacen_det == 0){ ?>
				<TD>&nbsp;</TD>
				<TD>&nbsp;</TD>
			<?php } ?>
		<?php } ?>
		</TR>
    <?php } ?>
    
    <?php if($mostrar_cant_det == 0){ ?>
    
		<TR BGCOLOR='#ffcccc'> 
		<TD align="left" colspan="<?php echo $num_col; ?>"><b>Costo Saldo inicial</b></TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<?php if($almacen_det == 0){ ?>
			<TD>&nbsp;</TD>
		<?php } ?>
		<?php if($otra_monedadet != 0){ ?>
			<TD>&nbsp;</TD>
			<?php if($totalcostodet >= 0){ ?>
				<TD align="right"><b><?php echo number_format($totalcostodet,$n_decimales); ?></b></TD>
				<TD>&nbsp;</TD>
			<?php } else { ?>
				<TD>&nbsp;</TD>
				<TD align="right"><b><?php echo number_format($totalcostodet,$n_decimales); ?></b></TD>
			<?php } ?>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
			<?php if($totalcostodet >= 0){ ?>
				<TD align="right"><b><?php echo number_format($totalcostodet * $tasa_tc,$n_tipocambio); ?></b></TD>
				<TD>&nbsp;</TD>
			<?php } else { ?>
				<TD>&nbsp;</TD>
				<TD align="right"><b><?php echo number_format($totalcostodet * $tasa_tc,$n_tipocambio); ?></b></TD>
			<?php } ?>
			<?php if($almacen_det == 0){ ?>
				<TD>&nbsp;</TD>
				<TD>&nbsp;</TD>
			<?php } ?>
			</TR>
		<?php } else { ?>
			<TD>&nbsp;</TD>
			<?php if($totalcostodet >= 0){ ?>
				<TD align="right"><b><?php echo number_format($totalcostodet,$n_decimales); ?></b></TD>
				<TD>&nbsp;</TD>
			<?php } else { ?>
				<TD>&nbsp;</TD>
				<TD align="right"><b><?php echo number_format($totalcostodet,$n_decimales); ?></b></TD>
			<?php } ?>
			<TD>&nbsp;</TD>
			<?php if($almacen_det == 0){ ?>
				<TD>&nbsp;</TD>
			<?php } ?>
			</TR>			  	
		<?php } ?>
		
    <?php } ?>
    <thead>
 	<TR> 
    <TD align="center"><b>Cod.</b></TD>
    <!--
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Uni. Men.</b></TD>
    -->
    <TD align="center"><b>Nro. Doc.</b></TD>
	<TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center"><b>Tipo de Mov.</b></TD>
    <TD align="center"><b>Concepto</b></TD>
    <?php if($glosa_ver_det == 1){ ?>
    <TD align="center"><b>Glosa</b></TD>
    <?php } ?>
    <?php if($empresa_ver_det == 1){ ?>
    <TD align="center"><b>Empresa</b></TD>
    <?php } ?>
    <TD align="center"><b>Vendedor</b></TD>
    <TD align="center"><b>Alm. Origen</b></TD>
	<TD align="center"><b>Alm. Destino</b></TD>
    <TD align="center"><b>Gen. Por</b></TD>
    <?php if($mostrar_lotes_det == 1) { ?>
    <TD align="center"><b>Lotes</b></TD>
    <?php } ?>
    <TD align="center"><b>Ingreso</b></TD>
	<TD align="center"><b>Egreso</b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD align="center"><b>Traspaso</b></TD>
	<?php } ?>
	<!--<TD align="center"><b>Cant.</b></TD>-->
    <TD align="center"><b>Saldo</b></TD>
    <?php if($mostrar_cant_det == 0){ ?>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo Extra</b></TD>
    <!--<TD align="center"><b>Costo</b></TD>-->
	<TD align="center"><b>Costo Ing.</b></TD>
	<TD align="center"><b>Costo Egr.</b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD align="center"><b>Costo Tra.</b></TD>
	<?php } ?>
	<TD align="center"><b>Costo Saldo</b></TD>
    <?php if($otra_monedadet != 0){ ?>
    <TD align="center"><b>Costo Uni. en <?php echo $nom_otra_moneda; ?></b></TD>
    <TD align="center"><b>Costo Extra en <?php echo $nom_otra_moneda; ?></b></TD>
    <!--<TD align="center"><b>Costo en <?php echo $nom_otra_moneda; ?></b></TD>-->
	<TD align="center"><b>Costo Ing. en <?php echo $nom_otra_moneda; ?></b></TD>
	<TD align="center"><b>Costo Egr. en <?php echo $nom_otra_moneda; ?></b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD align="center"><b>Costo Tra. en <?php echo $nom_otra_moneda; ?></b></TD>
	<?php } ?>
	<TD align="center"><b>Costo Saldo. en <?php echo $nom_otra_moneda; ?></b></TD>
    <?php } ?>
    <?php } ?>
    </TR>
    </thead>
    <tbody class="marcafila">

  <?php
  $color = 2;
  $suma_total_cant = 0;
  $suma_total_costo = 0;
  $suma_periodo_cant = 0;
  $suma_periodo_cant_ing = 0;
  $suma_periodo_cant_egr = 0;
  $suma_periodo_costo = 0;
  $suma_periodo_costo_ing = 0;
  $suma_periodo_costo_egr = 0;
  $suma_periodo_costo_extra = 0;
  $suma_total_costo_otra_moneda = 0;
  $suma_periodo_costo_otra_moneda = 0;
  $suma_periodo_costo_otra_moneda_ing = 0;
  $suma_periodo_costo_otra_moneda_egr = 0;
  $suma_periodo_costo_extra_otra_moneda = 0;
  $acum_otra = 0;
  $suma_saldo = $totalcantdet;
  $suma_saldo_costo = $totalcostodet;
  $suma_saldo_costo_otra_moneda = $totalcostodet * $tasa_tc;
  
  	if ($almacen_det == 0) {//if almacen todos
		while ($row = mysqli_fetch_array($result2)) { //while
			//para enlazar al que genero el asiento
			$papa_componente = $row['papa'];
			$papa_codigo = $row['cod_papa'];
			$usuario = $usuario_det;
			include "../../generadopor.php";
			
			$cod_mov_det = $row['cod_mov'];	
			$cod_det_det = $row['cod_det'];
			$cod_notav = $row['cod_papa'];
			$almacen_origen = $row['almacen_orig'];
			$almacen_destino = $row['almacen_dest'];
			$cantidad_ = $row['cantidad'];
			$cod_tipo_movimiento = $row['cod_tipo'];
			$tipo_movimiento = $row['tipo_mov'];
			$costo_ = $row['costo'];
			$costo_extra = $row['costo_extra'];	
			$empresa2 = $row['empresa'];
			$cod_empresa2 = $row['cod_empresa'];	
			
			if($color % 2 == 0) { //if color
			printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_det&showBatch=$mostrar_lotes_det&printAccountEntry=0&user=$usuario_det' title='Nota de Movimiento de Mercaderia'>%s</a></td>", $row['cod_mov']);//cod mov merc
			} else {
			printf("<tr><td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_det&showBatch=$mostrar_lotes_det&printAccountEntry=0&user=$usuario_det' title='Nota de Movimiento de Mercaderia'>%s</a></td>", $row['cod_mov']);//cod mov merc
			}//fin if color
			//printf("<td align='left'>%s</td>", $row['item']);//item
			//printf("<td align='left'>%s</td>", $row['unidad']);//unidad
			printf("<td align='center'>%s</td>", $row['nro_doc']);//nro doc
			printf("<td align='right'>%s</td>", $row['fecha']);//fecha
			printf("<td>%s</td>", $row['tipo_mov']);//tipo movimiento
			printf("<td>%s</td>", $row['concepto']);//concepto
			
			if($glosa_ver_det == 1){
				printf("<td>%s</td>", $row['glosa']);//glosa
			}
			if($empresa_ver_det == 1){ //if empresa2
				
				if($empresa2 == null && $cod_empresa2 != null) {
					$result2 = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
								from agnCompany
								where
								pkyCompany = '$cod_empresa2';");
					while ($row = mysqli_fetch_array($result2)) {
						$empresa2 = $row['empresa'];
					}
					mysqli_free_result($result2);
				}

				printf("<td>%s</td>", $empresa2);//empresa
			} //fin if empresa2
				
			if(strcmp($cod_notav,'ComponentSalesNote') == 0) {
				$resultvendedor = mysqli_query($link, "select b.pkyPerson as codigo, case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor
				from slsSalesNote a, agnPerson b
				where
				a.pkySalesNote = '$cod_notav' and 
				a.codSeller = b.pkyPerson;");
				
				while ($row = mysqli_fetch_array($resultvendedor)) {
				$cod_vendedor = $row['codigo'];
				$nom_vendedor = $row['vendedor'];
				}
				mysqli_free_result($resultvendedor);
			} else {
				$nom_vendedor = NULL;
			}
			printf("<td>%s</td>", $nom_vendedor);//vendedor
			printf("<td>%s</td>", $almacen_origen);//almacen origen
			printf("<td>%s</td>", $almacen_destino);//almacen destino
			printf("<td align='center'>%s</td>", $papa_enlace);//enlace papa
			
			if($mostrar_lotes_det == 1){//if muestra_lote1
				
				$suma_cant_lote = 0;
				$result4 = mysqli_query($link, "select a.codBatch as cod_lote, a.fldID as id_lote, case when a.codType = 1 then a.fldQuantity else a.fldQuantity * -1 end as cant_mov, a.fldExpirationDate as fecha_exp, a.fldPriority as prioridad, a.codType as cod_tipo
				from invItemMovementDetailBatch a
				where
				a.codItemMovementDetail = '$cod_det_det' and 
				a.codItemMovement = '$cod_mov_det' 
				order by cod_tipo desc;");
						
				//printf("<td>%s<br/>", $row['item']);//nombre item
				echo '<td>';
				//abrir la tabla para los lotes
				echo '<table border="0" align="left" cellpadding="3">
				<TR> 
				<TD align="center"><b>Cod. Lote</b></TD>
				<TD align="center"><b>ID</b></TD>
				<TD align="center"><b>Cantidad</b></TD>
				<TD align="center"><b>Expiraci&oacute;n</b></TD>
				<TD align="center"><b>Prioridad</b></TD>
				</TR>';
				$suma_cant_lote = 0;
				while ($row = mysqli_fetch_array($result4)) { //while
				
				$cod_lote = $row['cod_lote'];
				$id_lote = $row['id_lote'];
				$cant_mov = $row['cant_mov'];
				$fecha_exp = $row['fecha_exp'];
				$prioridad = $row['prioridad'];
				
				printf("<tr><td align='center'>%s</td>", $cod_lote);//cod lote
				printf("<td align='center'>%s</td>", $id_lote);//id lote
				printf("<td align='right'>%s</td>", number_format($cant_mov, $n_cantidad));//cant mov
				printf("<td align='right'>%s</td>", $fecha_exp);//fecha expiracion
				printf("<td align='right'>%s</td></tr>", $prioridad);//prioridad
				if($cod_tipo_movimiento == 3) { //if 0
					if($cant_mov >= 0) {
					$suma_cant_lote = $suma_cant_lote + $cant_mov;
					}
				} else {//else if 0
					$suma_cant_lote = $suma_cant_lote + $cant_mov;
				}//fin if 0
				}//fin while
				mysqli_free_result($result4);
				
				echo "<tr><td>&nbsp;</td><td>&nbsp;</td><td align='right'><HR width='90%' align='right'></td><td>&nbsp;</td><td>&nbsp;</td></tr>";
				echo '<tr><td colspan="2"><b>Total Lotes</b></td><td align="right">'. number_format($suma_cant_lote, $n_cantidad).'</td><td>&nbsp;</td><td>&nbsp;</td></tr>
				</table></td>';
			
			}//fin if muestra_lote1
			
			if ( $tipo_movimiento != 'Traspasos') {
				if ( $cantidad_ >= 0) {
					printf("<td align='right'>%s</td>", number_format($cantidad_,$n_cantidad));//cantidad ingreso
					echo "<td>&nbsp;</td>";
					echo "<td>&nbsp;</td>";
				} else {
					echo "<td>&nbsp;</td>";
					printf("<td align='right'>%s</td>", number_format($cantidad_,$n_cantidad));//cantidad egreso
					echo "<td>&nbsp;</td>";
				}
			} else {
				echo "<td>&nbsp;</td>";
				echo "<td>&nbsp;</td>";
				printf("<td align='right'><font color='#970818'>%s</font></td>", number_format($cantidad_,$n_cantidad));//cantidad traspaso con color
			}
			
			if ( $tipo_movimiento != 'Traspasos') {
				$suma_saldo = $suma_saldo + $cantidad_;
			}
			printf("<td align='right'>%s</td>", number_format($suma_saldo,$n_cantidad));//saldo
			if($mostrar_cant_det == 0) { //if mostrar_cant_det
			
				printf("<td align='right'>%s</td>", number_format($costo_ / $cantidad_,$n_decimales));//costo unitario		 	 
				printf("<td align='right'>%s</td>", number_format($costo_extra,$n_decimales));//costo extra
				if ( $tipo_movimiento != 'Traspasos') {
					if ( $costo_ >= 0) {
						printf("<td align='right'>%s</td>", number_format($costo_,$n_decimales));//costo ingreso
						echo "<td>&nbsp;</td>";
						echo "<td>&nbsp;</td>";
					} else {
						echo "<td>&nbsp;</td>";
						printf("<td align='right'>%s</td>", number_format($costo_,$n_decimales));//costo egreso
						echo "<td>&nbsp;</td>";
					}
				} else {
					echo "<td>&nbsp;</td>";
					echo "<td>&nbsp;</td>";
					printf("<td align='right'><font color='#970818'>%s</font></td>", number_format($costo_,$n_decimales));//costo traspaso con color
				}
				

				if ( $tipo_movimiento != 'Traspasos') {
					$suma_saldo_costo = $suma_saldo_costo + $costo_;
				}
				printf("<td align='right'>%s</td>", number_format($suma_saldo_costo,$n_decimales));//saldo costo
				
				if($otra_monedadet != 0){	
					printf("<td align='right'>%s</td>", number_format($costo_ / $cantidad_ * $tasa_tc,$n_decimales));//costo unitario otra moneda
					printf("<td align='right'>%s</td>", number_format($costo_extra * $tasa_tc,$n_decimales));//costo extra otra moneda
					//printf("<td align='right'>%s</td>", number_format($costo_ * $tasa_tc,$n_decimales));//costo otra moneda
					if ( $tipo_movimiento != 'Traspasos') {
						if ( $costo_ >= 0) {
							printf("<td align='right'>%s</td>", number_format($costo_ * $tasa_tc,$n_decimales));//costo ingreso otra moneda
							echo "<td>&nbsp;</td>";
							echo "<td>&nbsp;</td>";
						} else {
							echo "<td>&nbsp;</td>";
							printf("<td align='right'>%s</td>", number_format($costo_ * $tasa_tc,$n_decimales));//costo egreso otra moneda
							echo "<td>&nbsp;</td>";
						}
					} else {
						echo "<td>&nbsp;</td>";
						echo "<td>&nbsp;</td>";
						printf("<td align='right'><font color='#970818'>%s</font></td>", number_format($costo_ * $tasa_tc,$n_decimales));//costo traspaso con color otra moneda
					}
					
					if ( $tipo_movimiento != 'Traspasos') {
						$suma_saldo_costo_otra_moneda = $suma_saldo_costo_otra_moneda + $costo_ * $tasa_tc;
					}
					printf("<td align='right'>%s</td>", number_format($suma_saldo_costo_otra_moneda,$n_decimales));//saldo costo
				} 
			} //fin if mostrar_cant_det
			echo '</tr>';
				
				if ( $tipo_movimiento != 'Traspasos') { // if traspasos
					//para sumar en ingreso y egreso
					if ( $cantidad_ >= 0) {
						$suma_periodo_cant_ing = $suma_periodo_cant_ing + $cantidad_;
					} else {
						$suma_periodo_cant_egr = $suma_periodo_cant_egr + $cantidad_;
					}
					$suma_periodo_cant = $suma_periodo_cant + $cantidad_;
					
					//para sumar en ingreso y egreso
					if ( $costo_ >= 0) {
						$suma_periodo_costo_ing = $suma_periodo_costo_ing + $costo_;
					} else {
						$suma_periodo_costo_egr = $suma_periodo_costo_egr + $costo_;
					}
					$suma_periodo_costo = $suma_periodo_costo + $costo_;
					$acum_otra = $costo_ * $tasa_tc;

					//$suma_periodo_costo_otra_moneda = $suma_periodo_costo_otra_moneda + $acum_otra;
				
				} else {

					//para sumar en ingreso y egreso
					if ( $costo_ >= 0) {
						$suma_periodo_costo_ing = $suma_periodo_costo_ing + $costo_extra;
					} else {
						$suma_periodo_costo_egr = $suma_periodo_costo_egr + $costo_extra;
					}
					$suma_periodo_costo = $suma_periodo_costo + $costo_extra;
					$acum_otra = $costo_extra * $tasa_tc;
					//$suma_periodo_costo_otra_moneda = $suma_periodo_costo_otra_moneda + $acum_otra;
				} //fin if traspasos

				//para sumar en ingreso y egreso
				if ( $costo_ >= 0) {
					$suma_periodo_costo_otra_moneda_ing = $suma_periodo_costo_otra_moneda_ing + $acum_otra;
				} else {
					$suma_periodo_costo_otra_moneda_egr = $suma_periodo_costo_otra_moneda_egr + $acum_otra;
				}
				$suma_periodo_costo_otra_moneda = $suma_periodo_costo_otra_moneda + $acum_otra;
				$suma_periodo_costo_extra = $suma_periodo_costo_extra + $costo_extra;
				$suma_periodo_costo_extra_otra_moneda = $suma_periodo_costo_extra_otra_moneda + $costo_extra * $tasa_tc;
				$color++;
		}//fin while
		mysqli_free_result($result2);
		$suma_total_cant = $suma_periodo_cant + $totalcantdet;
		$suma_total_costo = $suma_periodo_costo + $totalcostodet;
		$suma_total_costo_otra_moneda = $suma_periodo_costo_otra_moneda + $totalcostodet * $tasa_tc;
	
  	} else {//else almacen todos
	
		while ($row = mysqli_fetch_array($result2)) { //while
			//para enlazar al que genero el asiento
			$papa_componente = $row['papa'];
			$papa_codigo = $row['cod_papa'];
			$usuario = $usuario_det;
			include "../../generadopor.php";
			
			$cod_mov_det = $row['cod_mov'];	
			$cod_det_det = $row['cod_det'];
			$nro_doc_det = $row['nro_doc'];
			$fecha_det = $row['fecha'];
			$tipo_mov_det = $row['tipo_mov'];
			$concepto_det = $row['concepto'];
			$empresa_det_det = $row['empresa'];
			$cod_empresa_det = $row['cod_empresa'];
			if($color % 2 == 0) { //if color
			printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_det&showBatch=$mostrar_lotes_det&printAccountEntry=0&user=$usuario_det' title='Nota de Movimiento de Mercaderia'>%s</a></td>", $cod_mov_det);//cod mov merc
			} else {
			printf("<tr><td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_det&showBatch=$mostrar_lotes_det&printAccountEntry=0&user=$usuario_det' title='Nota de Movimiento de Mercaderia'>%s</a></td>", $cod_mov_det);//cod mov merc
			}//fin if color
			//printf("<td align='left'>%s</td>", $row['item']);//item
			//printf("<td align='left'>%s</td>", $row['unidad']);//unidad
			printf("<td align='center'>%s</td>", $nro_doc_det);//nro doc
			printf("<td align='right'>%s</td>", $fecha_det);//fecha
			printf("<td>%s</td>", $tipo_mov_det);//tipo movimiento
			printf("<td>%s</td>", $concepto_det);//concepto
			if($empresa_ver_det == 1){ //if empresa ver 1
				
				if($empresa_det_det == null && $cod_empresa_det != null) {
					$result2 = mysqli_query($link, "select pkyCompany as codigo, fldName as empresa
								from agnCompany
								where
								pkyCompany = '$cod_empresa_det';");
					while ($row = mysqli_fetch_array($result2)) {
						$empresa_det_det = $row['empresa'];
					}
					mysqli_free_result($result2);
				}
				
				printf("<td>%s</td>", $row['empresa']);//empresa
			} //fin if empresa ver 1

			$cod_notav = $row['cod_papa'];
			$almacen_origen = $row['almacen_orig'];
			$almacen_destino = $row['almacen_dest'];
			$cantidad_ = $row['cantidad'];
			$cod_tipo_movimiento = $row['cod_tipo'];
			$tipo_movimiento = $row['tipo_mov'];
			$costo_ = $row['costo'];
			$costo_extra = $row['costo_extra'];
			
			if(strcmp($row['papa'],'ComponentSalesNote') == 0) {
				$resultvendedor = mysqli_query($link, "select b.pkyPerson as codigo, case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor
				from slsSalesNote a, agnPerson b
				where
				a.pkySalesNote = '$cod_notav' and 
				a.codSeller = b.pkyPerson;");
				
				while ($row = mysqli_fetch_array($resultvendedor)) {
				$cod_vendedor = $row['codigo'];
				$nom_vendedor = $row['vendedor'];
				}
				mysqli_free_result($resultvendedor);
			} else {
				$nom_vendedor = NULL;
			}
			
			printf("<td>%s</td>", $nom_vendedor);//vendedor
			printf("<td>%s</td>", $almacen_origen);//almacen origen
			printf("<td>%s</td>", $almacen_destino);//almacen destino
			printf("<td align='center'>%s</td>", $papa_enlace);//enlace papa
				
			$cantidad_det = $cantidad_;
			$costo_det = $costo_;	
			$costo_extra_det = $costo_extra;	
			
			if ( $tipo_movimiento == 'Traspasos') {//if traspasos
				if( $almacen_origen == $nom_almacen_det) {//if almacen origen
				$cantidad_det = $cantidad_ * -1;
				$costo_det = ($costo_ - $costo_extra) * -1;
				$costo_extra_det = 0;
				}//fin if almacen origen
			} //fin if traspasos
			
			if($mostrar_lotes_det == 1){//if muestra_lote1
				
				$suma_cant_lote = 0;
				$result4 = mysqli_query($link, "select a.codBatch as cod_lote, a.fldID as id_lote, case when a.codType = 1 then a.fldQuantity else a.fldQuantity * -1 end as cant_mov, a.fldExpirationDate as fecha_exp, a.fldPriority as prioridad, a.codType as cod_tipo
				from invItemMovementDetailBatch a
				where
				a.codItemMovementDetail = '$cod_det_det' and 
				a.codItemMovement = '$cod_mov_det' 
				order by cod_tipo desc;");
						
				//printf("<td>%s<br/>", $row['item']);//nombre item
				echo '<td>';
				//abrir la tabla para los lotes
				echo '<table border="0" align="left" cellpadding="3">
				<TR> 
				<TD align="center"><b>Cod. Lote</b></TD>
				<TD align="center"><b>ID</b></TD>
				<TD align="center"><b>Cantidad</b></TD>
				<TD align="center"><b>Expiraci&oacute;n</b></TD>
				<TD align="center"><b>Prioridad</b></TD>
				</TR>';
				$suma_cant_lote = 0;
				while ($row = mysqli_fetch_array($result4)) { //while4
				
					$cod_lote = $row['cod_lote'];
					$id_lote = $row['id_lote'];
					$cant_mov = $row['cant_mov'];
					$fecha_exp = $row['fecha_exp'];
					$prioridad = $row['prioridad'];
					
					printf("<tr><td align='center'>%s</td>", $cod_lote);//cod lote
					printf("<td align='center'>%s</td>", $id_lote);//id lote
					printf("<td align='right'>%s</td>", number_format($cant_mov, $n_cantidad));//cant mov
					printf("<td align='right'>%s</td>", $fecha_exp);//fecha expiracion
					printf("<td align='right'>%s</td></tr>", $prioridad);//prioridad
					if($cod_tipo_movimiento == 3) { //if 0
						if($cant_mov >= 0) {
						$suma_cant_lote = $suma_cant_lote + $cant_mov;
						}
					} else {//else if 0
						$suma_cant_lote = $suma_cant_lote + $cant_mov;
					}//fin if 0
				}//fin while4
				mysqli_free_result($result4);
				
				echo "<tr><td>&nbsp;</td><td>&nbsp;</td><td align='right'><HR width='90%' align='right'></td><td>&nbsp;</td><td>&nbsp;</td></tr>";
				echo '<tr><td colspan="2"><b>Total Lotes</b></td><td align="right">'. number_format($suma_cant_lote, $n_cantidad).'</td><td>&nbsp;</td><td>&nbsp;</td></tr>
				</table></td>';
			
			}//fin if muestra_lote1
			
			if ( $cantidad_det >= 0) {
				printf("<td align='right'>%s</td>", number_format($cantidad_det,$n_cantidad));//cantidad ingreso
				echo "<td>&nbsp;</td>";
			} else {
				echo "<td>&nbsp;</td>";
				printf("<td align='right'>%s</td>", number_format($cantidad_det,$n_cantidad));//cantidad egreso
			}
			//printf("<td align='right'>%s</td>", number_format($cantidad_det,$n_cantidad));//cantidad
			$suma_saldo = $suma_saldo + $cantidad_det;
			printf("<td align='right'>%s</td>", number_format($suma_saldo,$n_cantidad));//saldo
			
			if($mostrar_cant_det == 0) { //if mostrar_cant_det
				printf("<td align='right'>%s</td>", number_format($costo_det/$cantidad_det,$n_decimales));//costo unitario
				printf("<td align='right'>%s</td>", number_format($costo_extra_det,$n_decimales));//costo extra
				
				if ( $costo_det >= 0) {
					printf("<td align='right'>%s</td>", number_format($costo_det,$n_decimales));//costo ingreso
					echo "<td>&nbsp;</td>";
				} else {
					echo "<td>&nbsp;</td>";
					printf("<td align='right'>%s</td>", number_format($costo_det,$n_decimales));//costo egreso
				}
				//printf("<td align='right'>%s</td>", number_format($costo_det,$n_decimales));//costo
				$suma_saldo_costo = $suma_saldo_costo + $costo_det;
				printf("<td align='right'>%s</td>", number_format($suma_saldo_costo,$n_decimales));//saldo costo
				
				if($otra_monedadet != 0){
					printf("<td align='right'>%s</td>", number_format($costo_det/$cantidad_det * $tasa_tc,$n_decimales));//costo unitario otra moneda
					printf("<td align='right'>%s</td>", number_format($costo_extra_det * $tasa_tc,$n_decimales));//costo extra otra moneda
					
					if ( $costo_det >= 0) {
						printf("<td align='right'>%s</td>", number_format($costo_det * $tasa_tc,$n_decimales));//costo ingreso otra moneda
						echo "<td>&nbsp;</td>";
					} else {
						echo "<td>&nbsp;</td>";
						printf("<td align='right'>%s</td>", number_format($costo_det * $tasa_tc,$n_decimales));//costo egreso otra moneda
					}
					//printf("<td align='right'>%s</td>", number_format($costo_det * $tasa_tc,$n_decimales));//costo otra moneda
					$suma_saldo_costo_otra_moneda = $suma_saldo_costo_otra_moneda + $costo_det * $tasa_tc;
					printf("<td align='right'>%s</td>", number_format($suma_saldo_costo_otra_moneda,$n_decimales));//saldo costo
				}
			} //fin if mostrar_cant_det
			echo '</tr>';
			
			//para sumar en ingreso y egreso
			if ( $cantidad_det >= 0) {
				$suma_periodo_cant_ing = $suma_periodo_cant_ing + $cantidad_det;
			} else {
				$suma_periodo_cant_egr = $suma_periodo_cant_egr + $cantidad_det;
			}
			$suma_periodo_cant = $suma_periodo_cant + $cantidad_det;
			//para sumar en ingreso y egreso
			if ( $costo_det >= 0) {
				$suma_periodo_costo_ing = $suma_periodo_costo_ing + $costo_det;
			} else {
				$suma_periodo_costo_egr = $suma_periodo_costo_egr + $costo_det;
			}
			$suma_periodo_costo = $suma_periodo_costo + $costo_det;
			$acum_otra = $costo_det * $tasa_tc;

			//para sumar en ingreso y egreso
			if ( $costo_det >= 0) {
				$suma_periodo_costo_otra_moneda_ing = $suma_periodo_costo_otra_moneda_ing + $acum_otra;
			} else {
				$suma_periodo_costo_otra_moneda_egr = $suma_periodo_costo_otra_moneda_egr + $acum_otra;
			}
			$suma_periodo_costo_otra_moneda = $suma_periodo_costo_otra_moneda + $acum_otra;
			$suma_periodo_costo_extra = $suma_periodo_costo_extra + $costo_extra_det;
			$suma_periodo_costo_extra_otra_moneda = $suma_periodo_costo_extra_otra_moneda + $costo_extra_det * $tasa_tc;
			
			$color++;
		}//fin while
		mysqli_free_result($result2);
		$suma_total_cant = $suma_periodo_cant + $totalcantdet;
		$suma_total_costo = $suma_periodo_costo + $totalcostodet;
		$suma_total_costo_otra_moneda = $suma_periodo_costo_otra_moneda + $totalcostodet * $tasa_tc;  
  	}//fin if almacen todos
 ?>
<TR BGCOLOR='#ffcccc'> 
<TD align="left" colspan="<?php echo $num_col; ?>"><b>Total Cant. Periodo</b></TD>
<?php if($otra_monedadet != 0){ ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_cant_ing,$n_cantidad); ?></b></TD>
	<TD align="right"><b><?php echo number_format($suma_periodo_cant_egr,$n_cantidad); ?></b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
	<?php } ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_cant,$n_cantidad); ?></b></TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
		<?php if($mostrar_cant_det == 0){ ?>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<?php if($almacen_det == 0){ ?>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
		<?php } ?>
		<?php } ?>
	</TR> 
<?php } else { ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_cant_ing,$n_cantidad); ?></b></TD>
	<TD align="right"><b><?php echo number_format($suma_periodo_cant_egr,$n_cantidad); ?></b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
	<?php } ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_cant,$n_cantidad); ?></b></TD>
	
	<?php if($mostrar_cant_det == 0){ ?>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<?php if($almacen_det == 0){ ?>
			<TD>&nbsp;</TD>
		<?php } ?>
    <?php } ?>
	</TR> 
<?php } ?>

<?php if($mostrar_cant_det == 0){ ?>

<TR BGCOLOR='#ffcccc'> 
<TD align="left" colspan="<?php echo $num_col; ?>"><b>Total Costo periodo</b></TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<?php if($almacen_det == 0){ ?>
	<TD>&nbsp;</TD>
<?php } ?>
<TD align="right"><b><?php echo number_format($suma_periodo_costo_extra,$n_decimales); ?></b></TD>
<?php if($otra_monedadet != 0){ ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_ing,$n_decimales); ?></b></TD>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_egr,$n_decimales); ?></b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
	<?php } ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo,$n_decimales); ?></b></TD>
	<TD>&nbsp;</TD>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_extra_otra_moneda,$n_decimales); ?></b></TD>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_otra_moneda_ing,$n_decimales); ?></b></TD>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_otra_moneda_egr,$n_decimales); ?></b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
	<?php } ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_otra_moneda,$n_decimales); ?></b></TD></TR>
<?php } else { ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_ing,$n_decimales); ?></b></TD>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo_egr,$n_decimales); ?></b></TD>
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
	<?php } ?>
	<TD align="right"><b><?php echo number_format($suma_periodo_costo,$n_decimales); ?></b></TD></TR>
<?php } ?>

<?php } ?>
 
<TR BGCOLOR='#ffcccc'>
<TD align="left" colspan="<?php echo $num_col; ?>"><b>Total Cantidad</b></TD>
<?php if($otra_monedadet != 0){ ?>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
	<?php } ?>
	<TD align="right"><b><?php echo number_format($suma_total_cant,$n_cantidad); ?></b></TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
		<?php if($mostrar_cant_det == 0){ ?>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<?php if($almacen_det == 0){ ?>
			<TD>&nbsp;</TD>
			<TD>&nbsp;</TD>
		<?php } ?>
		<?php } ?>
	</TR>
<?php } else { ?>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
	<?php } ?>
	<TD align="right"><b><?php echo number_format($suma_total_cant,$n_cantidad); ?></b></TD>
		<?php if($mostrar_cant_det == 0){ ?>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<?php if($almacen_det == 0){ ?>
			<TD>&nbsp;</TD>
		<?php } ?>
		<?php } ?>
	</TR> 
<?php } ?>

<?php if($mostrar_cant_det == 0){ ?>
	<TR BGCOLOR='#ffcccc'> 
	<TD align="left" colspan="<?php echo $num_col; ?>"><b>Total Costo</b></TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	<TD>&nbsp;</TD>
	
	<?php if($almacen_det == 0){ ?>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
	<?php } ?>
	<?php if($otra_monedadet != 0){ ?>
		<TD>&nbsp;</TD>
		<TD align="right"><b><?php echo number_format($suma_total_costo,$n_decimales); ?></b></TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<TD>&nbsp;</TD>
		<?php if($almacen_det == 0){ ?>
			<TD>&nbsp;</TD>
		<?php } ?>
		<TD align="right"><b><?php echo number_format($suma_total_costo_otra_moneda,$n_decimales); ?></b></TD></TR>
	<?php } else { ?>
		<TD>&nbsp;</TD>
		<TD align="right"><b><?php echo number_format($suma_total_costo,$n_decimales); ?></b></TD></TR>
	<?php } ?> 
<?php } ?> 
</tbody>
</table>
  
  <?php

} //fin if 3
?>

</body>
</html>
