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

<script language="JavaScript">
 
function oculta(id){
	 var elDiv = document.getElementById(id); //se define la variable "elDiv" igual a nuestro div
	 elDiv.style.display='none'; //damos un atributo display:none que oculta el div	 
	}
 
function muestra(id){
	 var elDiv = document.getElementById(id); //se define la variable "elDiv" igual a nuestro div
	 elDiv.style.display='block';//damos un atributo display:block que  el div	 
	}
 
window.onload = function(){/*hace que se cargue la función */
/* "Mandamos como parametro el nombre de la Div para ocultar" */
muestra('Pinsumosu');
muestra('Pinsumose');
muestra('Pcostosi');
}
</script>

</head>
<?php

include "../../conn.php";
include "../../general.php";
include "../../token.php";

$rep=$_GET["rep"];
$tipo=$_GET["tipo"];
$item=$_POST["item"];
$fechaini=$_POST["fechaini"];
$fechafin=$_POST["fechafin"];
//$usuario=$_POST["usuario"];
$otra_moneda=$_POST["otra_moneda"];
$ordenar=$_POST["ordenar"];
$agrupar=$_POST["agrupar"];
$agruparlinea=$_POST["agruparlinea"];
$linea=$_POST["linea"];
$insumosu_ver=$_POST["insumosu_ver"];
$insumose_ver=$_POST["insumose_ver"];
$costosi_ver=$_POST["costosi_ver"];
$cod_contexto=$_POST["contexto"];

//$usuario_det=$_GET["usuario_det"];
$item_det=$_GET["item_det"];
$otra_moneda_det=$_GET["otra_moneda_det"];
$cod_prod_det=$_GET["cod_prod_det"];
$cod_contexto_det=$_GET["contexto_det"];

//para linea seleccion
if(!empty($_POST['linea_seleccion'])) {
	$seleccion_mat = array ();
	// Contar numero de checkboxes seleccionados.
	$contar_seleccion = count($_POST['linea_seleccion']);
	$txt_seleccion = 'Seleccionadas '.$contar_seleccion.' líneas';
	// Bucle para vaciar los checkboxes seleccionados.
	$i = 1;
	foreach($_POST['linea_seleccion'] as $seleccion) {
		$seleccion_mat[$i] = $seleccion;
		$i++;
	}
	$fin_selec = $i - 1;
} else {
	$fin_selec = 0;
	$txt_seleccion = '';
}


?>
<body>

	<?php
	
//Inicio reporte produccion por item


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

	//control de la seleccion de incio, antes estaba arriba if($agruparlinea == 1) { $linea = 0; }
	
	if($agrupar == 1) { $agruparlinea = 1; }
	if($agruparlinea == 1) { $linea = 0; }

//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);
	
//tasa de cambio
if($otra_moneda == $cod_moneda_principal) {// if tasa
	$tasa = 1;
} else {// else if tasa
$resultcambio = mysqli_query($link, "select fldRate as tasa 
from actExchangeRateDetail 
where 
codExchangeRate = '$tc_hoy' and 
codBaseCurrency = '$otra_moneda' and 
codTargetCurrency = '$cod_moneda_principal' and 
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultcambio)) {
	$tasa = $row['tasa'];
	}
	mysqli_free_result($resultcambio);
}// fin if tasa


if ($ordenar == 0) { //if ordenar = 0
	$valor_ordenar = 'order by item';
	$valor_ordenar2 = 'order by concepto';
	$nom_orden = 'Item';
} //fin if ordenar = 0
if ($ordenar == 1) { //if ordenar = 1
  	$valor_ordenar = 'order by cod_item';
	$valor_ordenar2 = 'order by concepto';
	$nom_orden = 'C&oacute;digo de Item';
} //fin if ordenar = 1
if ($ordenar == 2) { //if ordenar = 2
	$valor_ordenar = 'order by cod_fab';
	$valor_ordenar2 = 'order by concepto';
	$nom_orden = 'C&oacute;digo de F&aacute;brica';
} //fin if ordenar = 2

if ($agrupar == 0) { //if agrupar = 00
	if ($ordenar == 3) { //if ordenar = 3
		$valor_ordenar = 'order by item';
		$valor_ordenar2 = 'order by concepto';
		$nom_orden = 'Item';
	} //fin if ordenar = 3
} else {
	if ($ordenar == 3) { //if ordenar = 3
		$valor_ordenar = 'order by fecha, item';
		$valor_ordenar2 = 'order by fecha, concepto';
		$nom_orden = 'Fecha Orden de Producci&oacute;n (solo en NO agrupado)';
	} //fin if ordenar = 3
} //fin if agrupar = 00

if ($agrupar == 0) { //if agrupar = 0
	$nom_agrupar = 'Si';
} else {
	$nom_agrupar = 'No';
} //fin if agrupar = 0

if ($agruparlinea == 0) { //if agruparlinea = 0
	$nom_agruparlinea = 'Si (Una o Todas)';
	$nro_agruparlinea = 6;
	$valor_agruparlinea = ', cod_lin';
	$valor_ordenar = 'order by linea, item';
	$valor_ordenar2 = 'order by linea, concepto';
	$nom_orden = 'Línea e Item';
} //fin if agruparlinea = 0
if ($agruparlinea == 2) { //if agruparlinea = 2
	$nom_agruparlinea = 'Si ('.$txt_seleccion.')';
	$nro_agruparlinea = 4;
	$valor_agruparlinea = '';
} //fin if agruparlinea = 2
if ($agruparlinea == 1) { //if agruparlinea = 1
	$nom_agruparlinea = 'No';
	$nro_agruparlinea = 4;
	$valor_agruparlinea = '';
} //fin if agruparlinea = 1


//item
if($item == 0) {//if item
	$nom_item = 'Todos';
	$valor_item = '';
	$valor_item2 = '';
} else {//else if item
	$resultitem = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
	from
	invItem
	where
	pkyItem = '$item' and
	sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultitem)) {
	$nom_item = $row['cod_item'].' - '.$row['cod_fab'].' - '.$row['item'];
	}
	mysqli_free_result($resultitem);
	$valor_item = ' b.codItem = '.$item.' and ';
	$valor_item2 = ' g.codItem = '.$item.' and ';
}//fin if item

//verificar si hay seleccion de lineas o no 
if($agruparlinea == 0 || $agruparlinea == 1){ //if agrup
	//linea
	if($linea == 0) {//if item
		$nom_linea = 'Todos';
		$valor_linea = '';
	} else {//else if item
		$resultlinea = mysqli_query($link, "select pkyProductionLine as cod_linea, fldName as linea 
		from prdProductionLine
		where
		pkyProductionLine = '$linea' and
		sysEnabled = 1 and sysAuthorized = 1;");
			
		while ($row = mysqli_fetch_array($resultlinea)) {
		$nom_linea = $row['cod_linea'].' - '.$row['linea'];
		}
		mysqli_free_result($resultlinea);
		$valor_linea = ' a.codProductionLine = '.$linea.' and ';
	}//fin if linea
} else { //else if agrup
	//vemos si hay selección de lineas de producción
	if($fin_selec == 0) { //if comb
		$nom_linea = 'Todos';
		$valor_linea = '';
	} else { //else if comb
		//$valor_linea = 'a.codProductionLine = '.$cod_sucursal.' or ';
		for($i = 1; $i <= $fin_selec; $i++) {
			$sel_linea = $seleccion_mat[$i];
			$resultlinea = mysqli_query($link, "select pkyProductionLine as cod_linea, fldName as linea 
			from prdProductionLine
			where
			pkyProductionLine = '$sel_linea' and
			sysEnabled = 1 and sysAuthorized = 1;");
				
			while ($row = mysqli_fetch_array($resultlinea)) {
			$nom_linea = $nom_linea.'('.$row['cod_linea'].' - '.$row['linea'].') ';
			}
			mysqli_free_result($resultlinea);

			if($i != $fin_selec) {
			$valor_linea = $valor_linea.'a.codProductionLine = '.$sel_linea.' or ';
			} else {
			$valor_linea = $valor_linea.'a.codProductionLine = '.$sel_linea;	
			}
		}
		$valor_linea ='('.$valor_linea.') and ';
	} //fin if comb
} //fin agrup


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


if ($agrupar == 0) { //if agrupar 0	
//listado de produccion por item agrupado
//lista de items producidos
$result = mysqli_query($link, "SELECT t.cod_pro as cod_pro, t.nro_doc as nro_doc, t.fecha as fecha, t.cod_lin as cod_lin, t.linea as linea, t.cod_mov_sal as cod_mov_sal, t.cod_mov_ing as cod_mov_ing, t.cod_proy as cod_proy, t.cod_item as cod_item, t.item as item, t.cod_fab as cod_fab, sum(t.cantidad) as cantidad, sum(t.costo_insumos) as costo_insumos, sum(t.costo_extra) as costo_extra, (sum(t.costo_extra) + sum(t.costo_insumos)) / sum(t.cantidad) as costo_u, sum(t.costo_extra) + sum(t.costo_insumos) as costo, t.unidad as unidad
FROM 
(select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.fldDate as fecha, a.codProductionLine as cod_lin, e.fldName as linea, a.codItemMovementOut as cod_mov_sal, a.codItemMovementIn as cod_mov_ing, a.codProjection as cod_proy, b.codItem as cod_item, c.fldName as item, c.fldFactoryKey as cod_fab, (d.fldQuantity) as cantidad, (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut) as costo_insumos, (d.fldExtraCost) as costo_extra, ((d.fldExtraCost) + (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut)) / (d.fldQuantity) as costo_u, (d.fldExtraCost) + (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut) as costo, u.fldName as unidad
from
prdProductionOrder a, prdProductionOrderDetail b, invItem c, invItemMovementDetail d, prdProductionLine e, invStorageUnit u
where 
$valor_item 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = c.pkyItem and 
a.codItemMovementIn = d.codItemMovement and 
b.codItem = d.codItem and 
a.codProductionLine = e.pkyProductionLine and 
c.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t
group by cod_item $valor_agruparlinea
$valor_ordenar;");

//calculo del total para extraer el porcentaje este es 100%
$suma_porcentaje_total_insumos = 0;
while ($row = mysqli_fetch_array($result)) {//while 1
	$suma_porcentaje_total_insumos = $suma_porcentaje_total_insumos + $row['costo_insumos'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result, 0);


//lista de insumos 
$result2 = mysqli_query($link, "select e.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, sum(e.fldQuantity) as cantidad, sum(e.fldQuantity * c.fldCost) / sum(e.fldQuantity) as costo_u, sum(e.fldQuantity * c.fldCost) as costo, u.fldName as unidad, a.codProductionLine as cod_lin, f.fldName as linea 
from prdProductionOrder a, prdProductionOrderDetail b, invItemMovementDetail c, invItem d, prdProductionOrderDetailRecipe e, prdProductionLine f, invStorageUnit u
where 
$valor_item 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
a.codItemMovementOut = c.codItemMovement and 
a.pkyProductionOrder = e.codProductionOrder and 
b.pkyProductionOrderDetail = e.codProductionOrderDetail and 
e.codItem = c.codItem and 
e.codItem = d.pkyItem and 
a.codProductionLine = f.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by e.codItem $valor_agruparlinea
$valor_ordenar;");

//calculo del total para extraer el porcentaje, no se cuanto es lo calculo
$suma_porcentaje_insumos_utilizados = 0;
while ($row = mysqli_fetch_array($result2)) {//while 1
	$suma_porcentaje_insumos_utilizados = $suma_porcentaje_insumos_utilizados + $row['costo'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result2, 0);


//lista de insumos extra, no tiene que haber $valor_item
//hay dos querys porque el primero lista y el segundo es para ver si la suma es igual para mostrar costos
//aparentemente el valor $valor_agruparlinea no es necesario en ninguno de los dos querys
$result3 = mysqli_query($link, "select b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, sum(b.fldQuantity) as cantidad, sum(b.fldTotaCost) / sum(b.fldQuantity) as costo_u, sum(b.fldTotaCost) as costo, u.fldName as unidad, a.codProductionLine as cod_lin, e.fldName as linea, g.codItem AS cod_item2   
from prdProductionOrder a, prdExtraItem b, invItem d, prdProductionLine e, invStorageUnit u, prdProductionOrderDetail g
where  
$valor_item2 
$valor_linea  
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = d.pkyItem and 
a.codProductionLine = e.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.pkyProductionOrder = g.codProductionOrder AND 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by b.codItem $valor_agruparlinea
$valor_ordenar;");

//calculo del total para extraer el porcentaje, no se cuanto es lo calculo
$suma_porcentaje_insumos_extras = 0;
while ($row = mysqli_fetch_array($result3)) {//while 1
	$suma_porcentaje_insumos_extras = $suma_porcentaje_insumos_extras + $row['costo'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result3, 0);

//calculo los porcentaces para las columnas
$porcentaje_insumos_utilizados = $suma_porcentaje_insumos_utilizados / $suma_porcentaje_total_insumos;
$porcentaje_insumos_extras = $suma_porcentaje_insumos_extras / $suma_porcentaje_total_insumos;


//suma el total de los costos extras para ver si muestra con costos
$result31 = mysqli_query($link, "select b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, sum(b.fldQuantity) as cantidad, sum(b.fldTotaCost) / sum(b.fldQuantity) as costo_u, sum(b.fldTotaCost) as costo, u.fldName as unidad, 1 as grupo, a.codProductionLine as cod_lin, e.fldName as linea, g.codItem AS cod_item2  
from prdProductionOrder a, prdExtraItem b, invItem d, prdProductionLine e, invStorageUnit u, prdProductionOrderDetail g
where  
$valor_item2 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = d.pkyItem and 
a.codProductionLine = e.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.pkyProductionOrder = g.codProductionOrder AND 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by grupo;");
while ($row = mysqli_fetch_array($result31)) {
	$suma_costos_extras = $row['costo'];
	}
	mysqli_free_result($result31);

//lista de gastos indirectos
$result4 = mysqli_query($link, "select t.cod_con as cod_con, t.concepto as concepto, sum(t.monto) as monto, t.cod_item as cod_item, t.item as item, t.cod_fab as cod_fab, t.cod_lin as cod_lin 
from (
select b.codProductionConcept as cod_con, c.fldName as concepto, b.fldAmount as monto, b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.codProductionLine as cod_lin, e.fldName as linea   
from prdProductionOrder a, prdProductionOrderConcept b, prdProductionConcept c, invItem d, prdProductionLine e
where 
$valor_item 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codProductionConcept = c.pkyProductionConcept and 
b.codItem = d.pkyItem and 
a.codProductionLine = e.pkyProductionLine and 
a.sysEnabled = 1 and a.sysAuthorized = 1) t 
group by t.cod_con $valor_agruparlinea  
$valor_ordenar2;");


?>
<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>Producci&oacute;n 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="33%"><b>Item: </b><?php echo $nom_item; ?></TD>
        <TD width="33%"><b>Agrupado por Item y Concepto: </b><?php echo $nom_agrupar; ?></TD>
        <TD width="33%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        </TR>
        <TR> 
		<TD><b>L&iacute;nea de Producci&oacute;n: </b><?php echo $nom_linea; ?></TD>
		<TD><b>Agrupado por L&iacute;nea de Producci&oacute;n: </b><?php echo $nom_agruparlinea; ?></TD>
        <TD><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
		</TR>
        <TR> 
        <TD colspan="2"><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        <TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

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

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&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> 
	<?php if($agruparlinea == 0) { ?>
		<TD align="center" width="10%"><b>Cod. Línea</b></TD>
		<TD align="center"><b>Línea</b></TD>
		<TD align="center" width="10%"><b>Cod. Item</b></TD>
	<?php } else {?>
	<TD align="center" width="10%"><b>Cod.</b></TD>
	<?php } ?>

    <TD align="center"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Unidad</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
    <TD align="center"><b>Costo Insumos Utilizados</b></TD>
	<TD align="center"><b>Costo Insumos Extras</b></TD>
	<TD align="center"><b>Costo Total Insumos</b></TD>
    <TD align="center"><b>Costo Extra</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">

<?php

$color = 2;
$suma_cant = 0;
$suma_costins = 0;
$suma_costinsuti = 0;
$suma_costinsext = 0;
$suma_costex = 0;
$suma_costu = 0;
$suma_cost = 0;
//lista de items producidos
while ($row = mysqli_fetch_array($result)) {//while 1
	$cod_item = $row['cod_item'];
	
	if($agruparlinea == 0) {
		if($color % 2 == 0) { //if color
			printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_lin']);//cod item
		} else {
			printf("<tr><td align='center'>%s</td>", $row['cod_lin']);//cod item
		}//cierra if color
		printf("<td align='left'>%s</td>", $row['linea']);//cod item
		printf("<td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {

		if($color % 2 == 0) { //if color
			printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
		} else {
			printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
		}//cierra if color
	}
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa,$n_decimales));//costo insumos utilizados
	printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $porcentaje_insumos_extras * $tasa,$n_decimales));//costo insumos extras
	$suma_total_insumos = ($row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa) + ($row['costo_insumos'] * $porcentaje_insumos_extras * $tasa);
	printf("<td align='right'>%s</td>", number_format($suma_total_insumos, $n_decimales));//costo total insumos
	//printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $tasa,$n_decimales));//costo total insumos (antes calculaba así pero se pierde en los decimales)
	printf("<td align='right'>%s</td>", number_format($row['costo_extra'] * $tasa,$n_decimales));//costo extra
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
	$suma_total_costo = $suma_total_insumos + $row['costo_extra'] * $tasa;
	printf("<td align='right'>%s</td></tr>", number_format($suma_total_costo,$n_decimales));//costo
	//printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo (antes calculaba así pero se pierde en los decimales)
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costinsuti = $suma_costinsuti + $row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa;
	$suma_costinsext = $suma_costinsext + $row['costo_insumos'] * $porcentaje_insumos_extras * $tasa; 
	$suma_costins = $suma_costins + $suma_total_insumos;
	//$suma_costins = $suma_costins + $row['costo_insumos'] * $tasa; //(antes calculaba así pero se pierde en los decimales)
	$suma_costex = $suma_costex + $row['costo_extra'] * $tasa;
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
	//$suma_cost = $suma_cost + $row['costo'] * $tasa; //(antes calculaba así pero se pierde en los decimales)
	$suma_cost = $suma_cost + $suma_total_costo;
	
	$color++;
}//fin while 1
mysqli_free_result($result);	

?>
<tr BGCOLOR='#ffcccc'><td colspan="<?php echo $nro_agruparlinea; ?>"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costinsuti,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costinsext,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costins,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costex,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost,$n_decimales)); ?></td>
</tr>
</table>
<br />
<?php if ($insumosu_ver == 1) { //if insumos 1	?>
<b>Insumos utilizados: </b><button onclick="muestra('Pinsumosu')" class="boton">Mostrar</button> <button onclick="oculta('Pinsumosu')" class="boton">Ocultar</button> 
<br />
<div id="Pinsumosu">
<table border="1" align="center" cellpadding="2" width="100%">
 	<thead>
    <TR> 
 	<TD align="center" width="10%"><b>Cod.</b></TD>
    <TD align="center" width="10%"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Unidad</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">
<?php

//insumos utilizados
$color = 2;
$suma_cant = 0;
$suma_costu = 0;
$suma_cost1 = 0;

while ($row = mysqli_fetch_array($result2)) {//while 2
	$cod_item = $row['cod_item'];

	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
	printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
	$suma_cost1 = $suma_cost1 + $row['costo'] * $tasa;
	
	$color++;
}//fin while 2
mysqli_free_result($result2);	
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="4"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost1,$n_decimales)); ?></td>
</tr>
</table>
</div>
<br />
<?php } //fin if insumos 1 ?> 
<?php if ($insumose_ver == 1) { //if insumos 2	?>
<b>Insumos extras: </b><button onclick="muestra('Pinsumose')" class="boton">Mostrar</button> <button onclick="oculta('Pinsumose')" class="boton">Ocultar</button> 
<br />
<div id="Pinsumose">
<table border="1" align="center" cellpadding="2" width="100%" id="Pinsumose">
 	<thead>
    <TR> 
 	<TD align="center" width="10%"><b>Cod.</b></TD>
    <TD align="center" width="10%"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Unidad</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">
<?php

//insumos extras


$color = 2;
$suma_cant = 0;
$suma_costu = 0;
$suma_cost2 = 0;

//condicion para mostrar
$suma_muestra = $suma_cost1 + $suma_costos_extras;
//echo round($suma_cost1,4).' + '.round($suma_costos_extras,4).'<br>';
//echo round($suma_muestra,4).' = '.round($suma_costins,4).'<br>';
while ($row = mysqli_fetch_array($result3)) {//while 3
	$cod_item = $row['cod_item'];

	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	
	//muestra siempre con costos si se elije todos los items
	if($item == 0) {//if muestra 01
		printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
		printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
		printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo
			
		$suma_cant = $suma_cant + $row['cantidad'];
		$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
		$suma_cost2 = $suma_cost2 + $row['costo'] * $tasa;
	} else { //else if muestra 01 
		//compara si la suma es igual para mostrar con costos
		if(round($suma_muestra,4) == round($suma_costins,4)) {//if muestra 011
		printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
		printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
		printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo
			
		$suma_cant = $suma_cant + $row['cantidad'];
		$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
		$suma_cost2 = $suma_cost2 + $row['costo'] * $tasa;
		} else { //else if muestra 011 
		printf("<td>&nbsp;</td>");//cantidad blanco
		printf("<td>&nbsp;</td>");//costo unitario blanco
		printf("<td>&nbsp;</td></tr>");//costo blanco
		}//fin if muestra 011
	}//fin if muestra 01
	
	$color++;
}//fin while 3
mysqli_free_result($result3);	

//si la suma no es igual se muestra solo el total
/*
if(round($suma_muestra,4) != round($suma_costins,4)) {//if muestra 02
	//se resta el total de costos insumos utilizados e insumos extras menos costos insumos utilizados
	$suma_cost2 = $suma_costins - $suma_cost1;

}//fin if muestra 02
*/
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="4"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost2,$n_decimales)); ?></td>
</tr>
</table>
</div>
<br />
<?php } //fin if insumos 2 ?> 
<?php if ($costosi_ver == 1) { //if costos 1	?>
<b>Costos Indirectos: </b><button onclick="muestra('Pcostosi')" class="boton">Mostrar</button> <button onclick="oculta('Pcostosi')" class="boton">Ocultar</button> 
<br />
<div id="Pcostosi">
<table border="1" align="center" cellpadding="2" width="100%" id="Pcostosi">
 	<thead>
    <TR> 
 	<TD align="center" width="10%"><b>Cod.</b></TD>
    <TD align="center"><b>Concepto</b></TD>
    <TD align="center"><b>Monto</b></TD>
    <?php if($item != 0) {//if item no 0 ?>
    <TD align="center" width="10%"><b>Cod. Item</b></TD>
    <TD align="center" width="10%"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <?php }//fin if item no 0 ?>
    </TR>
	</thead>
    <tbody class="marcafila">
<?php
//costos indirectos
$color = 2;
$suma_cost = 0;

while ($row = mysqli_fetch_array($result4)) {//while 4
	$cod_con = $row['cod_con'];

	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_con']);//cod concepto
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_con']);//cod concepto
	}//cierra if color
	printf("<td align='left'>%s</td>", $row['concepto']);//concepto
	printf("<td align='right'>%s</td>", number_format($row['monto'] * $tasa,$n_decimales));//costo 
	if($item != 0) {//if item no 0
	printf("<td align='center'>%s</td>", $row['cod_item']);//cod item
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	}//fin if item no 0
	echo '</tr>';	
	$suma_cost = $suma_cost + $row['monto'] * $tasa;
	
	$color++;
}//fin while 4
mysqli_free_result($result4);	
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost,$n_decimales)); ?></td>
<?php if($item != 0) {//if item no 0 ?>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<?php }//fin if item no 0 ?>
</tr>
</table>
</div>
<?php } //fin if costos 1 ?>          
<?php

} //fin if agrupar 0




if ($agrupar == 1) { //if agrupar 1	
//listado de produccion por item sin agrupar
//lista de items producidos
$result = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.fldDate as fecha, a.codProductionLine as cod_lin, e.fldName as linea, a.codItemMovementOut as cod_mov_sal, a.codItemMovementIn as cod_mov_ing, a.codProjection as cod_proy, b.codItem as cod_item, c.fldName as item, c.fldFactoryKey as cod_fab, d.fldQuantity as cantidad, (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut) as costo_insumos, d.fldExtraCost as costo_extra, (d.fldExtraCost + (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut)) / d.fldQuantity as costo_u, d.fldExtraCost + (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut) as costo, u.fldName as unidad 
from
prdProductionOrder a, prdProductionOrderDetail b, invItem c, invItemMovementDetail d, prdProductionLine e, invStorageUnit u 
where 
$valor_item 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = c.pkyItem and 
a.codItemMovementIn = d.codItemMovement and 
b.codItem = d.codItem and 
a.codProductionLine = e.pkyProductionLine and 
c.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1
$valor_ordenar;");

//calculo del total para extraer el porcentaje este es 100%
$suma_porcentaje_total_insumos = 0;
while ($row = mysqli_fetch_array($result)) {//while 1
	$suma_porcentaje_total_insumos = $suma_porcentaje_total_insumos + $row['costo_insumos'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result, 0);


//lista de codigos de ordenes de produccion de items producidos, para filtrar en insumos extras (mismo query de lista de items producidos
$result00 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.fldDate as fecha, a.codProductionLine as cod_lin, e.fldName as linea, a.codItemMovementOut as cod_mov_sal, a.codItemMovementIn as cod_mov_ing, a.codProjection as cod_proy, b.codItem as cod_item, c.fldName as item, c.fldFactoryKey as cod_fab, d.fldQuantity as cantidad, d.fldCost * d.fldQuantity as costo_insumos, d.fldExtraCost as costo_extra, d.fldTotaCost / d.fldQuantity as costo_u, d.fldTotaCost as costo, u.fldName as unidad 
from
prdProductionOrder a, prdProductionOrderDetail b, invItem c, invItemMovementDetail d, prdProductionLine e, invStorageUnit u 
where 
$valor_item 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = c.pkyItem and 
a.codItemMovementIn = d.codItemMovement and 
b.codItem = d.codItem and 
a.codProductionLine = e.pkyProductionLine and 
c.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1
$valor_ordenar;");

$listap = 0;
while ($row = mysqli_fetch_array($result00)) {
	$listap = $listap.', '.$row['cod_pro'];
}
mysqli_free_result($result00);

$valor_producciones = 'a.pkyProductionOrder in ('.$listap.') and ';


//lista de insumos 
$result2 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.codProductionLine as cod_lin, f.fldName as linea, a.codItemMovementOut as cod_mov_sal, e.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.fldDate as fecha, e.fldQuantity as cantidad, c.fldCost as costo_u, e.fldQuantity * c.fldCost as costo, u.fldName as unidad  
from prdProductionOrder a, prdProductionOrderDetail b, invItemMovementDetail c, invItem d, prdProductionOrderDetailRecipe e, prdProductionLine f, invStorageUnit u
where  
$valor_item 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
a.codItemMovementOut = c.codItemMovement and 
a.pkyProductionOrder = e.codProductionOrder and 
b.pkyProductionOrderDetail = e.codProductionOrderDetail and 
e.codItem = c.codItem and 
e.codItem = d.pkyItem and 
a.codProductionLine = f.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1  
$valor_ordenar;");

//calculo del total para extraer el porcentaje, no se cuanto es lo calculo
$suma_porcentaje_insumos_utilizados = 0;
while ($row = mysqli_fetch_array($result2)) {//while 1
	$suma_porcentaje_insumos_utilizados = $suma_porcentaje_insumos_utilizados + $row['costo'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result2, 0);

//lista de insumos extra, no tiene que haber $valor_item
//hay dos querys porque el primero lista y el segundo es para ver si la suma es igual para mostrar costos
$result3 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.codProductionLine as cod_lin, f.fldName as linea, a.codItemMovementOut as cod_mov_sal, b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.fldDate as fecha, b.fldQuantity as cantidad, b.fldCost as costo_u, b.fldTotaCost as costo, u.fldName as unidad 
from prdProductionOrder a, prdExtraItem b, invItem d, prdProductionLine f, invStorageUnit u
where 
$valor_producciones 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = d.pkyItem and 
a.codProductionLine = f.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
$valor_ordenar;");

//calculo del total para extraer el porcentaje, no se cuanto es lo calculo
$suma_porcentaje_insumos_extras = 0;
while ($row = mysqli_fetch_array($result3)) {//while 1
	$suma_porcentaje_insumos_extras = $suma_porcentaje_insumos_extras + $row['costo'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result3, 0);

//calculo los porcentaces para las columnas
$porcentaje_insumos_utilizados = $suma_porcentaje_insumos_utilizados / $suma_porcentaje_total_insumos;
$porcentaje_insumos_extras = $suma_porcentaje_insumos_extras / $suma_porcentaje_total_insumos;


//suma el total de los costos extras para ver si muestra con costos
$result31 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.codProductionLine as cod_lin, f.fldName as linea, a.codItemMovementOut as cod_mov_sal, b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.fldDate as fecha, b.fldQuantity as cantidad, b.fldCost as costo_u, sum(b.fldTotaCost) as costo, u.fldName as unidad, 1 as grupo  
from prdProductionOrder a, prdExtraItem b, invItem d, prdProductionLine f, invStorageUnit u
where 
$valor_producciones 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = d.pkyItem and 
a.codProductionLine = f.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by grupo;");
while ($row = mysqli_fetch_array($result31)) {
	$suma_costos_extras = $row['costo'];
	}
	mysqli_free_result($result31);

//lista de gastos indirectos
$result4 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.fldDate as fecha, a.codProjection as cod_proy, b.codProductionConcept as cod_con, c.fldName as concepto, b.fldAmount as monto, b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.codProductionLine as cod_lin, e.fldName as linea
from prdProductionOrder a, prdProductionOrderConcept b, prdProductionConcept c, invItem d, prdProductionLine e
where  
$valor_item 
$valor_linea 
$valor_contexto 
a.fldDate >= '$fechaini' and 
a.fldDate <= '$fechafin' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codProductionConcept = c.pkyProductionConcept and 
b.codItem = d.pkyItem and 
a.codProductionLine = e.pkyProductionLine and 
a.sysEnabled = 1 and a.sysAuthorized = 1
$valor_ordenar2;");



?>
<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>Producci&oacute;n 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="33%"><b>Item: </b><?php echo $nom_item; ?></TD>
        <TD width="33%"><b>Agrupado por Item y Concepto: </b><?php echo $nom_agrupar; ?></TD>
        <TD width="33%"><b>Ordenado por: </b><?php echo $nom_orden; ?></TD>
        </TR>
        <TR> 
		<TD><b>L&iacute;nea de Producci&oacute;n: </b><?php echo $nom_linea; ?></TD>
		<TD><b>Agrupado por L&iacute;nea de Producci&oacute;n: </b><?php echo $nom_agruparlinea; ?></TD>
        <TD><b>De Fecha: </b><?php echo $fechaini; ?> <b>a Fecha: </b><?php echo $fechafin; ?></TD>
		</TR>
        <TR> 
        <TD colspan="2"><b>Contexto: </b><?php echo $nom_contexto; ?></TD>
        <TD><b>Expresado en: </b><?php echo $nom_otra_moneda; ?></TD>
        </TR>
    </table>

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

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&user=<?php echo $usuario; ?>&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>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Unidad</b></TD>
    <TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center"><b>Producci&oacute;n</b></TD>
    <TD align="center"><b>Proyecci&oacute;n</b></TD>
    <TD align="center"><b>L&iacute;nea de Prod.</b></TD>
    <TD align="center"><b>Mov. Merc. Egr.</b></TD>
    <TD align="center"><b>Mov. Merc. Ing.</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
	<TD align="center"><b>Costo Insumos Utilizados</b></TD>
	<TD align="center"><b>Costo Insumos Extras</b></TD>
    <TD align="center"><b>Costo Total Insumos</b></TD>
    <TD align="center"><b>Costo Extra</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">

<?php

$color = 2;
$suma_cant = 0;
$suma_costins = 0;
$suma_costinsuti = 0;
$suma_costinsext = 0;
$suma_costex = 0;
$suma_costu = 0;
$suma_cost = 0;
//lista de items producidos
while ($row = mysqli_fetch_array($result)) {//while 1
	$cod_item = $row['cod_item'];
	$cod_pro = $row['cod_pro'];
	$cod_proy = $row['cod_proy'];
	$cod_mov_ing = $row['cod_mov_ing'];
	$cod_mov_sal = $row['cod_mov_sal'];
	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	printf("<td align='center'>%s</td>", $row['fecha']);//fecha
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionOrder/index.php?pkyProductionOrder=$cod_pro&user=$usuario&token=$token' title='Nota de Orden de Producci&oacute;n'>%s</a> - %s</td>", $row['cod_pro'], $row['nro_doc']);//cod produccion, nro doc
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionProjection/index.php?pkyProductionProjection=$cod_proy&user=$usuario&token=$token' title='Proyecci&oacute;n de Producci&oacute;n'>%s</a></td>", $row['cod_proy']);//cod proyeccion
	printf("<td align='left'>%s</td>", $row['linea']);//linea
	printf("<td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_sal&showBatch=0&printAccountEntry=0&user=$usuario&token=$token' title='Nota de Movimiento de Mercader&iacute;a'>%s</a></td>", $row['cod_mov_sal']);//cod salida
	printf("<td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_ing&showBatch=0&printAccountEntry=0&user=$usuario&token=$token' title='Nota de Movimiento de Mercader&iacute;a'>%s</a></td>", $row['cod_mov_ing']);//cod ingreso
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa,$n_decimales));//costo insumos utilizados
	printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $porcentaje_insumos_extras * $tasa,$n_decimales));//costo insumos extras
	$suma_total_insumos = ($row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa) + ($row['costo_insumos'] * $porcentaje_insumos_extras * $tasa);
	printf("<td align='right'>%s</td>", number_format($suma_total_insumos, $n_decimales));//costo total insumos
	//printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $tasa,$n_decimales));//costo total insumos (antes calculaba así pero se pierde en los decimales)
	printf("<td align='right'>%s</td>", number_format($row['costo_extra'] * $tasa,$n_decimales));//costo extra
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
	$suma_total_costo = $suma_total_insumos + $row['costo_extra'] * $tasa;
	printf("<td align='right'><a href='../../ModuleProduction/ReportItemProduction/report.php?rep=14&tipo=2&cod_prod_det=$cod_pro&item_det=$cod_item&otra_moneda_det=$otra_moneda&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Detalle Producci&oacute;n del Item'>%s</a></td></tr>", number_format($suma_total_costo,$n_decimales));//costo
	//printf("<td align='right'><a href='../../ModuleProduction/ReportItemProduction/report.php?rep=14&tipo=2&cod_prod_det=$cod_pro&item_det=$cod_item&otra_moneda_det=$otra_moneda&contexto_det=$cod_contexto&usuario_det=$usuario&token=$token' title='Detalle Producci&oacute;n del Item'>%s</a></td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo (antes calculaba así pero se pierde en los decimales)
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costinsuti = $suma_costinsuti + $row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa;
	$suma_costinsext = $suma_costinsext + $row['costo_insumos'] * $porcentaje_insumos_extras * $tasa; 
	$suma_costins = $suma_costins + $suma_total_insumos;
	//$suma_costins = $suma_costins + $row['costo_insumos'] * $tasa; //(antes calculaba así pero se pierde en los decimales)
	$suma_costex = $suma_costex + $row['costo_extra'] * $tasa;
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
	//$suma_cost = $suma_cost + $row['costo'] * $tasa; //(antes calculaba así pero se pierde en los decimales)
	$suma_cost = $suma_cost + $suma_total_costo;
	
	$color++;
}//fin while 1
mysqli_free_result($result);	

?>
<tr BGCOLOR='#ffcccc'><td colspan="10"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costinsuti,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costinsext,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costins,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costex,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost,$n_decimales)); ?></td>
</tr>
</table>
<br />
<?php if ($insumosu_ver == 1) { //if insumos 1	?>
<b>Insumos utilizados: </b><button onclick="muestra('Pinsumosu')" class="boton">Mostrar</button> <button onclick="oculta('Pinsumosu')" class="boton">Ocultar</button> 
<br />
<div id="Pinsumosu">
<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>Unidad</b></TD>
    <TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center"><b>Producci&oacute;n</b></TD>
    <TD align="center"><b>L&iacute;nea de Prod.</b></TD>
    <TD align="center"><b>Mov. Merc. Egr.</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">
<?php

//insumos utilizados
$color = 2;
$suma_cant = 0;
$suma_costu = 0;
$suma_cost1 = 0;

while ($row = mysqli_fetch_array($result2)) {//while 2
	$cod_item = $row['cod_item'];
	$cod_pro = $row['cod_pro'];
	$cod_mov_sal = $row['cod_mov_sal'];
	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	printf("<td align='center'>%s</td>", $row['fecha']);//fecha
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionOrder/index.php?pkyProductionOrder=$cod_pro&user=$usuario&token=$token' title='Nota de Orden de Producci&oacute;n'>%s</a> - %s</td>", $row['cod_pro'], $row['nro_doc']);//cod produccion, nro doc
	printf("<td align='left'>%s</td>", $row['linea']);//linea
	printf("<td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_sal&showBatch=0&printAccountEntry=0&user=$usuario&token=$token' title='Nota de Movimiento de Mercader&iacute;a'>%s</a></td>", $row['cod_mov_sal']);//cod salida
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
	printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
	$suma_cost1 = $suma_cost1 + $row['costo'] * $tasa;
	
	$color++;
}//fin while 2
mysqli_free_result($result2);	
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="8"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost1,$n_decimales)); ?></td>
</tr>
</table>
</div>
<br />
<?php } //fin if insumos 1 ?> 
<?php if ($insumose_ver == 1) { //if insumos 2	?>
<b>Insumos extras: </b><button onclick="muestra('Pinsumose')" class="boton">Mostrar</button> <button onclick="oculta('Pinsumose')" class="boton">Ocultar</button> 
<br />
<div id="Pinsumose">
<table border="1" align="center" cellpadding="2" width="100%" id="Pinsumose">
 	<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>Unidad</b></TD>
    <TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center"><b>Producci&oacute;n</b></TD>
    <TD align="center"><b>L&iacute;nea de Prod.</b></TD>
    <TD align="center"><b>Mov. Merc. Egr.</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">
<?php

//insumos extras

$color = 2;
$suma_cant = 0;
$suma_costu = 0;
$suma_cost2 = 0;

//condicion para mostrar
$suma_muestra = $suma_cost1 + $suma_costos_extras;
//echo round($suma_muestra,4).' = '.round($suma_costins,4).'<br>';
while ($row = mysqli_fetch_array($result3)) {//while 3
	$cod_item = $row['cod_item'];
	$cod_pro = $row['cod_pro'];
	$cod_mov_sal = $row['cod_mov_sal'];
	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	printf("<td align='center'>%s</td>", $row['fecha']);//fecha
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionOrder/index.php?pkyProductionOrder=$cod_pro&user=$usuario&token=$token' title='Nota de Orden de Producci&oacute;n'>%s</a> - %s</td>", $row['cod_pro'], $row['nro_doc']);//cod produccion, nro doc
	printf("<td align='left'>%s</td>", $row['linea']);//linea
	printf("<td align='center'><a href='../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=$cod_mov_sal&showBatch=0&printAccountEntry=0&user=$usuario&token=$token' title='Nota de Movimiento de Mercader&iacute;a'>%s</a></td>", $row['cod_mov_sal']);//cod salida
		
	//muestra siempre con costos si se elije todos los items
	if($item == 0) {//if muestra 01
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
	printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
	$suma_cost2 = $suma_cost2 + $row['costo'] * $tasa;
	} else { //else if muestra 01 
		//compara si la suma es igual para mostrar con costos
		if(round($suma_muestra,4) == round($suma_costins,4)) {//if muestra 011
		printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
		printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa,$n_decimales));//costo unitario
		printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa,$n_decimales));//costo
			
		$suma_cant = $suma_cant + $row['cantidad'];
		$suma_costu = $suma_costu + $row['costo_u'] * $tasa;
		$suma_cost2 = $suma_cost2 + $row['costo'] * $tasa;
		} else { //else if muestra 011 
		printf("<td>&nbsp;</td>");//cantidad blanco
		printf("<td>&nbsp;</td>");//costo unitario blanco
		printf("<td>&nbsp;</td></tr>");//costo blanco
		}//fin if muestra 011
	}//fin if muestra 01
	$color++;
}//fin while 3
mysqli_free_result($result3);	

//si las sumas son diferentes se muestra solo el total
if(round($suma_muestra,4) != round($suma_costins,4)) {//if muestra 02
	//se resta el total de costos insumos utilizados e insumos extras menos costos insumos utilizados
	$suma_cost2 = $suma_costins - $suma_cost1;

}//fin if muestra 02
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="8"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost2,$n_decimales)); ?></td>
</tr>
</table>
</div>
<br />

<?php } //fin if insumos 2 ?> 
<?php if ($costosi_ver == 1) { //if costos 1	?>
<b>Costos Indirectos: </b><button onclick="muestra('Pcostosi')" class="boton">Mostrar</button> <button onclick="oculta('Pcostosi')" class="boton">Ocultar</button> 
<br />
<div id="Pcostosi">
<table border="1" align="center" cellpadding="2" width="100%" id="Pcostosi">
 	<thead>
    <TR> 
 	<TD align="center" width="10%"><b>Cod.</b></TD>
    <TD align="center"><b>Concepto</b></TD>
    <TD align="center" width="65"><b>Fecha</b></TD>
    <TD align="center"><b>Producci&oacute;n</b></TD>
    <TD align="center"><b>Proyecci&oacute;n</b></TD>
    <TD align="center"><b>Monto</b></TD>
    <TD align="center" width="10%"><b>Cod. Item</b></TD>
    <TD align="center" width="10%"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">
<?php
//costos indirectos
$color = 2;
$suma_cost = 0;

while ($row = mysqli_fetch_array($result4)) {//while 4
	$cod_con = $row['cod_con'];

	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_con']);//cod concepto
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_con']);//cod concepto
	}//cierra if color
	printf("<td align='left'>%s</td>", $row['concepto']);//concepto
	printf("<td align='center'>%s</td>", $row['fecha']);//fecha
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionOrder/index.php?pkyProductionOrder=$cod_pro&user=$usuario&token=$token' title='Nota de Orden de Producci&oacute;n'>%s</a> - %s</td>", $row['cod_pro'], $row['nro_doc']);//cod produccion, nro doc
	printf("<td align='center'><a href='../../ModuleProduction/VoucherProductionProjection/index.php?pkyProductionProjection=$cod_proy&user=$usuario&token=$token' title='Proyecci&oacute;n de Producci&oacute;n'>%s</a></td>", $row['cod_proy']);//cod proyeccion
	printf("<td align='right'>%s</td>", number_format($row['monto'] * $tasa,$n_decimales));//costo 
	printf("<td align='center'>%s</td>", $row['cod_item']);//cod item
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	echo '</tr>';	
	$suma_cost = $suma_cost + $row['monto'] * $tasa;
	
	$color++;
}//fin while 4
mysqli_free_result($result4);	
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="5"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</div>
<?php } //fin if costos 1 ?>          
<?php

} //fin if agrupar 1

} //fin if 2




//Detalle reporte produccion por item


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_det = $row['otra_moneda'];
	}
	mysqli_free_result($resultotra);
	
//tasa de cambio
if($otra_moneda_det == $cod_moneda_principal) {// if tasa
	$tasa_det = 1;
} else {// else if tasa
$resultcambio = mysqli_query($link, "select fldRate as tasa 
from actExchangeRateDetail 
where 
codExchangeRate = '$tc_hoy' and 
codBaseCurrency = '$otra_moneda_det' and 
codTargetCurrency = '$cod_moneda_principal' and 
sysEnabled = 1 and sysAuthorized = 1;");
		
	while ($row = mysqli_fetch_array($resultcambio)) {
	$tasa_det = $row['tasa'];
	}
	mysqli_free_result($resultcambio);
}// fin if tasa


//item
$resultitem = mysqli_query($link, "select pkyItem as cod_item, fldName as item, fldFactoryKey as cod_fabrica
from
invItem
where
pkyItem = '$item_det' and
sysEnabled = 1 and sysAuthorized = 1;");
	
while ($row = mysqli_fetch_array($resultitem)) {
$nom_item_det = $row['cod_item'].' - '.$row['cod_fab'].' - '.$row['item'];
}
mysqli_free_result($resultitem);

//produccion
$resultprod = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.fldDate as fecha, a.codProductionLine as cod_linea, b.fldName as linea, a.codItemMovementOut as cod_out, a.codItemMovementIn as cod_in, a.codProjection as cod_proy, a.codAccountEntry as cod_asiento 
from prdProductionOrder a, prdProductionLine b
where 
a.pkyProductionOrder = '$cod_prod_det' and 
a.codProductionLine = b.pkyProductionLine and 
a.sysEnabled = 1 and a.sysAuthorized = 1;");
	
while ($row = mysqli_fetch_array($resultprod)) {
$nro_doc_det = $row['nro_doc'];
$fecha_det = $row['fecha'];
$linea_det = $row['linea'];
$cod_out_det = $row['cod_out'];
$cod_in_det = $row['cod_in'];
$cod_proy_det = $row['cod_proy'];
$cod_asiento_det = $row['cod_asiento'];
}
mysqli_free_result($resultprod);

//proyeccion
$result311 = mysqli_query($link, "select fldDocumentNumber as nro_doc 
from prdProductionProjection 
where 
pkyProductionProjection = '$cod_proy_det';");
	while ($row = mysqli_fetch_array($result311)) {
	$nom_proy_det = $row['nro_doc'];
	}
	mysqli_free_result($result311);

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

//lista de items producidos
$result = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.fldDate as fecha, a.codProductionLine as cod_lin, e.fldName as linea, a.codItemMovementOut as cod_mov_sal, a.codItemMovementIn as cod_mov_ing, a.codProjection as cod_proy, b.codItem as cod_item, c.fldName as item, c.fldFactoryKey as cod_fab, d.fldQuantity as cantidad, (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut) as costo_insumos, d.fldExtraCost as costo_extra, (d.fldExtraCost + (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut)) / d.fldQuantity as costo_u, d.fldExtraCost + (SELECT sum(a1.fldTotaCost) FROM invItemMovementDetail a1 WHERE a1.codItemMovement = a.codItemMovementOut) as costo, u.fldName as unidad
from
prdProductionOrder a, prdProductionOrderDetail b, invItem c, invItemMovementDetail d, prdProductionLine e, invStorageUnit u
where 
$valor_contexto_det 
b.codItem = '$item_det' and 
a.pkyProductionOrder = '$cod_prod_det' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = c.pkyItem and 
a.codItemMovementIn = d.codItemMovement and 
b.codItem = d.codItem and 
a.codProductionLine = e.pkyProductionLine and 
c.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1
order by item;");

//calculo del total para extraer el porcentaje este es 100%
$suma_porcentaje_total_insumos = 0;
while ($row = mysqli_fetch_array($result)) {//while 1
	$suma_porcentaje_total_insumos = $suma_porcentaje_total_insumos + $row['costo_insumos'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result, 0);


//lista de insumos 
$result2 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.codProductionLine as cod_lin, f.fldName as linea, a.codItemMovementOut as cod_mov_sal, e.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.fldDate as fecha, e.fldQuantity as cantidad, c.fldCost as costo_u, e.fldQuantity * c.fldCost as costo, u.fldName as unidad 
from prdProductionOrder a, prdProductionOrderDetail b, invItemMovementDetail c, invItem d, prdProductionOrderDetailRecipe e, prdProductionLine f, invStorageUnit u
where  
$valor_contexto_det 
b.codItem = '$item_det' and 
a.pkyProductionOrder = '$cod_prod_det' and 
a.pkyProductionOrder = b.codProductionOrder and 
a.codItemMovementOut = c.codItemMovement and 
a.pkyProductionOrder = e.codProductionOrder and 
b.pkyProductionOrderDetail = e.codProductionOrderDetail and 
e.codItem = c.codItem and 
e.codItem = d.pkyItem and 
a.codProductionLine = f.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1  
order by item;");

//calculo del total para extraer el porcentaje, no se cuanto es lo calculo
$suma_porcentaje_insumos_utilizados = 0;
while ($row = mysqli_fetch_array($result2)) {//while 1
	$suma_porcentaje_insumos_utilizados = $suma_porcentaje_insumos_utilizados + $row['costo'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result2, 0);


//lista de insumos extra, no tiene que haber $valor_item
//hay dos querys porque el primero lista y el segundo es para ver si la suma es igual para mostrar costos
$result3 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.codProductionLine as cod_lin, f.fldName as linea, a.codItemMovementOut as cod_mov_sal, b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.fldDate as fecha, b.fldQuantity as cantidad, b.fldCost as costo_u, b.fldTotaCost as costo, u.fldName as unidad  
from prdProductionOrder a, prdExtraItem b, invItem d, prdProductionLine f, invStorageUnit u
where 
$valor_contexto_det 
a.pkyProductionOrder = '$cod_prod_det' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = d.pkyItem and 
a.codProductionLine = f.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
order by item;");

//calculo del total para extraer el porcentaje, no se cuanto es lo calculo
$suma_porcentaje_insumos_extras = 0;
while ($row = mysqli_fetch_array($result3)) {//while 1
	$suma_porcentaje_insumos_extras = $suma_porcentaje_insumos_extras + $row['costo'];
}
//coloca el puntero de nuevo al inicio para recorrerlo de nuevo al mostrar
mysqli_data_seek($result3, 0);

//calculo los porcentaces para las columnas
$porcentaje_insumos_utilizados = $suma_porcentaje_insumos_utilizados / $suma_porcentaje_total_insumos;
$porcentaje_insumos_extras = $suma_porcentaje_insumos_extras / $suma_porcentaje_total_insumos;


//suma el total de los costos extras para ver si muestra con costos
$result31 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.codProductionLine as cod_lin, f.fldName as linea, a.codItemMovementOut as cod_mov_sal, b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab, a.fldDate as fecha, b.fldQuantity as cantidad, b.fldCost as costo_u, sum(b.fldTotaCost) as costo, u.fldName as unidad  
from prdProductionOrder a, prdExtraItem b, invItem d, prdProductionLine f, invStorageUnit u
where 
$valor_contexto_det 
a.pkyProductionOrder = '$cod_prod_det' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codItem = d.pkyItem and 
a.codProductionLine = f.pkyProductionLine and 
d.codMinimumStorageUnit = u.pkyStorageUnit and 
a.sysEnabled = 1 and a.sysAuthorized = 1 
group by cod_pro;");
while ($row = mysqli_fetch_array($result31)) {
	$suma_costos_extras = $row['costo'];
	}
	mysqli_free_result($result31);


//lista de gastos indirectos
$result4 = mysqli_query($link, "select a.pkyProductionOrder as cod_pro, a.fldDocumentNumber as nro_doc, a.fldDate as fecha, a.codProjection as cod_proy, b.codProductionConcept as cod_con, c.fldName as concepto, b.fldAmount as monto, b.codItem as cod_item, d.fldName as item, d.fldFactoryKey as cod_fab
from prdProductionOrder a, prdProductionOrderConcept b, prdProductionConcept c, invItem d
where  
$valor_contexto_det 
b.codItem = '$item_det' and 
a.pkyProductionOrder = '$cod_prod_det' and 
a.pkyProductionOrder = b.codProductionOrder and 
b.codProductionConcept = c.pkyProductionConcept and 
b.codItem = d.pkyItem and 
a.sysEnabled = 1 and a.sysAuthorized = 1
order by concepto;");



?>
<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 de Producci&oacute;n 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_det; ?></TD>
        <TD width="25%"><b>Orden de Producci&oacute;n: </b><a href="../../ModuleProduction/VoucherProductionOrder/index.php?pkyProductionOrder=<?php echo $cod_prod_det; ?>&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Proyecci&oacute;n de Producci&oacute;n"><?php echo $cod_prod_det; ?></a> - <?php echo $nro_doc_det; ?></TD>
        <TD width="25%"><b>Fecha: </b><?php echo $fecha_det; ?></TD>
        <TD width="25%"><b>Proyecci&oacute;n: </b><a href="../../ModuleProduction/VoucherProductionProjection/index.php?pkyProductionProjection=<?php echo $cod_proy_det; ?>&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Proyecci&oacute;n de Producci&oacute;n"><?php echo $cod_proy_det; ?></a> - <?php echo $nom_proy_det; ?></TD>
        </TR>
        <TR> 
        <TD><b>L&iacute;nea de Producci&oacute;n: </b><?php echo $linea_det; ?></TD>
        <TD><b>Egr. Materia Prima: </b><a href="../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=<?php echo $cod_out_det; ?>&showBatch=0&printAccountEntry=0&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Nota de Movimiento de Mercaderia"><?php echo $cod_out_det; ?></a></TD>
        <TD><b>Ing. Prod. Terminado: </b><a href="../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=<?php echo $cod_in_det; ?>&showBatch=0&printAccountEntry=0&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Nota de Movimiento de Mercaderia"><?php echo $cod_in_det; ?></a></TD>
        <TD><b>Expresado en: </b><?php echo $nom_otra_moneda_det; ?></TD>
        </TR>
        <TR>
        <TD colspan="4"><b>Contexto: </b><?php echo $nom_contexto_det; ?></TD>
        </TR>
    </table>

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

    <table border="1" align="center" cellpadding="2" width="100%">
    <tr>
    <TD><b>Tipo de Cambio:</b></TD>
    </tr><tr>
    <TD align="center"><a href="../../ModuleAccounting/VoucherExchangeRate/index.php?pkyExchangeRate=<?php echo $ultimo_tc; ?>&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>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD align="center"><b>Unidad</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
	<TD align="center"><b>Costo Insumos Utilizados</b></TD>
	<TD align="center"><b>Costo Insumos Extras</b></TD>
    <TD align="center"><b>Costo Total Insumos</b></TD>
    <TD align="center"><b>Costo Extra</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">

<?php

$color = 2;
$suma_cant = 0;
$suma_costins = 0;
$suma_costinsuti = 0;
$suma_costinsext = 0;
$suma_costex = 0;
$suma_costu = 0;
$suma_cost = 0;
//lista de items producidos
while ($row = mysqli_fetch_array($result)) {//while 1
	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa_det,$n_decimales));//costo insumos utilizados
	printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $porcentaje_insumos_extras * $tasa_det,$n_decimales));//costo insumos extras
	printf("<td align='right'>%s</td>", number_format($row['costo_insumos'] * $tasa_det,$n_decimales));//costo total insumos
	printf("<td align='right'>%s</td>", number_format($row['costo_extra'] * $tasa_det,$n_decimales));//costo extra
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa_det,$n_decimales));//costo unitario
	printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa_det,$n_decimales));//costo
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costinsuti = $suma_costinsuti + $row['costo_insumos'] * $porcentaje_insumos_utilizados * $tasa_det;
	$suma_costinsext = $suma_costinsext + $row['costo_insumos'] * $porcentaje_insumos_extras * $tasa_det;
	$suma_costins = $suma_costins + $row['costo_insumos'] * $tasa_det;
	$suma_costex = $suma_costex + $row['costo_extra'] * $tasa_det;
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa_det;
	$suma_cost = $suma_cost + $row['costo'] * $tasa_det;
	
	$color++;
}//fin while 1
mysqli_free_result($result);	

?>
<tr BGCOLOR='#ffcccc'><td colspan="4"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costinsuti,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costinsext,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costins,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costex,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost,$n_decimales)); ?></td>
</tr>
</table>
<br />
<b>Insumos utilizados: </b><button onclick="muestra('Pinsumosu')" class="boton">Mostrar</button> <button onclick="oculta('Pinsumosu')" class="boton">Ocultar</button> 
<br />
<div id="Pinsumosu">
<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>Unidad</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">
<?php

//insumos utilizados
$color = 2;
$suma_cant = 0;
$suma_costu = 0;
$suma_cost1 = 0;

while ($row = mysqli_fetch_array($result2)) {//while 2
	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa_det,$n_decimales));//costo unitario
	printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa_det,$n_decimales));//costo
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa_det;
	$suma_cost1 = $suma_cost1 + $row['costo'] * $tasa_det;
	
	$color++;
}//fin while 2
mysqli_free_result($result2);	
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="4"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost1,$n_decimales)); ?></td>
</tr>
</table>
</div>
<br />
<b>Insumos extras: </b><button onclick="muestra('Pinsumose')" class="boton">Mostrar</button> <button onclick="oculta('Pinsumose')" class="boton">Ocultar</button> 
<br />
<div id="Pinsumose">
<table border="1" align="center" cellpadding="2" width="100%" id="Pinsumose">
 	<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>Unidad</b></TD>
    <TD align="center"><b>Cantidad</b></TD>
    <TD align="center"><b>Costo Uni.</b></TD>
    <TD align="center"><b>Costo</b></TD>
    </TR>
	</thead>
    <tbody class="marcafila">
<?php

//insumos extras


$color = 2;
$suma_cant = 0;
$suma_costu = 0;
$suma_cost2 = 0;

//condicion para mostrar
$suma_muestra = $suma_cost1 + $suma_costos_extras;
//echo round($suma_muestra,4).' = '.round($suma_costins,4).'<br>';
while ($row = mysqli_fetch_array($result3)) {//while 3
	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_item']);//cod item
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_item']);//cod item
	}//cierra if color
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	printf("<td align='left'>%s</td>", $row['unidad']);//unidad
	//compra si las sumas son iguales muestra con costos
	if(round($suma_muestra,4) == round($suma_costins,4)) {//if muestra 01
	printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
	printf("<td align='right'>%s</td>", number_format($row['costo_u'] * $tasa_det,$n_decimales));//costo unitario
	printf("<td align='right'>%s</td></tr>", number_format($row['costo'] * $tasa_det,$n_decimales));//costo
		
	$suma_cant = $suma_cant + $row['cantidad'];
	$suma_costu = $suma_costu + $row['costo_u'] * $tasa_det;
	$suma_cost2 = $suma_cost2 + $row['costo'] * $tasa_det;
	} else { //else if muestra 01 
	printf("<td>&nbsp;</td>");//cantidad blanco
	printf("<td>&nbsp;</td>");//costo unitario blanco
	printf("<td>&nbsp;</td></tr>");//costo blanco
	}//fin if muestra 01
	$color++;
}//fin while 3
mysqli_free_result($result3);	

//si las sumas son diferentes se muestra solo el total
if(round($suma_muestra,4) != round($suma_costins,4)) {//if muestra 02
	//se resta el total de costos insumos utilizados e insumos extras menos costos insumos utilizados
	$suma_cost2 = $suma_costins - $suma_cost1;

}//fin if muestra 02
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="4"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cant,$n_cantidad)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_costu,$n_decimales)); ?></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost2,$n_decimales)); ?></td>
</tr>
</table>
</div>
<br />

<b>Costos Indirectos: </b><button onclick="muestra('Pcostosi')" class="boton">Mostrar</button> <button onclick="oculta('Pcostosi')" class="boton">Ocultar</button> 
<br />
<div id="Pcostosi">
<table border="1" align="center" cellpadding="2" width="100%" id="Pcostosi">
 	<thead>
    <TR> 
 	<TD align="center" width="10%"><b>Cod.</b></TD>
    <TD align="center"><b>Concepto</b></TD>
    <TD align="center"><b>Monto</b></TD>
    <TD align="center" width="10%"><b>Cod. Item</b></TD>
    <TD align="center" width="10%"><b>Cod. Fab.</b></TD>
    <TD align="center"><b>Item</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">
<?php
//costos indirectos
$color = 2;
$suma_cost = 0;

while ($row = mysqli_fetch_array($result4)) {//while 4
	$cod_con = $row['cod_con'];

	if($color % 2 == 0) { //if color
		printf("<tr BGCOLOR='#e2e7fa'><td align='center'>%s</td>", $row['cod_con']);//cod concepto
	} else {
		printf("<tr><td align='center'>%s</td>", $row['cod_con']);//cod concepto
	}//cierra if color
	printf("<td align='left'>%s</td>", $row['concepto']);//concepto
	printf("<td align='right'>%s</td>", number_format($row['monto'] * $tasa_det,$n_decimales));//costo 
	printf("<td align='center'>%s</td>", $row['cod_item']);//cod item
	printf("<td align='center'>%s</td>", $row['cod_fab']);//cod fabrica
	printf("<td align='left'>%s</td>", $row['item']);//item
	echo '</tr>';	
	$suma_cost = $suma_cost + $row['monto'] * $tasa_det;
	
	$color++;
}//fin while 4
mysqli_free_result($result4);	
?>
 
<tr BGCOLOR='#ffcccc'><td colspan="2"><b>Total</b></td>
<td align="right"><?php printf("<b>%s</b>", number_format($suma_cost,$n_decimales)); ?></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</div>

<?php
} //fin if 3
?>

</body>
</html>
