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

</head>
<?php
/*
Muestra las ventas combinando item con item, vendedor, almacen, cliente, local o punto de venta, ciudad. Permite elegir el tipo que puede ser banco, cheque, cortesia, cxc, efectivo y tarjeta de credito, además filtra por familia, subfamilia, grupo y subgrupo en un rango de fechas.
El detalle discrimina de acuerdo a la eleccion que se realiza item, vendedor, almacen, cliente, local o punto de venta, ciudad. Tambien pasa los parametros de banco, cheque, cortesia, cxc, efectivo y tarjeta de credito, familia, subfamilia, grupo y subgrupo. (Modificado por sugerencia de M)
*/
include "../../conn.php";
include "../../general.php";
include "../../token.php";

$rep=$_GET["rep"];
$tipo=$_GET["tipo"];
//$usuario=$_POST["usuario"];
$asientocc=$_POST["asientocc"];
$tipo_nota=$_POST["tiponota"];
$item=$_POST["item"];
$vendedor=$_POST["vendedor"];
$almacen=$_POST["almacen"];
$cliente=$_POST["cliente"];
$canal_venta=$_POST["canal_venta"];
$local=$_POST["local"];
$ciudad=$_POST["ciudad"];
$familia=$_POST["familia"];
$subfamilia=$_POST["subfamilia"];
$grupo=$_POST["grupo"];
$subgrupo=$_POST["subgrupo"];
$fechaini=$_POST["fechaini"];
$fechafin=$_POST["fechafin"];
$orden=$_POST["orden"];
$otra_moneda=$_POST["otra_moneda"];
$combinar=$_POST["combinar"];
$cod_contexto=$_POST["contexto"];
$marca=$_POST["marca"];
$modelo=$_POST["modelo"];

//$usuario_rev=$_GET["usuario_rev"];
$asientocc_rev=$_GET["asientocc_rev"];
$tipo_nota_rev=$_GET["tiponota_rev"];
$item_rev=$_GET["item_rev"];
$familia_rev=$_GET["familia_rev"];
$fechaini_rev=$_GET["fechaini_rev"];
$fechafin_rev=$_GET["fechafin_rev"];
$orden_rev=$_GET["orden_rev"];
$otra_moneda_rev=$_GET["otra_moneda_rev"];
$combinar_rev=$_GET["combinar_rev"];
$cod_contexto_rev=$_GET["contexto_rev"];
$marca_rev=$_GET["marca_rev"];
$modelo_rev=$_GET["modelo_rev"];

//if($usuario_rev != NULL) { $usuario = $usuario_rev; }
if($asientocc_rev != NULL) { $asientocc = $asientocc_rev; }
if($tipo_nota_rev != NULL) { $tipo_nota = $tipo_nota_rev; }
if($item_rev != NULL) { $item = $item_rev; }
if($familia_rev != NULL) { $familia = $familia_rev; }
if($fechaini_rev != NULL) { $fechaini = $fechaini_rev; }
if($fechafin_rev != NULL) { $fechafin = $fechafin_rev; }
if($orden_rev != NULL) { $orden = $orden_rev; }
if($otra_moneda_rev != NULL) { $otra_moneda = $otra_moneda_rev; }
if($combinar_rev != NULL) { $combinar = $combinar_rev; }
if($cod_contexto_rev != NULL) { $cod_contexto = $cod_contexto_rev; }
if($marca_rev != NULL) { $marca = $marca_rev; }
if($modelo_rev != NULL) { $modelo = $modelo_rev; }


$cod_cxc=$_GET["cod_cxc"];
$empresa=$_GET["empresa"];
//$usuario_det=$_GET["usuario_det"];
$asientocc_det=$_GET["asientocc_det"];
$otra_moneda_det=$_GET["otra_moneda_det"];
$combinar_det=$_GET["combinar_det"];
$periodo_det=$_GET["periodo_det"];
$tipo_nota_det=$_GET["tipo_nota_det"];
$familia_det=$_GET["familia_det"];
$subfamilia_det=$_GET["subfamilia_det"];
$grupo_det=$_GET["grupo_det"];
$subgrupo_det=$_GET["subgrupo_det"];
$fechaini_det=$_GET["fechaini_det"];
$fechafin_det=$_GET["fechafin_det"];
$cod_item_det=$_GET["cod_item_det"];
$cod_varios_det=$_GET["cod_varios_det"]; //son los codigos de vendedor, cliente, almacen, local, ciudad
$cod_contexto_det=$_GET["contexto_det"];
$marca_det=$_GET["marca_det"];
$modelo_det=$_GET["modelo_det"];

//$n_decimales = 6;

if($familia == '') { $familia = 0;}
if($subfamilia == '') { $subfamilia = 0;}
if($grupo == '') { $grupo = 0;}
if($subgrupo == '') { $subgrupo = 0;}

if($marca == '') { $marca = 0;}
if($modelo == '') { $modelo = 0;}
?>
<body>

	<?php
	
//Inicio reporte Ventas por Item


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

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


if ($combinar == 0) { //if combinar = 0
	$cliente = 0;
	$canal_venta = 0;
	$vendedor = 0;
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_item';
	if ($orden == 0) {
		$valor_ordenar = 'order by item, vendedor, cliente';
		$nom_orden = 'Item (Nombre)';
	} else {
		$valor_ordenar = 'order by cantidad desc, item, vendedor, cliente';
		$nom_orden = 'Cantidad (Ranking)';	
	}
	$nom_combinar = 'Item';
} //fin if combinar = 0
if ($combinar == 1) { //if combinar = 1
  	$cliente = 0;
	$canal_venta = 0;
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_vendedor, cod_item';
	$valor_agrupar2 = 'group by cod_vendedor';
	if ($orden == 0) {
		$valor_ordenar = 'order by vendedor, item';
		$valor_ordenar2 = 'order by vendedor, item';
		$nom_orden = 'Vendedor e Item';
	} else {
		$valor_ordenar = 'order by vendedor, cantidad desc, item';
		$valor_ordenar2 = 'order by vendedor, cantidad desc, item';
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Vendedor';
} //fin if combinar = 1
if ($combinar == 2) { //if combinar = 2
	$vendedor = 0;  
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_cli, cod_item'; //$valor_agrupar = 'group by fin.cod_cli, fin.cod_item';
	$valor_agrupar2 = 'group by cod_cli'; //$valor_agrupar2 = 'group by fin2.cod_cli';
	if ($orden == 0) {
		$valor_ordenar = 'order by cliente, item'; //$valor_ordenar = 'order by fin.cliente, fin.item';
		$valor_ordenar2 = 'order by cliente, item'; //$valor_ordenar2 = 'order by fin2.cliente, fin2.item';
		$nom_orden = 'Cliente e Item';
	} else {
		$valor_ordenar = 'order by cliente, cantidad desc, item';
		$valor_ordenar2 = 'order by cliente, cantidad desc, item';
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Cliente';
} //fin if combinar = 2
if ($combinar == 3) { //if combinar = 3
	$cliente = 0;  
	$canal_venta = 0;
	$vendedor = 0;  
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_alm, cod_item';
	$valor_agrupar2 = 'group by cod_alm';
	if ($orden == 0) {
		$valor_ordenar = 'order by almacen, item';
		$valor_ordenar2 = 'order by almacen, item';
		$nom_orden = 'Almacen e Item';
	} else {
		$valor_ordenar = 'order by almacen, cantidad desc, item';
		$valor_ordenar2 = 'order by almacen, cantidad desc, item';
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Almacen';
}//fin if combinar = 3
if ($combinar == 4) { //if combinar = 4
	$cliente = 0;  
	$canal_venta = 0;
	$vendedor = 0;  
	$almacen = 0;
	$ciudad = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_local, cod_item';
	$valor_agrupar2 = 'group by cod_local';
	if ($orden == 0) {
		$valor_ordenar = 'order by local_venta, item';
		$valor_ordenar2 = 'order by local_venta, item';
		$nom_orden = 'Punto o Local de venta e Item';
	} else {
		$valor_ordenar = 'order by local_venta, cantidad desc, item';
		$valor_ordenar2 = 'order by local_venta, cantidad desc, item';
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Punto o Local de venta';
}//fin if combinar = 4
if ($combinar == 5) { //if combinar = 5
	$cliente = 0;  
	$canal_venta = 0;
	$vendedor = 0;  
	$almacen = 0;
	$local = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_ciudad, cod_item';
	$valor_agrupar2 = 'group by cod_ciudad';
	if ($orden == 0) {
		$valor_ordenar = 'order by ciudad, item';
		$valor_ordenar2 = 'order by ciudad, item';
		$nom_orden = 'Ciudad e Item';
	} else {	
		$valor_ordenar = 'order by ciudad, cantidad desc, item';
		$valor_ordenar2 = 'order by ciudad, cantidad desc, item';
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Ciudad';
}//fin if combinar = 5
if ($combinar == 6) { //if combinar = 6
	$cliente = 0;
	$canal_venta = 0;
	$vendedor = 0;
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_familia, cod_item';
	$valor_agrupar2 = 'group by cod_familia';
	if ($orden == 0) {
		$valor_ordenar = 'order by familia, item';
		$valor_ordenar2 = 'order by familia, item';
		$nom_orden = 'Familia e Item';
	} else {	
		$valor_ordenar = 'order by familia, cantidad desc, item';
		$valor_ordenar2 = 'order by familia, cantidad desc, item';
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Familia';
}//fin if combinar = 6
if ($combinar == 7) { //if combinar = 7
	$cliente = 0;
	$canal_venta = 0;
	$vendedor = 0;
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codFamily';
	$valor_agrupar = 'group by cod_familia, cod_item';
	$valor_agrupar2 = 'group by cod_familia';
	$valor_ordenar = 'order by familia, item';
	$valor_ordenar2 = 'order by familia, item';
	if ($orden == 0) {
		$nom_orden = 'Familia';
	} else {	
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Familia (Consolidado)';
}//fin if combinar = 7
if ($combinar == 8) { //if combinar = 8
	$cliente = 0;
	$canal_venta = 0;
	$vendedor = 0;
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codSubFamily';
	$valor_agrupar = 'group by cod_familia, cod_item';
	$valor_agrupar2 = 'group by cod_familia';
	$valor_ordenar = 'order by familia, item';
	$valor_ordenar2 = 'order by familia, item';
	if ($orden == 0) {
		$nom_orden = 'Sub Familia';
	} else {	
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Sub Familia (Consolidado)';
}//fin if combinar = 8
if ($combinar == 9) { //if combinar = 9
	$cliente = 0;
	$canal_venta = 0;
	$vendedor = 0;
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codGroup';
	$valor_agrupar = 'group by cod_familia, cod_item';
	$valor_agrupar2 = 'group by cod_familia';
	$valor_ordenar = 'order by familia, item';
	$valor_ordenar2 = 'order by familia, item';
	if ($orden == 0) {
		$nom_orden = 'Grupo';
	} else {		
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Grupo (Consolidado)';
}//fin if combinar = 9
if ($combinar == 10) { //if combinar = 10
	$cliente = 0;
	$canal_venta = 0;
	$vendedor = 0;
	$almacen = 0;
	$local = 0;
	$ciudad = 0;
	$consolidado = 'i.codSubGroup';
	$valor_agrupar = 'group by cod_familia, cod_item';
	$valor_agrupar2 = 'group by cod_familia';
	$valor_ordenar = 'order by familia, item';
	$valor_ordenar2 = 'order by familia, item';
	if ($orden == 0) {
		$nom_orden = 'Sub Grupo';
	} else {	
		$nom_orden = 'Cantidad (Ranking)';
	}
	$nom_combinar = 'Sub Grupo (Consolidado)';
}//fin if combinar = 10

if ($marca == 0) { // if marca
	$nom_marca = 'Todos';
	$valor_marca = ' ';
	$valor_marca2 = ' ';
} else {
	//nombre marca
	$result5 = mysqli_query($link, "select pkyBrand as cod, fldName as marca 
							from invBrand 
							where 
							pkyBrand = '$marca' and 
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result5)) {
		$nom_marca = $row['marca'];
	}
	mysqli_free_result($result5);
	$valor_marca = ' i.codBrand = ' .$marca. ' and ';
	$valor_marca2 = ' c.codBrand = ' .$marca. ' and ';
} //fin if marca

if ($modelo == 0) { // if modelo
	$nom_modelo = 'Todos';
	$valor_modelo = ' ';
	$valor_modelo2 = ' ';
} else {
	//nombre modelo
	$result6 = mysqli_query($link, "select pkyBrandModel as cod, fldName as modelo 
							from invBrandModel 
							where 
							pkyBrandModel = '$modelo' and 
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result6)) {
		$nom_modelo = $row['modelo'];
	}
	mysqli_free_result($result6);
	$valor_modelo = ' i.codBrandModel = ' .$modelo. ' and ';
	$valor_modelo2 = ' c.codBrandModel = ' .$modelo. ' and ';
} //fin if modelo

if ($tipo_nota == 0) { //if tipo nota
	$nom_tipo_nota = 'Todos';
	$valor_tipo_nota = ' ';
  } else { 
  	$valor_tipo_nota = ' a.codType = '.$tipo_nota.' and ';
	//nombre de tipo de nota
$resulttipo = mysqli_query($link, "select pkySalesNoteType as codigo, fldName as tipo
from 
slsSalesNoteType
where
pkySalesNoteType = '$tipo_nota' and 
sysEnabled = 1 and sysAuthorized = 1
order by tipo;");
	while ($row = mysqli_fetch_array($resulttipo)) {
	$nom_tipo_nota = $row['tipo'];
	}
	mysqli_free_result($resulttipo);
  } //fin if tipo nota

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

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

if ($cliente == 0) { //if cliente
    $valor_cliente = ' ';
	//$valor_cliente1 = ' ';
	$nom_cliente = 'Todos';
  } else { 
    $valor_cliente = ' a.codClient = '.$cliente.' and ';
	//$valor_cliente1 = ' and g.codClient = '.$cliente.' ';
	//nombre de cliente
	$resultcli = mysqli_query($link, "select pkyCompany as codigo, fldName as cliente
from agnCompany
where
fldIsClient = 1 and
pkyCompany = '$cliente' and 
sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($resultcli)) {
	$nom_cliente = $row['codigo'].' - '.$row['cliente'];
	}
	mysqli_free_result($resultcli);
  } //fin if cliente

if($canal_venta == 0) { // if canal
	$nom_canal_venta = 'Todos';
	$valor_canal_venta = ' ';
} else { 
	$resultcan = mysqli_query($link, "select pkyChannel as codigo, fldName as canal
						from agnChannel
						where
						pkyChannel = '$canal_venta';");
	while ($row = mysqli_fetch_array($resultcan)) {   
	$nom_canal_venta = $row['canal'];
	}
	mysqli_free_result($resultcan);
	$valor_canal_venta = ' c.codChannel = '.$canal_venta.' and ';
} // fin if canal

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

if ($ciudad == 0) { //if ciudad
    $valor_ciudad = ' ';
	$nom_ciudad = 'Todos';
  } else { 
    $valor_ciudad = ' c.codCityLocation = '.$ciudad.' and ';
	//nombre de local
	$resultciu = mysqli_query($link, "select a.codCityLocation as codigo, b.fldName as ciudad
from
agnCompany a, regCity b
where
a.fldIsClient = 1 and 
a.codCityLocation = '$ciudad' and 
a.codCityLocation = b.pkyCity and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by codigo 
order by ciudad;");
	while ($row = mysqli_fetch_array($resultciu)) {
	$nom_ciudad = $row['ciudad'];
	}
	mysqli_free_result($resultciu);
  } //fin if ciudad

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

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

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

//listado de ventas del periodo
//cuidado con el movimiento de stock que no genera cuando el item es tipo servicio t3 en el query (se cambio a.codItemMovement is NULL por i.codType = 2 para las notas mixtas)
$result = mysqli_query($link, "select fin.cod_item as cod_item, fin.item as item, 
fin.cod_cli as cod_cli, fin.cliente as cliente, 
fin.cod_vendedor as cod_vendedor, fin.vendedor as vendedor, 
fin.cod_alm as cod_alm, fin.almacen as almacen, 
fin.cod_local as cod_local, fin.local_venta as local_venta, 
fin.cod_ciudad as cod_ciudad, fin.ciudad as ciudad, 
fin.cod_familia as cod_familia, fin.familia as familia, sum(fin.bonificacion) as bonificacion,
sum(fin.cantidad) as cantidad, fin.precio_fin as precio, 
fin.desc_porc as desc_porc, sum(fin.precio_total_fin) as precio_total, 
fin.costo_u_fin as costo_u, sum(fin.total_costo_fin) as total_costo, 
fin.margen_u as margen_u, sum(fin.margen) as margen, 
sum(fin.comision_total) as comision_total, fin.comision_u as comision_u, fin.cod_fabrica as cod_fabrica
from (
select t2.cod_item as cod_item, t2.item as item, 
t2.fecha as fecha, 
t2.nro_doc as nro_doc, t2.cliente as cliente, 
t2.vendedor as vendedor, t2.cod_alm as cod_alm,
t2.almacen as almacen, t2.local_venta as local_venta, t2.cod_local as cod_local,
t2.moneda_venta as moneda_venta, t2.cod_tc_venta as cod_tc_venta, t2.bonificacion as bonificacion, 
t2.cantidad as cantidad, 
t2.precio as precio, t2.desc_porc as desc_porc,
t2.precio_total as precio_total,
t2.cod_cxc as cod_cxc, 
t2.cod_moneda_venta as cod_moneda_venta, 
t2.cod_moneda_costo as cod_moneda_costo, 
t2.moneda_costo as moneda_costo, 
t2.cant_costo as cant_costo, t2.costo_u as costo_u,
t2.total_costo as total_costo, t2.tasa as tasa,
t2.precio_fin as precio_fin,
t2.precio_total_fin as precio_total_fin, 
tc2.fldRate as tasa_costo,
t2.costo_u * tc2.fldRate as costo_u_fin,
t2.total_costo * tc2.fldRate as total_costo_fin,
(t2.precio_fin - t2.comision_u - (t2.costo_u * tc2.fldRate)) as margen_u,
(t2.precio_total_fin - t2.comision_total - (t2.total_costo * tc2.fldRate)) as margen,
t2.cod_cli as cod_cli,
t2.cod_vendedor as cod_vendedor, 
t2.cod_ciudad as cod_ciudad, t2.ciudad as ciudad, 
t2.cod_familia as cod_familia, t2.familia as familia, 
t2.comision_total as comision_total, t2.comision_u as comision_u, t2.cod_fabrica as cod_fabrica
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, t.bonificacion as bonificacion, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, tc.fldRate as tasa,
t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, 
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia, 
t.comision * tc.fldRate as comision_total, t.comision * tc.fldRate / t.cantidad as comision_u, t.cod_fabrica as cod_fabrica
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, case when h.fldIsBonus = 1 then h.fldQuantity else 0 end as bonificacion, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
h.fldCommission as comision, i.fldFactoryKey as cod_fabrica 
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f,  
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_venta and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_venta 
union all
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, t.bonificacion as bonificacion, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, 1 as tasa,
t.precio as precio_fin,
t.precio_total as precio_total_fin,
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia, 
t.comision as comision_total, t.comision / t.cantidad as comision_u, t.cod_fabrica as cod_fabrica
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, case when h.fldIsBonus = 1 then h.fldQuantity else 0 end as bonificacion, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
h.fldCommission as comision, i.fldFactoryKey as cod_fabrica  
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_venta = '$otra_moneda') t2, actExchangeRateDetail tc2 
where
tc2.codTargetCurrency = t2.cod_moneda_costo and
tc2.codBaseCurrency = '$otra_moneda' and
tc2.codExchangeRate = t2.cod_tc_venta 

union all

select t2.cod_item as cod_item, t2.item as item, 
t2.fecha as fecha, 
t2.nro_doc as nro_doc, t2.cliente as cliente, 
t2.vendedor as vendedor, t2.cod_alm as cod_alm,
t2.almacen as almacen, t2.local_venta as local_venta, t2.cod_local as cod_local, 
t2.moneda_venta as moneda_venta, t2.cod_tc_venta as cod_tc_venta, t2.bonificacion as bonificacion, 
t2.cantidad as cantidad, 
t2.precio as precio, t2.desc_porc as desc_porc,
t2.precio_total as precio_total,
t2.cod_cxc as cod_cxc, 
t2.cod_moneda_venta as cod_moneda_venta, 
t2.cod_moneda_costo as cod_moneda_costo, 
t2.moneda_costo as moneda_costo, 
t2.cant_costo as cant_costo, t2.costo_u as costo_u,
t2.total_costo as total_costo, t2.tasa as tasa,
t2.precio_fin as precio_fin,
t2.precio_total_fin as precio_total_fin, 
1 as tasa_costo,
t2.costo_u as costo_u_fin,
t2.total_costo as total_costo_fin,
(t2.precio_fin - t2.comision_u - t2.costo_u) as margen_u,
(t2.precio_total_fin - t2.comision_total - t2.total_costo) as margen,
t2.cod_cli as cod_cli,
t2.cod_vendedor as cod_vendedor, 
t2.cod_ciudad as cod_ciudad, t2.ciudad as ciudad, 
t2.cod_familia as cod_familia, t2.familia as familia, 
t2.comision_total as comision_total, t2.comision_u as comision_u, t2.cod_fabrica as cod_fabrica
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local, 
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, t.bonificacion as bonificacion, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, tc.fldRate as tasa,
t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin,
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia, 
t.comision * tc.fldRate as comision_total, t.comision * tc.fldRate / t.cantidad as comision_u, t.cod_fabrica as cod_fabrica 
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, case when h.fldIsBonus = 1 then h.fldQuantity else 0 end as bonificacion, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
h.fldCommission as comision, i.fldFactoryKey as cod_fabrica  
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_venta and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_venta 
union all
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local, 
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, t.bonificacion as bonificacion, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, 1 as tasa,
t.precio as precio_fin,
t.precio_total as precio_total_fin,
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia, 
t.comision as comision_total, t.comision / t.cantidad as comision_u, t.cod_fabrica as cod_fabrica
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, case when h.fldIsBonus = 1 then h.fldQuantity else 0 end as bonificacion, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
h.fldCommission as comision, i.fldFactoryKey as cod_fabrica  
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o 
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_venta = '$otra_moneda') t2 
where
t2.cod_moneda_costo = '$otra_moneda' 



union all



select t3.cod_item as cod_item, t3.item as item, 
t3.fecha as fecha, 
t3.nro_doc as nro_doc, t3.cliente as cliente, 
t3.vendedor as vendedor, t3.cod_alm as cod_alm,
t3.almacen as almacen, t3.local_venta as local_venta, t3.cod_local as cod_local, 
t3.moneda_venta as moneda_venta, t3.cod_tc_venta as cod_tc_venta, t3.bonificacion as bonificacion, 
t3.cantidad as cantidad, 
t3.precio as precio, t3.desc_porc as desc_porc,
t3.precio_total as precio_total,
t3.cod_cxc as cod_cxc, 
t3.cod_moneda_venta as cod_moneda_venta, 
NULL as cod_moneda_costo, 
NULL as moneda_costo, 
0 as cant_costo, 0 as costo_u,
0 as total_costo, t3.tasa as tasa,
t3.precio_fin as precio_fin,
t3.precio_total_fin as precio_total_fin, 
1 as tasa_costo,
0 as costo_u_fin,
0 as total_costo_fin,
(t3.precio_fin - t3.comision_u - 0) as margen_u,
(t3.precio_total_fin - t3.comision_total - 0) as margen,
t3.cod_cli as cod_cli,
t3.cod_vendedor as cod_vendedor, 
t3.cod_ciudad as cod_ciudad, t3.ciudad as ciudad, 
t3.cod_familia as cod_familia, t3.familia as familia, 
t3.comision_total as comision_total, t3.comision_u as comision_u, t3.cod_fabrica as cod_fabrica
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, t.bonificacion as bonificacion, 
t.cantidad as cantidad, t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total, t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
tc.fldRate as tasa, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, 
t.cod_cli as cod_cli, t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia, 
t.comision * tc.fldRate as comision_total, t.comision * tc.fldRate / t.cantidad as comision_u, t.cod_fabrica as cod_fabrica  
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, 
a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, case when h.fldIsBonus = 1 then h.fldQuantity else 0 end as bonificacion, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
a.codItemMovement as cod_mov_merc, 
h.fldCommission as comision, i.fldFactoryKey as cod_fabrica 
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, regCity m, invItemCategory o  
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
a.pkySalesNote = h.codSalesNote and 
i.pkyItem = h.codItem and 
i.codType = 2 and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_venta and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_venta 
union all
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, t.bonificacion as bonificacion, 
t.cantidad as cantidad, t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total, t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
1 as tasa, t.precio as precio_fin,
t.precio_total as precio_total_fin,
t.cod_cli as cod_cli, t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia, 
t.comision as comision_total, t.comision / t.cantidad as comision_u, t.cod_fabrica as cod_fabrica 
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, 
a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, case when h.fldIsBonus = 1 then h.fldQuantity else 0 end as bonificacion, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
a.codItemMovement as cod_mov_merc, 
h.fldCommission as comision, i.fldFactoryKey as cod_fabrica  
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, regCity m, invItemCategory o 
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
a.pkySalesNote = h.codSalesNote and 
i.pkyItem = h.codItem and 
i.codType = 2 and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_venta = '$otra_moneda') t3 ) fin 
$valor_agrupar 
$valor_ordenar;");


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

?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Ventas por Item</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Item: </b><?php echo $nom_item; ?></TD>
        <TD width="25%"><b>Tipo: </b><?php echo $nom_tipo_nota; ?></TD>
        <TD width="25%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        <TD width="25%"><b>Vendedor: </b><?php echo $nom_vendedor; ?></TD>
        </TR>
        <TR>
        <TD><b>Cliente: </b><?php echo $nom_cliente; ?></TD>
        <TD><b>Almacen: </b><?php echo $nom_almacen; ?></TD>
        <TD><b>Local o Punto de venta: </b><?php echo $nom_local; ?></TD>
        <TD><b>Ciudad: </b><?php echo $nom_ciudad; ?></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>Canal (solo para empresas): </b><?php echo $nom_canal_venta; ?></TD>
        <TD><b>Agrupar Item con: </b><?php echo $nom_combinar; ?></TD>
        <TD><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
        <TD><b>Expresado en: </b><?php echo $mostrar_txt_moneda; ?></TD>
        </TR>
        <TR>
		<TD><b>Marca: </b><?php echo $nom_marca; ?></TD>
        <TD><b>Modelo: </b><?php echo $nom_modelo; ?></TD>
        <TD colspan="2"><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        </TR>
    </table>

</td>
<!--
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
-->
</tr>
</table>
<br />
<?php
if($combinar == 0) { //if combinar = 0, combina todos los items con todos los clientes, todos los vendedores, todos los almacenes, todos los locales y todas las ciudades, tambien cuando se elige un solo item
?>
<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center"><b>Cod.</b></TD>
	<TD align="center"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Bon. Periodo</b></TD>
	<TD align="center"><b>Cant. Periodo</b></TD>
    <TD align="center"><b>Precio U.</b></TD>
    <TD align="center"><b>Precio x Cant. Periodo</b></TD>
    <TD align="center"><b>Costo U.</b></TD>
    <TD align="center"><b>Costo x Cant. Periodo</b></TD>
    <TD align="center"><b>Comisi&oacute;n U.</b></TD>
    <TD align="center"><b>Comisi&oacute;n x Cant. Periodo</b></TD>
    <TD align="center"><b>Margen U.</b></TD>
    <TD align="center"><b>Margen x Cant. Periodo</b></TD>
    <TD align="center"><b>% Margen</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

    <?php
    	
	// cargar listado ventas del periodo 
		$matriz_item = array ();
		$i = 1;
		while ($row = mysqli_fetch_array($result)) {
			$matriz_item[$i][1] = $row['cod_item'];
			$matriz_item[$i][2] = $row['item'];
			$matriz_item[$i][3] = $row['cod_cli'];
			$matriz_item[$i][4] = $row['cliente'];
			$matriz_item[$i][5] = $row['cod_vendedor'];
			$matriz_item[$i][6] = $row['vendedor'];
			$matriz_item[$i][7] = $row['cantidad'];
			$matriz_item[$i][8] = $row['precio'];
			$matriz_item[$i][9] = $row['precio_total'];
			$matriz_item[$i][10] = $row['costo_u'];
			$matriz_item[$i][11] = $row['total_costo'];
			$matriz_item[$i][12] = $row['margen_u'];
			$matriz_item[$i][13] = $row['margen'];
			$matriz_item[$i][14] = $row['comision_total'];
			$matriz_item[$i][15] = $row['bonificacion'];
			$matriz_item[$i][16] = $row['cod_fabrica'];
			//$matriz_item[$i][14] = 0;// cantidad saldo inicial
			//$matriz_item[$i][15] = 0;// precio saldo inicial
			//$matriz_item[$i][16] = 0;// costo saldo inicial
			//$matriz_item[$i][17] = 0;// margen saldo inicial
			
			$i++;
			}
			mysqli_free_result($result);
		
		$fin_item = $i - 1;
		/*
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item']) {
					 $matriz_item[$i][14] = $row['cantidad'];
					 $matriz_item[$i][15] = $row['precio_total'];
					 $matriz_item[$i][16] = $row['total_costo'];
					 $matriz_item[$i][17] = $row['margen'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
	*/
	$color = 2;
	$suma_mg = 0;
	$suma_pc = 0;
	$suma_cc = 0;
	$suma_co = 0;
	$suma_bo = 0;
	$suma_ca = 0;
	
	$suma_mg_sal = 0;
	$suma_pc_sal = 0;
	$suma_cc_sal = 0;
	$suma_bo_sal = 0;
	$suma_ca_sal = 0;
	
	$suma_mg_tot = 0;
	$suma_pc_tot = 0;
	$suma_cc_tot = 0;
	$suma_bo_tot = 0;
	$suma_ca_tot = 0;
	$i = 1;
	
	while($i <= $fin_item) { //while
		//$codigo = $matriz_item[$i][14];
		if($color % 2 == 0) { //if color
			printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		} else {
			printf("<tr><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		}//cierra if color
		printf("<td>%s</td>", $matriz_item[$i][16]);//cod fab
		printf("<td>%s</td>", $matriz_item[$i][2]);//item
		$cod_item_det = $matriz_item[$i][1];
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][14],2));//saldo cant
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][15],$n_decimales));//saldo precio x cant
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][16],$n_decimales));// saldo costo x cant 
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][17],$n_decimales));//saldo margen
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][15],$n_cantidad));//bonificacion
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7],$n_cantidad));//cantidad
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][9]/$matriz_item[$i][7],$n_decimales));//precio unitario
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=0&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&contexto_det=$cod_contexto&marca_det=$marca&modelo_det=$modelo&usuario_det=$usuario&token=$token&asientocc_det=$asientocc' title='Kardex de Ventas por Item del Periodo'>%s</a></td>", number_format($matriz_item[$i][9],$n_decimales));//precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=0&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&contexto_det=$cod_contexto&marca_det=$marca&modelo_det=$modelo&usuario_det=$usuario&token=$token&asientocc_det=$asientocc' title='Kardex de Ventas por Item del Periodo'>%s</a></td>", number_format($matriz_item[$i][9],$n_decimales));//precio x cant
		}
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][10],$n_decimales));//costo unitario
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][11]/$matriz_item[$i][7],$n_decimales));//costo unitario
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][11],$n_decimales));//costo x cant
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][14]/$matriz_item[$i][7],$n_decimales));//comision unitaria
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][14],$n_decimales));//comision x cant
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][13]/$matriz_item[$i][7],$n_decimales));//margen unitario
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][13],$n_decimales));//margen
		/*
		$total_cantidad = $matriz_item[$i][14] + $matriz_item[$i][7];
		printf("<td align='right'>%s</td>", number_format($total_cantidad,2));// total cantidad
		$total_precio = $matriz_item[$i][15] + $matriz_item[$i][9];
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=0&periodo_det=0&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo' title='Kardex de Cotizaciones y Notas de Pedido por Item'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=0&periodo_det=0&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo' title='Kardex de Cotizaciones y Notas de Pedido por Item'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant
		}
		$total_costo = $matriz_item[$i][16] + $matriz_item[$i][11];
		printf("<td align='right'>%s</td>", number_format($total_costo,$n_decimales));// total costo x cant
		$total_margen = $matriz_item[$i][17] + $matriz_item[$i][13];
		printf("<td align='right'>%s</td>", number_format($total_margen,$n_decimales));//total margen
		*/
		$total_costo = $matriz_item[$i][11];
		$total_margen = $matriz_item[$i][13];
		$total_comision = $matriz_item[$i][14];
		if($total_costo != 0) {//if $total_costo != 0
			printf("<td align='right'>%s</td>", number_format(($total_margen / ($total_costo + $total_comision)) * 100,2));//% margen
		} else { //else if $total_costo != 0
			if($total_comision != 0) {//if comi != 0
			printf("<td align='right'>%s</td>", number_format(($total_margen / ($total_costo + $total_comision)) * 100,2));//% margen
			} else { //else comi != 0
			printf("<td align='right'>%s</td>", number_format(100,2));//% margen	
			} // fin if comi != 0
		}//fin if $total_costo != 0
		$suma_mg = $suma_mg + $matriz_item[$i][13];
		$suma_pc = $suma_pc + $matriz_item[$i][9];
		$suma_cc = $suma_cc + $matriz_item[$i][11];
		$suma_co = $suma_co + $matriz_item[$i][14];
		$suma_ca = $suma_ca + $matriz_item[$i][7];
		$suma_bo = $suma_bo + $matriz_item[$i][15];
	    
		$suma_mg_sal = $suma_mg_sal + $matriz_item[$i][17];
		$suma_pc_sal = $suma_pc_sal + $matriz_item[$i][15];
		//$suma_cc_sal = $suma_cc_sal + $matriz_item[$i][16];
		$suma_ca_sal = $suma_ca_sal + $matriz_item[$i][7];
		$suma_bo_sal = $suma_bo_sal + $matriz_item[$i][15];
		
		$suma_mg_tot = $suma_mg_tot + $total_margen;
		$suma_pc_tot = $suma_pc_tot + $total_precio;
		$suma_cc_tot = $suma_cc_tot + $total_costo;
		$suma_ca_tot = $suma_ca_tot + $matriz_item[$i][7];
		$suma_bo_tot = $suma_bo_tot + $matriz_item[$i][15];
	  	$color++;
		$i++;
	}//fin while
	
	?>
 
 <tr BGCOLOR='#ffcccc'><td colspan="3"><b>Totales</b></td>
 <!--
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc_sal,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc_sal,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg_sal,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 -->
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_bo,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_ca,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_co,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td>&nbsp;</td>
 <!--
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc_tot,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc_tot,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg_tot,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 -->
 </tr>
 </tbody>
 </table>
         

<?php
	
	} else { //else combinar = 0
	
	//si combinar = 1 => mostrar vendedor, si combinar = 2 => mostrar cliente, si combinar = 3 => mostrar almacen, si combinar = 4 => mostrar local, si combinar = 5 => mostrar ciudad, si combinar = 6 => mostrar familia
	?>
	<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center"><b>Cod.</b></TD>
	<?php if($combinar <= 6) { ?>
	<TD align="center"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <?php } if($combinar == 1) { ?>
    <TD align="center"><b>Vendedor</b></TD>
    <?php } if($combinar == 2) {?>
    <TD align="center"><b>Cliente</b></TD>
    <?php } if($combinar == 3) {?>
    <TD align="center"><b>Almac&eacute;n</b></TD>
    <?php } if($combinar == 4) {?>
    <TD align="center"><b>Punto o Local de venta</b></TD>
    <?php } if($combinar == 5) {?>
    <TD align="center"><b>Ciudad</b></TD>
    <?php } if($combinar == 6) {?>
    <TD align="center"><b>Familia</b></TD>
    <?php } if($combinar == 7) {?>
    <TD align="center"><b>Familia</b></TD>
    <?php } if($combinar == 8) {?>
    <TD align="center"><b>Sub Familia</b></TD>
    <?php } if($combinar == 9) {?>
    <TD align="center"><b>Grupo</b></TD>
    <?php } if($combinar == 10) {?>
    <TD align="center"><b>Sub Grupo</b></TD>
    <?php } ?>
    
    <TD align="center"><b>Bon. Periodo</b></TD>
	<TD align="center"><b>Cant. Periodo</b></TD>
    <TD align="center"><b>Precio U.</b></TD>
    <TD align="center"><b>Precio x Cant. Periodo</b></TD>
    <TD align="center"><b>Costo U.</b></TD>
    <TD align="center"><b>Costo x Cant. Periodo</b></TD>
    <TD align="center"><b>Comisi&oacute;n U.</b></TD>
    <TD align="center"><b>Comisi&oacute;n x Cant. Periodo</b></TD>
    <TD align="center"><b>Margen U.</b></TD>
    <TD align="center"><b>Margen x Cant. Periodo</b></TD>
    <TD align="center"><b>% Margen</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">

    <?php
	
	// cargar listado ventas del periodo 
		$matriz_item = array ();
		$i = 1;
		while ($row = mysqli_fetch_array($result)) {
			$matriz_item[$i][1] = $row['cod_item'];
			$matriz_item[$i][2] = $row['item'];
			$matriz_item[$i][3] = $row['cod_cli'];
			$matriz_item[$i][4] = $row['cliente'];
			$matriz_item[$i][5] = $row['cod_vendedor'];
			$matriz_item[$i][6] = $row['vendedor'];
			$matriz_item[$i][7] = $row['cantidad'];
			$matriz_item[$i][8] = $row['precio'];
			$matriz_item[$i][9] = $row['precio_total'];
			$matriz_item[$i][10] = $row['costo_u'];
			$matriz_item[$i][11] = $row['total_costo'];
			$matriz_item[$i][12] = $row['margen_u'];
			$matriz_item[$i][13] = $row['margen'];
			$matriz_item[$i][14] = $row['comision_total'];
			$matriz_item[$i][15] = $row['bonificacion'];
			$matriz_item[$i][16] = $row['cod_fabrica'];
			//$matriz_item[$i][14] = 0;// cantidad saldo inicial
			//$matriz_item[$i][15] = 0;// precio saldo inicial
			//$matriz_item[$i][16] = 0;// costo saldo inicial
			//$matriz_item[$i][17] = 0;// margen saldo inicial
			$matriz_item[$i][18] = $row['cod_alm'];
			$matriz_item[$i][19] = $row['almacen'];
			$matriz_item[$i][20] = $row['cod_local'];
			$matriz_item[$i][21] = $row['local_venta'];
			$matriz_item[$i][22] = $row['cod_ciudad'];
			$matriz_item[$i][23] = $row['ciudad'];
			$matriz_item[$i][24] = $row['cod_familia'];
			$matriz_item[$i][25] = $row['familia'];
			
			$i++;
			}
			mysqli_free_result($result);
		
		$fin_item = $i - 1;
		
	// verifica si es vendedor, cliente, almacen, local o ciudad para cargar saldos iniciales
	/*
	if($combinar == 1) {//if combinar = 1
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item'] && $matriz_item[$i][5] == $row['cod_vendedor']) {
					 $matriz_item[$i][14] = $row['cantidad'];
					 $matriz_item[$i][15] = $row['precio_total'];
					 $matriz_item[$i][16] = $row['total_costo'];
					 $matriz_item[$i][17] = $row['margen'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
		
	} //fin if combinar = 1
	
	if($combinar == 2) {//if combinar = 2
	
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item'] && $matriz_item[$i][3] == $row['cod_cli']) {
					 $matriz_item[$i][14] = $row['cantidad'];
					 $matriz_item[$i][15] = $row['precio_total'];
					 $matriz_item[$i][16] = $row['total_costo'];
					 $matriz_item[$i][17] = $row['margen'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
	}//fin if combinar = 2
	
	if($combinar == 3) {//if combinar = 3
	
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item'] && $matriz_item[$i][18] == $row['cod_alm']) {
					 $matriz_item[$i][14] = $row['cantidad'];
					 $matriz_item[$i][15] = $row['precio_total'];
					 $matriz_item[$i][16] = $row['total_costo'];
					 $matriz_item[$i][17] = $row['margen'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
	}//fin if combinar = 3
	
	if($combinar == 4) {//if combinar = 4
	
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item'] && $matriz_item[$i][20] == $row['cod_local']) {
					 $matriz_item[$i][14] = $row['cantidad'];
					 $matriz_item[$i][15] = $row['precio_total'];
					 $matriz_item[$i][16] = $row['total_costo'];
					 $matriz_item[$i][17] = $row['margen'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
	}//fin if combinar = 4

	if($combinar == 5) {//if combinar = 5
	
		while ($row = mysqli_fetch_array($result1)) {
			$i = 1;
			$control = 0;
			while($i <= $fin_item && $control == 0) {
				  if($matriz_item[$i][1] == $row['cod_item'] && $matriz_item[$i][22] == $row['cod_ciudad']) {
					 $matriz_item[$i][14] = $row['cantidad'];
					 $matriz_item[$i][15] = $row['precio_total'];
					 $matriz_item[$i][16] = $row['total_costo'];
					 $matriz_item[$i][17] = $row['margen'];
					 $control = 1;
				  }
					 $i++;
			}
		}
		mysqli_free_result($result1);
	}//fin if combinar = 5
	*/
	$result_it = mysqli_query($link, "select fin2.cod_item as cod_item, fin2.cod_vendedor as cod_vendedor, fin2.cod_cli as cod_cli, fin2.cod_alm as cod_alm, fin2.cod_local as cod_local, fin2.cod_ciudad as cod_ciudad, fin2.ciudad as ciudad, fin2.cod_familia as cod_familia, fin2.familia as familia, count(fin2.cod_item) as num_reg
from(
select fin.cod_item as cod_item, fin.item as item, 
fin.cod_cli as cod_cli, fin.cliente as cliente, 
fin.cod_vendedor as cod_vendedor, fin.vendedor as vendedor, 
fin.cod_alm as cod_alm, fin.almacen as almacen, 
fin.cod_local as cod_local, fin.local_venta as local_venta, 
fin.cod_ciudad as cod_ciudad, fin.ciudad as ciudad, 
fin.cod_familia as cod_familia, fin.familia as familia, 
sum(fin.cantidad) as cantidad, fin.precio_fin as precio, 
fin.desc_porc as desc_porc, sum(fin.precio_total_fin) as precio_total, 
fin.costo_u_fin as costo_u, sum(fin.total_costo_fin) as total_costo, 
fin.margen_u as margen_u, sum(fin.margen) as margen
from (
select t2.cod_item as cod_item, t2.item as item, 
t2.fecha as fecha, 
t2.nro_doc as nro_doc, t2.cliente as cliente, 
t2.vendedor as vendedor, t2.cod_alm as cod_alm,
t2.almacen as almacen, t2.local_venta as local_venta, t2.cod_local as cod_local,
t2.moneda_venta as moneda_venta, t2.cod_tc_venta as cod_tc_venta, 
t2.cantidad as cantidad, 
t2.precio as precio, t2.desc_porc as desc_porc,
t2.precio_total as precio_total,
t2.cod_cxc as cod_cxc, 
t2.cod_moneda_venta as cod_moneda_venta, 
t2.cod_moneda_costo as cod_moneda_costo, 
t2.moneda_costo as moneda_costo, 
t2.cant_costo as cant_costo, t2.costo_u as costo_u,
t2.total_costo as total_costo, t2.tasa as tasa,
t2.precio_fin as precio_fin,
t2.precio_total_fin as precio_total_fin, 
tc2.fldRate as tasa_costo,
t2.costo_u * tc2.fldRate as costo_u_fin,
t2.total_costo * tc2.fldRate as total_costo_fin,
(t2.precio_fin - (t2.costo_u * tc2.fldRate)) as margen_u,
(t2.precio_total_fin - (t2.total_costo * tc2.fldRate)) as margen,
t2.cod_cli as cod_cli,
t2.cod_vendedor as cod_vendedor, 
t2.cod_ciudad as cod_ciudad, t2.ciudad as ciudad, 
t2.cod_familia as cod_familia, t2.familia as familia
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, tc.fldRate as tasa,
t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, 
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia 
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f,  
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_venta and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_venta 
union all
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, 1 as tasa,
t.precio as precio_fin,
t.precio_total as precio_total_fin,
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia 
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_venta = '$otra_moneda') t2, actExchangeRateDetail tc2 
where
tc2.codTargetCurrency = t2.cod_moneda_costo and
tc2.codBaseCurrency = '$otra_moneda' and
tc2.codExchangeRate = t2.cod_tc_venta 

union all

select t2.cod_item as cod_item, t2.item as item, 
t2.fecha as fecha, 
t2.nro_doc as nro_doc, t2.cliente as cliente, 
t2.vendedor as vendedor, t2.cod_alm as cod_alm,
t2.almacen as almacen, t2.local_venta as local_venta, t2.cod_local as cod_local, 
t2.moneda_venta as moneda_venta, t2.cod_tc_venta as cod_tc_venta, 
t2.cantidad as cantidad, 
t2.precio as precio, t2.desc_porc as desc_porc,
t2.precio_total as precio_total,
t2.cod_cxc as cod_cxc, 
t2.cod_moneda_venta as cod_moneda_venta, 
t2.cod_moneda_costo as cod_moneda_costo, 
t2.moneda_costo as moneda_costo, 
t2.cant_costo as cant_costo, t2.costo_u as costo_u,
t2.total_costo as total_costo, t2.tasa as tasa,
t2.precio_fin as precio_fin,
t2.precio_total_fin as precio_total_fin, 
1 as tasa_costo,
t2.costo_u as costo_u_fin,
t2.total_costo as total_costo_fin,
(t2.precio_fin - t2.costo_u) as margen_u,
(t2.precio_total_fin - t2.total_costo) as margen,
t2.cod_cli as cod_cli,
t2.cod_vendedor as cod_vendedor, 
t2.cod_ciudad as cod_ciudad, t2.ciudad as ciudad, 
t2.cod_familia as cod_familia, t2.familia as familia
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local, 
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, tc.fldRate as tasa,
t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin,
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia 
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia 
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o 
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_venta and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_venta 
union all
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, 
t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local, 
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, 
t.cantidad as cantidad, 
t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total,
t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
t.cod_moneda_costo as cod_moneda_costo, 
t.moneda_costo as moneda_costo, 
t.cant_costo as cant_costo, t.costo_u as costo_u,
t.total_costo as total_costo, 1 as tasa,
t.precio as precio_fin,
t.precio_total as precio_total_fin,
t.cod_cli as cod_cli,
t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia 
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, 
a.fldNumber as nro_doc, c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
k.codCurrency as cod_moneda_costo, 
l.fldName as moneda_costo, 
h.fldQuantity as cant_costo, j.fldCost as costo_u,
(h.fldQuantity * j.fldCost) + j.fldExtraCost as total_costo, a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia 
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, invItemMovementDetail j, 
invItemMovement k, actCurrency l, regCity m, invItemCategory o
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
k.codCurrency = l.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
h.codSalesNote = a.pkySalesNote and 
i.pkyItem = h.codItem and 
a.codItemMovement = j.codItemMovement and 
h.codItem = j.codItem and 
a.codItemMovement = k.pkyItemMovement and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_venta = '$otra_moneda') t2 
where
t2.cod_moneda_costo = '$otra_moneda' 



union all



select t3.cod_item as cod_item, t3.item as item, 
t3.fecha as fecha, 
t3.nro_doc as nro_doc, t3.cliente as cliente, 
t3.vendedor as vendedor, t3.cod_alm as cod_alm,
t3.almacen as almacen, t3.local_venta as local_venta, t3.cod_local as cod_local, 
t3.moneda_venta as moneda_venta, t3.cod_tc_venta as cod_tc_venta, 
t3.cantidad as cantidad, 
t3.precio as precio, t3.desc_porc as desc_porc,
t3.precio_total as precio_total,
t3.cod_cxc as cod_cxc, 
t3.cod_moneda_venta as cod_moneda_venta, 
NULL as cod_moneda_costo, 
NULL as moneda_costo, 
0 as cant_costo, 0 as costo_u,
0 as total_costo, t3.tasa as tasa,
t3.precio_fin as precio_fin,
t3.precio_total_fin as precio_total_fin, 
1 as tasa_costo,
0 as costo_u_fin,
0 as total_costo_fin,
(t3.precio_fin - 0) as margen_u,
(t3.precio_total_fin - 0) as margen,
t3.cod_cli as cod_cli,
t3.cod_vendedor as cod_vendedor, 
t3.cod_ciudad as cod_ciudad, t3.ciudad as ciudad, 
t3.cod_familia as cod_familia, t3.familia as familia
from (
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, 
t.cantidad as cantidad, t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total, t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
tc.fldRate as tasa, t.precio * tc.fldRate as precio_fin,
t.precio_total * tc.fldRate as precio_total_fin, 
t.cod_cli as cod_cli, t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia 
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, 
a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
a.codItemMovement as cod_mov_merc
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, regCity m, invItemCategory o 
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
a.pkySalesNote = h.codSalesNote and 
i.pkyItem = h.codItem and 
i.codType = 2 and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t, actExchangeRateDetail tc
where
tc.codTargetCurrency = t.cod_moneda_venta and
tc.codBaseCurrency = '$otra_moneda' and
tc.codExchangeRate = t.cod_tc_venta 
union all
select t.cod_item as cod_item, t.item as item, 
t.fecha as fecha, t.nro_doc as nro_doc, t.cliente as cliente, 
t.vendedor as vendedor, t.cod_alm as cod_alm,
t.almacen as almacen, t.local_venta as local_venta, t.cod_local as cod_local,
t.moneda_venta as moneda_venta, t.cod_tc_venta as cod_tc_venta, 
t.cantidad as cantidad, t.precio as precio, t.desc_porc as desc_porc,
t.precio_total as precio_total, t.cod_cxc as cod_cxc, 
t.cod_moneda_venta as cod_moneda_venta, 
1 as tasa, t.precio as precio_fin,
t.precio_total as precio_total_fin,
t.cod_cli as cod_cli, t.cod_vendedor as cod_vendedor, 
t.cod_ciudad as cod_ciudad, t.ciudad as ciudad, 
t.cod_familia as cod_familia, t.familia as familia 
from (
select h.codItem as cod_item, i.fldName as item, 
a.fldDate as fecha, a.fldNumber as nro_doc, 
c.fldName as cliente, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, 
a.codWarehouse as cod_alm, 
d.fldName as almacen, e.fldName as local_venta, a.codSalesPlace as cod_local,
f.fldName as moneda_venta, a.codExchangeRate as cod_tc_venta, 
h.fldQuantity as cantidad, 
h.fldPrice as precio, h.fldDiscount as desc_porc,
h.fldTotalNetPrice as precio_total,
a.codAccountReceivable as cod_cxc, 
a.codCurrency as cod_moneda_venta, 
a.codClient as cod_cli,
a.codSeller as cod_vendedor, 
c.codCityLocation as cod_ciudad, m.fldName as ciudad, 
$consolidado as cod_familia, o.fldName as familia, 
a.codItemMovement as cod_mov_merc
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse d, 
slsSalesPlace e, actCurrency f, 
slsSalesNoteDetail h, invItem i, regCity m, invItemCategory o 
where 
$valor_item 
$valor_vendedor 
$valor_cliente 
$valor_canal_venta 
$valor_almacen 
$valor_local 
$valor_ciudad 
$valor_familia 
$valor_subfamilia 
$valor_grupo 
$valor_subgrupo 
$valor_tipo_nota 
$valor_contexto 
$valor_marca
$valor_modelo 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = d.pkyWarehouse and 
a.codSalesPlace = e.pkySalesPlace and 
a.codCurrency = f.pkyCurrency and 
c.codCityLocation = m.pkyCity and 
a.pkySalesNote = h.codSalesNote and 
i.pkyItem = h.codItem and 
i.codType = 2 and 
$consolidado = o.pkyItemCategory and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
where
t.cod_moneda_venta = '$otra_moneda') t3 ) fin 
$valor_agrupar 
$valor_ordenar ) fin2
$valor_agrupar2 
$valor_ordenar2;");
	
	$matriz_it = array ();
	$i = 1;
	//verifica cuantos registros mostrara en el while de abajo si es vendedor, cliente, local,  almacen o ciudad
	if($combinar == 1) {//if combinar = 1, otro
		while ($row = mysqli_fetch_array($result_it)) {
		$matriz_it[$i][1] = $row['cod_vendedor'];
		$matriz_it[$i][2] = $row['num_reg'];
		$i++;
		}
	} //fin if combinar = 1, otro
	
	if($combinar == 2) {//if combinar = 2, otro
		while ($row = mysqli_fetch_array($result_it)) {
		$matriz_it[$i][1] = $row['cod_cli'];
		$matriz_it[$i][2] = $row['num_reg'];
		$i++;
		}	
	}//fin if combinar = 2, otro
	 
	if($combinar == 3) {//if combinar = 3, otro
		while ($row = mysqli_fetch_array($result_it)) {
		$matriz_it[$i][1] = $row['cod_alm'];
		$matriz_it[$i][2] = $row['num_reg'];
		$i++;
		}	
	}//fin if combinar = 3, otro
	
	if($combinar == 4) {//if combinar = 4, otro
		while ($row = mysqli_fetch_array($result_it)) {
		$matriz_it[$i][1] = $row['cod_local'];
		$matriz_it[$i][2] = $row['num_reg'];
		$i++;
		}	
	}//fin if combinar = 4, otro
	
	if($combinar == 5) {//if combinar = 5, otro
		while ($row = mysqli_fetch_array($result_it)) {
		$matriz_it[$i][1] = $row['cod_ciudad'];
		$matriz_it[$i][2] = $row['num_reg'];
		$i++;
		}	
	}//fin if combinar = 5, otro
	
	if($combinar == 6) {//if combinar = 6, otro
		while ($row = mysqli_fetch_array($result_it)) {
		$matriz_it[$i][1] = $row['cod_familia'];
		$matriz_it[$i][2] = $row['num_reg'];
		$i++;
		}	
	}//fin if combinar = 6, otro
	
	if($combinar == 7 || $combinar == 8 || $combinar == 9 || $combinar == 10) {//if combinar = 7, otro
		while ($row = mysqli_fetch_array($result_it)) {
		$matriz_it[$i][1] = $row['cod_familia'];
		$matriz_it[$i][2] = $row['num_reg'];
		$i++;
		}	
	}//fin if combinar = 7, otro
	
	$fin_it = $i - 1;
	
	mysqli_free_result($result_it);
	
	$color = 2;
	$color2 = 2;
	$suma_mg = 0;
	$suma_pc = 0;
	$suma_cc = 0;
	$suma_co = 0;
	
	$suma_bono = 0;
	$suma_cantidad = 0;
	$suma_pu = 0;
	$suma_costou = 0;
	$suma_comiu = 0;
	$suma_margenu = 0;
	$suma_margenp = 0;
	
	$suma_mg_sal = 0;
	$suma_pc_sal = 0;
	$suma_cc_sal = 0;
	
	$suma_mg_tot = 0;
	$suma_pc_tot = 0;
	$suma_cc_tot = 0;
	
	
	$suma_mg_par = 0;
	$suma_pc_par = 0;
	$suma_cc_par = 0;
	$suma_co_par = 0;
	
	$suma_bono_par = 0;
	$suma_cantidad_par = 0;
	$suma_pu_par = 0;
	$suma_costou_par = 0;
	$suma_comiu_par = 0;
	$suma_margenu_par = 0;
	$suma_margenp_par = 0;
	    
	$suma_mg_sal_par = 0;
	$suma_pc_sal_par = 0;
	$suma_cc_sal_par = 0;
		
	$suma_mg_tot_par = 0;
	$suma_pc_tot_par = 0;
	$suma_cc_tot_par = 0;
	
	//matriz para guardar cuando se agrupa por familia, subfamilia, grupo, subgrupo y es necesario ordenar
	$mat_fam = array();
	//matriz auxiliar para ordenar
	$aux = array();
	$fa = 0;
	
	$i = 1;
	$j = 1;
	
	while($j <= $fin_it){//while fin_it
		$k = 1;
	while($k <= $matriz_it[$j][2]) { //while
		$total_costo = $matriz_item[$i][11];
		$total_margen = $matriz_item[$i][13];
		$total_comision = $matriz_item[$i][14];
		if($total_costo != 0) {//if $total_costo != 0
			$total_margen_100 = $total_margen / ($total_costo + $total_comision);//% margen
		} else { //else if $total_costo != 0
			if($total_comision != 0) {//if comi != 0
			$total_margen_100 = $total_margen / ($total_costo + $total_comision);//% margen
			} else { //else comi != 0
			$total_margen_100 = 100;//% margen
			} // fin if comi != 0
		}//fin if $total_costo != 0
	  
	  if($combinar <= 6) {//if menor 6
		if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		} else {
		printf("<tr><td align='center'>%s</td>", $matriz_item[$i][1]);//cod
		}//cierra if color
		printf("<td align='center'>%s</td>", $matriz_item[$i][16]);//cod fab
		$cod_item_det = $matriz_item[$i][1];
		printf("<td>%s</td>", $matriz_item[$i][2]);//item
		if($combinar == 1) {//if combinar = 1
			printf("<td>%s</td>", $matriz_item[$i][6]);//vendedor
			$cod_varios_det = $matriz_item[$i][5];
		} //fin if combinar = 1
		if($combinar == 2) {//if combinar = 2
			printf("<td>%s</td>", $matriz_item[$i][4]);//cliente
			$cod_varios_det = $matriz_item[$i][3];
		}//fin if combinar = 2
		if($combinar == 3) {//if combinar = 3
			printf("<td>%s</td>", $matriz_item[$i][19]);//almacen
			$cod_varios_det = $matriz_item[$i][18];
		}//fin if combinar = 3
		if($combinar == 4) {//if combinar = 4
			printf("<td>%s</td>", $matriz_item[$i][21]);//punto o local de venta
			$cod_varios_det = $matriz_item[$i][20];
		}//fin if combinar = 4
		if($combinar == 5) {//if combinar = 5
			printf("<td>%s</td>", $matriz_item[$i][23]);//ciudad
			$cod_varios_det = $matriz_item[$i][22];
		}//fin if combinar = 5
		if($combinar == 6) {//if combinar = 6
			printf("<td>%s</td>", $matriz_item[$i][25]);//familia
			$cod_varios_det = $matriz_item[$i][24];
		}//fin if combinar = 6
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][14],2));//saldo cant
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][15],$n_decimales));//saldo precio x cant
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][16],$n_decimales));// saldo costo x cant 
		//printf("<td align='right'>%s</td>", number_format($matriz_item[$i][17],$n_decimales));//saldo margen
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][15],$n_cantidad));//bonificacion
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][7],$n_cantidad));//cantidad
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][9]/$matriz_item[$i][7],$n_decimales));//precio unitario
		
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=$combinar&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&cod_varios_det=$cod_varios_det&contexto_det=$cod_contexto&marca_det=$marca&modelo_det=$modelo&usuario_det=$usuario&token=$token&asientocc_det=$asientocc' title='Kardex de Ventas por Item del Periodo'>%s</a></td>", number_format($matriz_item[$i][9],$n_decimales));//precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=$combinar&periodo_det=1&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&cod_varios_det=$cod_varios_det&contexto_det=$cod_contexto&marca_det=$marca&modelo_det=$modelo&usuario_det=$usuario&token=$token&asientocc_det=$asientocc' title='Kardex de Ventas por Item del Periodo'>%s</a></td>", number_format($matriz_item[$i][9],$n_decimales));//precio x cant
		}
		
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][11]/$matriz_item[$i][7],$n_decimales));//costo unitario
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][11],$n_decimales));//costo x cant
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][14]/$matriz_item[$i][7],$n_decimales));//comision unitaria
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][14],$n_decimales));//comision x cant
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][13]/$matriz_item[$i][7],$n_decimales));//margen unitario
		printf("<td align='right'>%s</td>", number_format($matriz_item[$i][13],$n_decimales));//margen
		printf("<td align='right'>%s</td>", number_format($total_margen_100,2));//% margen
		/*
		$total_cantidad = $matriz_item[$i][14] + $matriz_item[$i][7];
		printf("<td align='right'>%s</td>", number_format($total_cantidad,2));// total cantidad
		$total_precio = $matriz_item[$i][15] + $matriz_item[$i][9];
		
		if($otra_moneda != 0) {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=$otra_moneda&combinar_det=$combinar&periodo_det=0&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&cod_varios_det=$cod_varios_det' title='Kardex de Cotizaciones y Notas de Pedido por Item'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant
		} else {
		printf("<td align='right'><a href='report.php?rep=14&tipo=2&cod_item_det=$cod_item_det&otra_moneda_det=0&combinar_det=$combinar&periodo_det=0&fechaini_det=$fechaini&fechafin_det=$fechafin&tipo_nota_det=$tipo_nota&familia_det=$familia&subfamilia_det=$subfamilia&grupo_det=$grupo&subgrupo_det=$subgrupo&cod_varios_det=$cod_varios_det' title='Kardex de Cotizaciones y Notas de Pedido por Item'>%s</a></td>", number_format($total_precio,$n_decimales));// total precio x cant
		}
		
		$total_costo = $matriz_item[$i][16] + $matriz_item[$i][11];
		printf("<td align='right'>%s</td>", number_format($total_costo,$n_decimales));// total costo x cant
		$total_margen = $matriz_item[$i][17] + $matriz_item[$i][13];
		printf("<td align='right'>%s</td>", number_format($total_margen,$n_decimales));//total margen
		*/
		/*		
		$total_costo = $matriz_item[$i][11];
		$total_margen = $matriz_item[$i][13];
		$total_comision = $matriz_item[$i][14];
		if($total_costo != 0) {//if $total_costo != 0
			printf("<td align='right'>%s</td>", number_format(($total_margen / ($total_costo + $total_comision)) * 100,2));//% margen
		} else { //else if $total_costo != 0
			if($total_comision != 0) {//if comi != 0
			printf("<td align='right'>%s</td>", number_format(($total_margen / ($total_costo + $total_comision)) * 100,2));//% margen
			} else { //else comi != 0
			printf("<td align='right'>%s</td>", number_format(100,2));//% margen	
			} // fin if comi != 0
		}//fin if $total_costo != 0
		*/
	  }//fin if menor 6
		
		$suma_mg = $suma_mg + $matriz_item[$i][13];
		$suma_pc = $suma_pc + $matriz_item[$i][9];
		$suma_cc = $suma_cc + $matriz_item[$i][11];
		$suma_co = $suma_co + $matriz_item[$i][14];
		$suma_ca = $suma_ca + $matriz_item[$i][7];
		$suma_bo = $suma_bo + $matriz_item[$i][15];
		
		$suma_bono = $suma_bono + $matriz_item[$i][15];
		$suma_cantidad = $suma_cantidad + $matriz_item[$i][7];
		$suma_pu = $suma_pu + $matriz_item[$i][9]/$matriz_item[$i][7];
		$suma_costou = $suma_costou + $matriz_item[$i][11]/$matriz_item[$i][7];
		$suma_comiu = $suma_comiu + $matriz_item[$i][14]/$matriz_item[$i][7];
		$suma_margenu = $suma_margenu + $matriz_item[$i][13]/$matriz_item[$i][7];
		$suma_margenp = $suma_margenp + $total_margen_100;
	    
		$suma_mg_sal = $suma_mg_sal + $matriz_item[$i][17];
		$suma_pc_sal = $suma_pc_sal + $matriz_item[$i][15];
		//$suma_cc_sal = $suma_cc_sal + $matriz_item[$i][16];
		
		$suma_mg_tot = $suma_mg_tot + $total_margen;
		$suma_pc_tot = $suma_pc_tot + $total_precio;
		$suma_cc_tot = $suma_cc_tot + $total_costo;
		
		$suma_mg_par = $suma_mg_par + $matriz_item[$i][13];
		$suma_pc_par = $suma_pc_par + $matriz_item[$i][9];
		$suma_cc_par = $suma_cc_par + $matriz_item[$i][11];
		$suma_co_par = $suma_co_par + $matriz_item[$i][14];
		
		$suma_bono_par = $suma_bono_par + $matriz_item[$i][15];
		$suma_cantidad_par = $suma_cantidad_par + $matriz_item[$i][7];
		$suma_pu_par = $suma_pu_par + $matriz_item[$i][9]/$matriz_item[$i][7];
		$suma_costou_par = $suma_costou_par + $matriz_item[$i][11]/$matriz_item[$i][7];
		$suma_comiu_par = $suma_comiu_par + $matriz_item[$i][14]/$matriz_item[$i][7];
		$suma_margenu_par = $suma_margenu_par + $matriz_item[$i][13]/$matriz_item[$i][7];
		$suma_margenp_par = $suma_margenp_par + $total_margen_100;
	    
		$suma_mg_sal_par = $suma_mg_sal_par + $matriz_item[$i][17];
		$suma_pc_sal_par = $suma_pc_sal_par + $matriz_item[$i][15];
		//$suma_cc_sal_par = $suma_cc_sal_par + $matriz_item[$i][16];
		
		$suma_mg_tot_par = $suma_mg_tot_par + $total_margen;
		$suma_pc_tot_par = $suma_pc_tot_par + $total_precio;
		$suma_cc_tot_par = $suma_cc_tot_par + $total_costo;
	  	$color++;
		$i++;
		$k++;
	}//fin while
	$j++;
	?>
 <tr BGCOLOR='#ffcccc'>
 <?php if($combinar == 1) { //if combinar = 1 ?>
 <td colspan="4"><b>Total Periodo Vendedor <?php echo $matriz_item[$i-1][6]; ?></b></td>
 <?php } //fin if combinar = 1
 	   if($combinar == 2) { //if combinar = 2 ?>
 <td colspan="4"><b>Total Periodo Cliente <?php echo $matriz_item[$i-1][4]; ?></b></td>
 <?php } //fin if combinar = 2
 	   if($combinar == 3) { //if combinar = 3 ?>
 <td colspan="4"><b>Total Periodo Almacen <?php echo $matriz_item[$i-1][19]; ?></b></td>
 <?php } //fin if combinar = 3 
 	   if($combinar == 4) { //if combinar = 4 ?>
 <td colspan="4"><b>Total Periodo Punto o Local de venta <?php echo $matriz_item[$i-1][21]; ?></b></td>
 <?php } //fin if combinar = 4 
 	   if($combinar == 5) { //if combinar = 5 ?>
 <td colspan="4"><b>Total Periodo Ciudad <?php echo $matriz_item[$i-1][23]; ?></b></td>
 <?php } //fin if combinar = 5 
 	   if($combinar == 6) { //if combinar = 6?>
 <td colspan="4"><b>Total Periodo Familia <?php echo $matriz_item[$i-1][25]; ?></b></td>
 <?php } //fin if combinar = 6 ?>
 <!--
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc_sal_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc_sal_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg_sal_par,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 -->
 <?php if($combinar <= 6) {//if menor 6 2 ?>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_bono_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cantidad_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pu_par/($k-1),$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_costou_par/($k-1),$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_comiu_par/($k-1),$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_co_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_margenu_par/($k-1),$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_margenp_par/($k-1),2)); ?></td>
 <?php }//fin if menor 6 2 ?> 
 <!--
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc_tot_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc_tot_par,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg_tot_par,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 -->
 </tr>
 <?php
 if($combinar == 7 || $combinar == 8 || $combinar == 9 || $combinar == 10) {//if combinar = 7
 	$mat_fam[$fa][1] = $matriz_item[$i-1][24]; //codigo
	$mat_fam[$fa][2] = $matriz_item[$i-1][25]; //nombre
	$mat_fam[$fa][3] = $suma_cantidad_par; //cantidad
	$aux[$fa] = $suma_cantidad_par; //cantidad vector para ordenar
	$mat_fam[$fa][4] = $suma_pu_par/($k-1); //precio unitario
	$mat_fam[$fa][5] = $suma_pc_par; //precio x cant
	$mat_fam[$fa][6] = $suma_costou_par/($k-1); //costo unitario
	$mat_fam[$fa][7] = $suma_cc_par; //costo x cant
	$mat_fam[$fa][8] = $suma_comiu_par/($k-1); //comision unitario
	$mat_fam[$fa][9] = $suma_co_par; //comision x cant
	$mat_fam[$fa][10] = $suma_margenu_par/($k-1); //margen unitario
	$mat_fam[$fa][11] = $suma_mg_par; //margen x cant
	$mat_fam[$fa][12] = $suma_margenp_par/($k-1); //margen %
	$mat_fam[$fa][13] = $suma_bono_par; //bonificacion
	$fa++;
	 	
 }//fin if combinar = 7
	$suma_mg_par = 0;
	$suma_pc_par = 0;
	$suma_cc_par = 0;
	$suma_co_par = 0;
	
	$suma_bono_par = 0;
	$suma_cantidad_par = 0;
	$suma_pu_par = 0;
	$suma_costou_par = 0;
	$suma_comiu_par = 0;
	$suma_margenu_par = 0;
	$suma_margenp_par = 0;
	    
	$suma_mg_sal_par = 0;
	$suma_pc_sal_par = 0;
	$suma_cc_sal_par = 0;
		
	$suma_mg_tot_par = 0;
	$suma_pc_tot_par = 0;
	$suma_cc_tot_par = 0;	
	}//fin while fin_it
	
	$fin_fa = $fa - 1;
	$f = 0;
	
	//ordeno cuando es 1
	if($orden == 1) {
		array_multisort($aux, SORT_DESC, $mat_fam);	
	}
	
	//aqui imprimo cuando es familia, subfamilia, grupo, subgrupo
if($combinar == 7 || $combinar == 8 || $combinar == 9 || $combinar == 10) {//if combinar = 72
	while($f <= $fin_fa){//while f
	$codigo = $mat_fam[$f][1];
	 if($color2 % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $mat_fam[$f][1]);//cod
		} else {
		printf("<tr><td align='center'>%s</td>", $mat_fam[$f][1]);//cod
		}//cierra if color
	printf("<td>%s</td>", $mat_fam[$f][2]);//nombre
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][13],$n_cantidad));//bonificacion
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][3],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][4],$n_decimales));//precio unitario
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][5],$n_decimales));//precio x cant
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][6],$n_decimales));//costo unitario
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][7],$n_decimales));//costo x cant
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][8],$n_decimales));//comision unitario
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][9],$n_decimales));//comision x cant
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][10],$n_decimales));//margen unitario
	printf("<td align='right'>%s</td>", number_format($mat_fam[$f][11],$n_decimales));//margen x cant
	if($combinar == 7) {//if comb7
		printf("<td align='right'><a href='report.php?rep=14&tipo=1&familia_rev=$codigo&fechaini_rev=$fechaini&fechafin_rev=$fechafin&combinar_rev=6&orden_rev=$orden&asientocc_rev=$asientocc&otra_moneda_rev=$otra_moneda&item_rev=$item&tipo_nota_rev=$tipo_nota&contexto_rev=$cod_contexto&marca_rev=$marca&modelo_rev=$modelo&usuario_rev=$usuario&token=$token' title='Reporte Ventas por Item'>%s</a></td></tr>", number_format($mat_fam[$f][12],2));//margen %
	} else {
		printf("<td align='right'>%s</td></tr>", number_format($mat_fam[$f][12],2));//margen %
	}//fin if comb7
	$color2++;
	$f++;
	}//fin while f
}//fin if combinar = 72

?>
 <?php if($combinar <= 6) { ?>
 <tr BGCOLOR='#ffcccc'><td colspan="4"><b>Totales</b></td>
 <?php } else { ?>
 <tr BGCOLOR='#ffcccc'><td colspan="2"><b>Totales</b></td>
 <?php } ?>
 <!--
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc_sal,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc_sal,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg_sal,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 -->
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_bo,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_ca,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_co,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 <!--
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_pc_tot,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_cc_tot,$n_decimales)); ?></td>
 <td align="right"><?php printf("<b>%s</b>", number_format($suma_mg_tot,$n_decimales)); ?></td>
 <td>&nbsp;</td>
 -->
 </tr>
 </tbody>
 </table>
         

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



// inicio muestra detalle

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

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

if ($combinar_det == 0) { //if combinar_det = 0
$valor_cli_det = ' ';
$valor_ven_det = ' ';
$valor_alm_det = ' ';
$valor_loc_det = ' ';
$valor_ciu_det = ' ';
$nom_det = 'Item';
}//fin if combinar_det = 0
if ($combinar_det == 1) { //if combinar_det = 1
$valor_cli_det = ' ';
$valor_ven_det = ' c.codSeller = ' .$cod_varios_det. ' and ';
$valor_alm_det = ' ';
$valor_loc_det = ' ';
$valor_ciu_det = ' ';
$nom_det = 'Vendedor';
}//fin if combinar_det = 1
if ($combinar_det == 2) { //if combinar_det = 2
$valor_cli_det = ' c.codClient = ' .$cod_varios_det. ' and ';
$valor_ven_det = ' ';
$valor_alm_det = ' ';
$valor_loc_det = ' ';
$valor_ciu_det = ' ';
$nom_det = 'Cliente';
}//fin if combinar_det = 2
if ($combinar_det == 3) { //if combinar_det = 3
$valor_cli_det = ' ';
$valor_ven_det = ' ';
$valor_alm_det = ' c.codWarehouse = ' .$cod_varios_det. ' and ';
$valor_loc_det = ' ';
$valor_ciu_det = ' ';
$nom_det = 'Almacen';
}//fin if combinar_det = 3
if ($combinar_det == 4) { //if combinar_det = 4
$valor_cli_det = ' ';
$valor_ven_det = ' ';
$valor_alm_det = ' ';
$valor_loc_det = ' c.codSalesPlace = ' .$cod_varios_det. ' and ';
$valor_ciu_det = ' ';
$nom_det = 'Punto o Local de venta';
}//fin if combinar_det = 4
if ($combinar_det == 5) { //if combinar_det = 5
$valor_cli_det = ' ';
$valor_ven_det = ' ';
$valor_alm_det = ' ';
$valor_loc_det = ' ';
$valor_ciu_det = ' d.codCityLocation = ' .$cod_varios_det. ' and ';
$nom_det = 'Ciudad';
}//fin if combinar_det = 5
if ($combinar_det == 6) { //if combinar_det = 6
$valor_cli_det = ' ';
$valor_ven_det = ' ';
$valor_alm_det = ' ';
$valor_loc_det = ' ';
$valor_ciu_det = ' ';
$familia_det = $cod_varios_det; //el cod de la familia tiene que ser el mismo que el enviado desde el detalle porque agrupa por familia
$nom_det = 'Familia';
}//fin if combinar_det = 0

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

if ($tipo_nota_det == 0) { //if tipo nota
	$nom_tipo_nota_det = 'Todos';
	$valor_tipo_nota_det = ' ';
  } else { 
  	$valor_tipo_nota_det = ' c.codType = '.$tipo_nota_det.' and ';
	//nombre de tipo de nota
$resulttipo = mysqli_query($link, "select pkyOrderNoteType as codigo, fldName as tipo
from 
slsOrderNoteType
where
pkyOrderNoteType = '$tipo_nota_det' and 
sysEnabled = 1 and sysAuthorized = 1
order by tipo;");
	while ($row = mysqli_fetch_array($resulttipo)) {
	$nom_tipo_nota_det = $row['tipo'];
	}
	mysqli_free_result($resulttipo);
  } //fin if tipo nota

if ($marca_det == 0) { // if marca
	$nom_marca_det = 'Todos';
	$valor_marca_det = ' ';
} else {
	//nombre marca
	$result5 = mysqli_query($link, "select pkyBrand as cod, fldName as marca 
							from invBrand 
							where 
							pkyBrand = '$marca_det' and 
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result5)) {
		$nom_marca_det = $row['marca'];
	}
	mysqli_free_result($result5);
	$valor_marca_det = ' b.codBrand = ' .$marca_det. ' and ';
} //fin if marca

if ($modelo_det == 0) { // if modelo
	$nom_modelo_det = 'Todos';
	$valor_modelo_det = ' ';
} else {
	//nombre modelo
	$result6 = mysqli_query($link, "select pkyBrandModel as cod, fldName as modelo 
							from invBrandModel 
							where 
							pkyBrandModel = '$modelo_det' and 
							sysEnabled = 1 and sysAuthorized = 1;");
	while ($row = mysqli_fetch_array($result6)) {
		$nom_modelo_det = $row['modelo'];
	}
	mysqli_free_result($result6);
	$valor_modelo_det = ' b.codBrandModel = ' .$modelo_det. ' and ';
} //fin if modelo

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

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

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


$resultdet = mysqli_query($link, "select c.pkySalesNote as codigo, a.fldQuantity as cantidad,
a.fldPrice as precio, a.fldDiscount as descuento,
a.fldTotalNetPrice as total, b.fldName as item, b.fldFactoryKey as cod_fabrica, 
c.fldDate as fecha, c.fldNumber as nro_doc, 
c.codClient as cod_cliente, 
d.fldName as cliente, c.codAccountReceivable as cod_cxc, 
c.codAccountEntry as cod_asiento, c.codItemMovement as cod_mov_mercaderia, 
e.fldName as moneda, c.codCurrency as cod_moneda, 
c.codExchangeRate as cod_tc, c.codWarehouse as cod_alm, 
f.fldName as almacen, c.codSeller as cod_vendedor, 
case when fldMiddleName is NULL then concat(g.fldLastName,', ',g.fldFirstName) else concat(g.fldLastName,' ',g.fldMiddleName,', ',g.fldFirstName) end as vendedor, 
c.codSalesPlace as cod_local, h.fldName as local, 
d.codCityLocation as cod_ciudad, i.fldName as ciudad, 
b.codFamily as cod_familia, j.fldName as familia, 
c.codInvoice as cod_fac, c.codPettyCashMovement as cod_mov_caja, 
c.codCheck as cod_cheque, c.codBankMovement as cod_mov_banco 
from
slsSalesNoteDetail a, invItem b, slsSalesNote c, 
agnCompany d, actCurrency e, invWarehouse f, 
agnPerson g, slsSalesPlace h, regCity i, invItemCategory j
where 
$valor_fecha_ini_det 
$valor_fecha_fin_det 
$valor_cli_det 
$valor_ven_det 
$valor_alm_det 
$valor_loc_det 
$valor_ciu_det 
$valor_tipo_nota_det 
$valor_familia_det 
$valor_subfamilia_det 
$valor_grupo_det 
$valor_subgrupo_det 
$valor_contexto_det 
$valor_marca_det
$valor_modelo_det 
a.codItem = b.pkyItem and 
a.codItem = '$cod_item_det' and 
a.codSalesNote = c.pkySalesNote and 
c.codClient = d.pkyCompany and 
c.codCurrency = e.pkyCurrency and 
c.codWarehouse = f.pkyWarehouse and 
c.codSeller = g.pkyPerson and 
c.codSalesPlace = h.pkySalesPlace and 
d.codCityLocation = i.pkyCity and 
b.codFamily = j.pkyItemCategory and
c.sysEnabled = 1 and c.sysAuthorized = 1
order by fecha, cliente, vendedor;");
$matriz_det = array();
$i = 1;

		while ($row = mysqli_fetch_array($resultdet)) {
		$matriz_det[$i][1] = $row['codigo'];
		$matriz_det[$i][2] = $row['nro_doc'];
		$matriz_det[$i][3] = $row['item'];
		$matriz_det[$i][4] = $row['fecha'];
		$matriz_det[$i][5] = $row['cliente'];
		$matriz_det[$i][6] = $row['cod_cxc'];
		$matriz_det[$i][7] = $row['cantidad'];
		$matriz_det[$i][8] = $row['precio'];
		$matriz_det[$i][9] = $row['descuento'];
		$matriz_det[$i][10] = $row['total'];
		$matriz_det[$i][11] = $row['moneda'];
		$matriz_det[$i][12] = $row['cod_moneda'];
		$matriz_det[$i][13] = $row['cod_tc'];
		$cod_tc = $matriz_det[$i][13];
		$cod_moneda_base = $matriz_det[$i][12];
		//por alguna razon estos valores deben ir antes de la comprobacion de la moneda sino se pierden
		$matriz_det[$i][15] = $row['almacen'];
		$matriz_det[$i][16] = $row['vendedor'];
		$matriz_det[$i][17] = $row['local'];
		$matriz_det[$i][18] = $row['ciudad'];
		$matriz_det[$i][19] = $row['cod_asiento'];
		$matriz_det[$i][20] = $row['cod_mov_mercaderia'];
		$matriz_det[$i][21] = $row['cod_fac'];//cod factura
		$matriz_det[$i][22] = $row['cod_mov_caja'];//cod movimiento de caja
		$matriz_det[$i][23] = $row['cod_cheque'];//cod cheque
		$matriz_det[$i][24] = $row['cod_mov_banco'];//cod movimiento de banco
		$matriz_det[$i][25] = $row['familia'];//familia
		$matriz_det[$i][26] = $row['cod_fabrica'];//cod fabrica
		
		if($matriz_det[$i][12] != $otra_moneda_det) {
			//valores de conversion tipo de cambio a cada fecha de venta o cotizacion
			$resulttc = mysqli_query($link, "SELECT pkyExchangeRateDetail as codigotc, codBaseCurrency as monedabase, codTargetCurrency as monedacambio, fldRate as tc
			from
			actExchangeRateDetail
			where
			codExchangeRate = '$cod_tc' and
			codBaseCurrency = '$otra_moneda_det' and
			codTargetCurrency = '$cod_moneda_base' and
			sysEnabled = 1 AND sysAuthorized = 1;");
			while ($row = mysqli_fetch_array($resulttc)) {
				$matriz_det [$i][14] = $row['tc'];//valor a multiplicar del tc 
				}
				mysqli_free_result($resulttc);
		} else {
			$matriz_det[$i][14] = 1;
		}
		$i++;
		}
		mysqli_free_result($resultdet);
		$fin_det = $i - 1;
?>
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><?php echo $mostrar_logo_reportes; ?>
</td><td align="right"><b>Fecha: <?php echo date("Y-m-d"); ?><br/>Hora: <?php echo date("H:i:s"); ?><br/>Usuario: <?php echo $usuario_det; ?></b>
</td></tr></table>
<p><br /><center><font color="#000099" size="+1"><b>Detalle Ventas Item</b></font></center></p>
<table border="0" cellpadding="2" align="center" width="100%">
<tr>
<td>	
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Item: </b><?php echo $cod_item_det; ?> - <?php echo $matriz_det[1][26]; ?> - <?php echo $matriz_det[1][3]; ?></TD>
        <TD width="25%"><b>Tipo: </b><?php echo $nom_tipo_nota_det; ?></TD>
        <TD width="25%"><?php echo $nom_fecha_det; ?></TD>
        <TD width="25%"><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
        <TR>
        <TD><b>Familia: </b><?php echo $nom_familia_det; ?></TD>
        <TD><b>Sub Familia: </b><?php echo $nom_subfamilia_det; ?></TD>
        <TD><b>Grupo: </b><?php echo $nom_grupo_det; ?></TD>
        <TD><b>Sub Grupo: </b><?php echo $nom_subgrupo_det; ?></TD>
        </TR>
        <TR>
		<TD><b>Marca: </b><?php echo $nom_marca_det; ?></TD>
        <TD><b>Modelo: </b><?php echo $nom_modelo_det; ?></TD>
        <TD><b>Agrupar Item con: </b><?php echo $nom_det; ?></TD>
        <TD><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
        </TR>
    </table>

</td>
<!--
<td valign="top" width="150">

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $ultimo_tc; ?></a> (<?php echo $tc_fecha; ?> - <?php echo $tc_hora; ?>)<br/ >
        <table border="0" cellpadding="2" align="center">
            <?php
            for($m = 1; $m <= $fin_m; $m++) {
            printf("<tr><td align='left'>1 %s</td>", $ma_tc [$m][1]);//moneda base
            printf("<td align='center'>%s</td>", ' = ');//letra a
            printf("<td align='left'>%s %s</td>", number_format($ma_tc [$m][3],$n_tipocambio), $ma_tc [$m][2]);//moneda target y tasa
            //printf("<td align='right'>%s</td></tr>", number_format($ma_tc [$m][3],$n_tipocambio));//tasa
            }
            ?>
        </table>
    </TD>
    </tr>
	</table>
    
</td>
-->
</tr>
</table>
<br />
<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
    <TD align="center"><b>Cod.</b></TD>
    <TD align="center"><b>Nro. Doc.</b></TD>
    <TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Familia</b></TD>
    <TD align="center"><b>Cliente</b></TD>
    <TD align="center"><b>Vendedor</b></TD>
    <TD align="center"><b>Almac&eacute;n</b></TD>
    <TD align="center"><b>Punto o Local de venta</b></TD>
    <TD align="center"><b>Ciudad</b></TD>
    <TD align="center"><b>CxC</b></TD>
    <TD align="center"><b>Asiento</b></TD>
    <TD align="center"><b>Mov. Merc.</b></TD>
    <TD align="center"><b>Fac.</b></TD>
    <TD align="center"><b>Mov. Caja</b></TD>
    <TD align="center"><b>Cheq.</b></TD>
    <TD align="center"><b>Mov. Banco</b></TD>
    <TD align="center"><b>Cant.</b></TD>
    <TD align="center"><b>Mon.</b></TD>
    <TD align="center"><b>Precio</b></TD>
    <TD align="center"><b>Desc. %</b></TD>
    <TD align="center"><b>Total</b></TD>
    <?php if($otra_moneda_det != 0){ ?>
    <TD align="center"><b>Tasa a <?php echo $nom_otra_moneda; ?></b></TD>
    <TD align="center"><b>Total en <?php echo $nom_otra_moneda; ?></b></TD>
    <?php } ?>
    </TR>
    </thead>
    <tbody class="marcafila">

    <?php
	$suma_total = 0;
	$suma_total_om = 0;
	$suma_cant = 0;
	$color = 2;
	for ($i = 1; $i <= $fin_det; $i++) { //for
		$codigo_nota_venta = $matriz_det[$i][1];
		$codigo_cxc = $matriz_det[$i][6];
		$codigo_asiento = $matriz_det[$i][19];
		$codigo_mov_mercaderia = $matriz_det[$i][20];
		$codigo_mov_caja = $matriz_det[$i][22];
		$codigo_mov_banco = $matriz_det[$i][24];
		$codigo_factura = $matriz_det[$i][21];
		$cod_cheque = $matriz_det[$i][23];
		if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'><a href='../../ModuleSales/VoucherSalesNote/index.php?pkySalesNote=$codigo_nota_venta&user=$usuario_det&token=$token' title='Nota de Venta'>%s</a></td>", $matriz_det[$i][1]);//cod
		} else {
		printf("<tr><td align='center'><a href='../../ModuleSales/VoucherSalesNote/index.php?pkySalesNote=$codigo_nota_venta&user=$usuario_det&token=$token' title='Nota de Venta'>%s</a></td>", $matriz_det[$i][1]);//cod
		}//fin if color
		printf("<td align='center'>%s</td>", $matriz_det[$i][2]);//numero documento
		printf("<td align='right'>%s</td>", $matriz_det[$i][4]);//fecha
		printf("<td>%s</td>", $matriz_det[$i][3]);//item
		printf("<td>%s</td>", $matriz_det[$i][25]);//familia
		printf("<td>%s</td>", $matriz_det[$i][5]);//cliente
		printf("<td>%s</td>", $matriz_det[$i][16]);//vendedor
		printf("<td>%s</td>", $matriz_det[$i][15]);//almacen
		printf("<td>%s</td>", $matriz_det[$i][17]);//punto o local de venta
		printf("<td>%s</td>", $matriz_det[$i][18]);//ciudad
		printf("<td align='right'><a href='../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=$codigo_cxc&user=$usuario_det&token=$token' title='Nota de Cuenta por Cobrar'>%s</a></td>", $matriz_det[$i][6]);//cxc
		printf("<td align='right'><a href='../../ModuleAccounting/VoucherAccountEntry/index.php?pkyAccountEntry=$codigo_asiento&showCC=$asientocc_det&user=$usuario_det&token=$token' title='Asiento Contable'>%s</a></td>", $matriz_det[$i][19]);//asiento
		printf("<td align='right'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$codigo_mov_mercaderia&showBatch=0&printAccountEntry=0&user=$usuario_det&token=$token' title='Movimiento de Mercadería con Lotes'>%s</a></td>", $matriz_det[$i][20]);//movimiento de mercaderia (printAccountEntry=0 porque no genera asiento, lo genera la nota de pedido) 
		
		printf("<td align='right'><a href='../../ModuleTaxes/VoucherSalesLedger/index.php?pkySalesLedger=$codigo_factura&sheetSize=$formato_factura&head=$muestra_cabecera&user=$usuario_det&token=$token' title='Factura'>%s</a></td>", $matriz_det[$i][21]);//factura
		printf("<td align='right'><a href='../../ModulePettyCash/VoucherPettyCashMovement/index.php?pkyPettyCashMovement=$codigo_mov_caja&user=$usuario_det&token=$token' title='Movimiento de Caja'>%s</a></td>", $matriz_det[$i][22]);//mov de caja
		printf("<td align='right'><a href='../../ModuleTreasury/VoucherCheck/index.php?pkyCheck=$cod_cheque&user=$usuario_det&token=$token' title='Cheque'>%s</a></td>", $matriz_det[$i][23]);//cheque
		printf("<td align='right'><a href='../../ModuleTreasury/VoucherBankMovement/index.php?pkyBankMovement=$codigo_mov_banco&user=$usuario_det&token=$token' title='Nota de Movimiento Bancario'>%s</a></td>", $matriz_det[$i][24]);//mov de banco
		printf("<td align='right'>%s</td>", number_format($matriz_det[$i][7],$n_cantidad));//cantidad
		printf("<td>%s</td>", $matriz_det[$i][11]);//moneda
		printf("<td align='right'>%s</td>", number_format($matriz_det[$i][8],$n_decimales));//precio
		printf("<td align='right'>%s</td>", number_format($matriz_det[$i][9], $n_descuento));//descuento
				
		if($otra_moneda_det != 0){ //if otra moneda
			printf("<td align='right'>%s</td>", number_format($matriz_det[$i][10], $n_decimales));//total
			printf("<td align='right'>%s</td>", number_format($matriz_det[$i][14], $n_tipocambio));//tasa
			printf("<td align='right'>%s</td></tr>", number_format($matriz_det[$i][10] * $matriz_det[$i][14], $n_decimales));//total otra moneda
			}//fin if otra moneda 
			else { //else otra moneda
		 	printf("<td align='right'>%s</td></tr>", number_format($matriz_det[$i][10], $n_decimales));//total
		 }//fin if otra moneda
		 $suma_total = $suma_total + $matriz_det[$i][10];
		 $suma_total_om = $suma_total_om + $matriz_det[$i][10] * $matriz_det[$i][14];
		 $suma_cant = $suma_cant + $matriz_det[$i][7];
		 $color++;
		}//fin for

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

</body>
</html>
