<?php
//inicio muestra detalle de la nota de venta mismo que voucherSalesNote, este detalle esta dentro del detalle

// Inicio impresion Nota de Venta


$result = mysqli_query($link, "select a.pkySalesNote as codigo_orden, a.fldDate as fecha, 
a.fldNumber as numero_doc, a.codOrderNote as cod_pedido, a.codSeller as cod_vendedor, 
case when b.fldMiddleName is NULL then concat(b.fldLastName,', ',b.fldFirstName) else concat(b.fldLastName,' ',b.fldMiddleName,', ',b.fldFirstName) end as vendedor, 
case when b.fldMiddleName is NULL then concat(b.fldFirstName,' ',b.fldLastName) else concat(b.fldFirstName,' ',b.fldLastName,' ',b.fldMiddleName) end as vendedor_reves, 
c.fldName as cliente, c.fldNIT as nit, 
a.codDeliveryAddress as cod_dir, 
a.codFixedContactPhone as cod_tel, 
a.codMovilContactPhone as cod_movil, 
f.fldName as almacen, g.fldName as local_venta, 
a.codCurrency as cod_moneda, h.fldName as moneda, 
i.pkyExchangeRate as cod_tc, 
concat(i.fldDate,' - ',i.fldTime) as fecha_tc, 
a.fldGrossTotal as total_bruto, 
a.fldTotalDiscountPercent as total_desc_porciento, 
a.fldGlobalDiscountPercent as total_desc_porciento_global, 
a.fldNetTotal as total_neto, a.txtDescription as glosa, 
a.sysEnabled as enabled, a.sysAuthorized as authorized, 
a.codType as cod_tipo, j.fldName as tipo_nota,  
a.codAccountEntry as cod_asiento, a.codAccountReceivable as cod_cxc, 
a.codItemMovement as cod_mov_merc, a.codInvoice as cod_fac, 
a.codPettyCashMovement as cod_mov_caja, a.codCheck as cod_cheque, a.codBankMovement as cod_mov_banco, k.fldName as usuario_reg, a.sysContext as cod_contexto, s.fldName as contexto   
from slsSalesNote a, agnPerson b, agnCompany c, invWarehouse f, slsSalesPlace g, actCurrency h, actExchangeRate i, slsSalesNoteType j, accGroup k, srvContext s
where
a.codSeller = b.pkyPerson and
a.codClient = c.pkyCompany and 
a.codWarehouse = f.pkyWarehouse and
a.codSalesPlace = g.pkySalesPlace and
a.codCurrency = h.pkyCurrency and
a.codExchangeRate = i.pkyExchangeRate and 
a.codType = j.pkySalesNoteType and 
a.sysAuthorizationGroup = k.pkyGroup and 
a.sysContext = s.pkyContext and 
a.pkySalesNote = '$cod_venta' ");
	while ($row = mysqli_fetch_array($result)) {
		$codigo_orden = $row['codigo_orden'];
		$fecha_orden = $row['fecha'];
		$numero_doc = $row['numero_doc'];
		$vendedor = $row['vendedor'];
		$vendedor_reves = $row['vendedor_reves'];
		$cliente = $row['cliente'];
		$nit = $row['nit'];
		$cod_dir = $row['cod_dir'];
		$cod_tel = $row['cod_tel'];
		$cod_movil = $row['cod_movil'];
		$almacen = $row['almacen'];
		$local_venta = $row['local_venta'];
		$cod_moneda = $row['cod_moneda'];
		$moneda = $row['moneda'];
		$cod_tc = $row['cod_tc'];
		$fecha_tc = $row['fecha_tc'];
		$total_bruto = $row['total_bruto'];
		$total_desc_porciento = $row['total_desc_porciento'];
		$total_desc_porciento_global = $row['total_desc_porciento_global'];
		$total_neto = $row['total_neto'];
		$glosa = $row['glosa'];
		$glosa = nl2br($glosa);//quita salto de linea 
		$glosa = str_replace('\n','<br />',$glosa);//reemplaza para salto de linea
		$usuario_reg = $row['usuario_reg'];
		$enabled = $row['enabled'];
		$authorized = $row['authorized'];
		$cod_tipo = $row['cod_tipo'];
		$tipo_nota = $row['tipo_nota']; 
		$estado = $row['estado'];
		$cod_asiento = $row['cod_asiento'];
		$cod_cxc = $row['cod_cxc'];
		$cod_mov_merc = $row['cod_mov_merc'];
		$cod_pedido = $row['cod_pedido'];
		$cod_factura = $row['cod_fac'];
		$cod_mov_caja = $row['cod_mov_caja'];
		$cod_cheque = $row['cod_cheque'];
		$cod_mov_banco = $row['cod_mov_banco'];
		//$cod_contrato = $row['cod_contrato'];
		$cod_vendedor = $row['cod_vendedor'];
		$cod_contexto = $row['cod_contexto'];
		$contexto = $row['contexto'];
	}
	mysqli_free_result($result);
	
$resultdir = mysqli_query($link, "select a.fldAddress as direccion, b.fldName as tipo_dir
from
agnCompanyAddress a, agnAddressType b
where
a.pkyCompanyAddress = '$cod_dir' and 
a.codType = b.pkyAddressType;");
while ($row = mysqli_fetch_array($resultdir)) {
	$direccion = $row['direccion'];
	$tipo_dir = $row['tipo_dir'];
}
mysqli_free_result($resultdir);

$resulttel = mysqli_query($link, "select a.fldPhone as telefono, b.fldName as tipo_tel
from
agnCompanyPhone a, agnPhoneType b
where
a.pkyCompanyPhone = '$cod_tel' and 
a.codType = b.pkyPhoneType;");
while ($row = mysqli_fetch_array($resulttel)) {
	$telef = $row['telefono'];
	$tipo_tel = $row['tipo_tel'];
}
mysqli_free_result($resulttel);

$resultmov = mysqli_query($link, "select a.fldPhone as telefono, b.fldName as tipo_tel
from
agnCompanyPhone a, agnPhoneType b
where
a.pkyCompanyPhone = '$cod_movil' and 
a.codType = b.pkyPhoneType;");
while ($row = mysqli_fetch_array($resultmov)) {
	$celu = $row['telefono'];
	$tipo_cel = $row['tipo_tel'];
}
mysqli_free_result($resultmov);

$resulttc = mysqli_query($link, "select pkyExchangeRate as cod_tc, fldDate as fecha, fldTime as hora
from
actExchangeRate
where
pkyExchangeRate = '$cod_tc';");
while ($row = mysqli_fetch_array($resulttc)) {
	$tc_fecha = $row['fecha'];
	$tc_hora = $row['hora'];
}
mysqli_free_result($resulttc);

$resulttcdet = mysqli_query($link, "select a.pkyExchangeRateDetail as cod_tc_det, a.codBaseCurrency as cod_mon_target, b.fldName as mon_target, b.txtDescription as nom_mon_target, a.codTargetCurrency as cod_mon_base, c.fldName as mon_base, c.txtDescription as nom_mon_base, a.fldRate as tasa
from
actExchangeRateDetail a, actCurrency b, actCurrency c
where
a.codExchangeRate = '$cod_tc' and 
a.codBaseCurrency = '$cod_moneda_principal' and 
a.codBaseCurrency = b.pkyCurrency and 
a.codTargetCurrency = c.pkyCurrency 
order by cod_mon_target;");
$ma_tc = array();
$m = 1;
while ($row = mysqli_fetch_array($resulttcdet)) {
	$ma_tc [$m][1] = $row['mon_base'];
	$ma_tc [$m][2] = $row['mon_target'];
	$ma_tc [$m][3] = $row['tasa'];
	$m++;
}
mysqli_free_result($resulttcdet);
$fin_m = $m - 1;
	
	$result22 = mysqli_query($link, "select a.codItem as cod_item, b.fldName as nombre, a.fldQuantity as cantidad, a.fldPrice as precio, a.fldDiscount as descuento, a.fldTotalNetPrice as total, b.txtDescription as descrip
from
slsSalesNoteDetail a, invItem b
where
a.codItem = b.pkyItem and
a.codSalesNote = '$codigo_orden' 
order by nombre");

//datos de cheque segun cod_cheque
$resultcheque = mysqli_query($link, "select fldNumber as nro_cheque, fldName as nom_giro_cheque, fldForeignAccount as banco_cta
from tryCheck 
where
pkyCheck = '$cod_cheque';");
while ($row = mysqli_fetch_array($resultcheque)) {
	$nro_cheque = $row['nro_cheque'];
	$nom_giro_cheque = $row['nom_giro_cheque'];
	$banco_cta = $row['banco_cta'];
}
mysqli_free_result($resultcheque);

//datos del banco y cta segun el cheque
$resultbanco = mysqli_query($link, "select b.fldName as banco
from 
tryCheck a, tryBank b
where
a.codBank = b.pkyBank and 
a.pkyCheck = '$cod_cheque';");
while ($row = mysqli_fetch_array($resultbanco)) {
	$nom_banco = $row['banco'];
	//$banco_cta = $row['nro_cta'];
}
mysqli_free_result($resultbanco);

//datos del banco y cta segun el movimiento bancario
$resultbanco2 = mysqli_query($link, "select b.fldName as banco, c.fldNumber as nro_cta
from
tryBankMovement a, tryBank b, tryBankDetail c
where
a.pkyBankMovement = '$cod_mov_banco' and 
a.codBank = b.pkyBank and 
a.codBankAccount = c.pkyBankDetail;");
while ($row = mysqli_fetch_array($resultbanco2)) {
	$banco_mov = $row['banco'];
	$banco_cta_mov = $row['nro_cta'];
}
mysqli_free_result($resultbanco2);


//datos de la factura
$resultfactura = mysqli_query($link, "select fldNumber as nro_fac
from 
txsSalesLedger
where
pkySalesLedger = '$cod_factura';");
while ($row = mysqli_fetch_array($resultfactura)) {
	$numero_factura = $row['nro_fac'];
}
mysqli_free_result($resultfactura);

/*
//datos del contrato
$resultcontrato = mysqli_query($link, "select fldNumber as nro_cont 
from vhcVehicleContract 
where 
pkyVehicleContract = '$cod_contrato';");	
while ($row = mysqli_fetch_array($resultcontrato)) {
	$numero_contrato = $row['nro_cont']; 
}
mysqli_free_result($resultcontrato);
*/
?>
<!--
<table border="0" align="left" width="100%" cellpadding="5">
<tr><td><b>Empresa: <?php echo $nombre_empresa; ?><br/>NIT: <?php echo $mi_nit; ?></b>
</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><br/>
-->
<?php if($quitar == 0) { ?>
<p><center><font color="#000099"><b>Detalle Nota de Venta</b></font></center></p>
<?php } ?>
<table border="0" cellpadding="2" align="left" width="90%">
<tr>
<td>  
    <table border="1" align="center" cellpadding="2" width="100%">
        <TR> 
        <TD width="25%"><b>Cod. Reg.: </b><a href="../../ModuleSales/VoucherSalesNote/index.php?pkySalesNote=<?php echo $codigo_orden; ?>&user=<?php echo $usuario_det; ?>&token=<?php echo $token; ?>" title="Nota de Venta"><?php echo $codigo_orden; ?></a></TD>
        <TD width="25%"><b>Nro. Doc.: </b><?php echo $numero_doc; ?></TD>
        <TD width="25%"><b>Moneda: </b><?php echo $moneda; ?></TD>
        <TD width="25%"><b>Fecha de Reg.: </b><?php echo $fecha_orden; ?></TD>
        </TR>
        <TR> 
        <TD colspan="4"><b>Contexto: </b><?php echo $cod_contexto; ?> - <?php echo $contexto; ?></TD>
        </TR>
        <!--
        <TR>
        <TD><b>Cliente: </b><?php echo $cliente; ?></TD>
        <TD><b>NIT: </b><?php echo $nit; ?></TD>
        <TD><b>Direcci&oacute;n: </b><?php echo $direccion; ?> (<?php echo $tipo_dir; ?>)</TD>
        <TD><b>Tel&eacute;fono: </b><?php echo $telef; ?> (<?php echo $tipo_tel; ?>)</TD>
        </TR>
        <TR>
        <TD><b>Celular: </b><?php echo $celu; ?> (<?php echo $tipo_cel; ?>)</TD> 
        <TD><b>Tipo: </b><?php echo $tipo_nota; ?></TD>
        <?php if($cod_contrato != NULL) { ?> 
        <TD><b>Contrato: </b><a href="../../ModuleVehicles/VoucherVehicleContract/index.php?pkyVehicleContract=<?php echo $cod_contrato; ?>&codStatus=0" title="Contrato"><?php echo $cod_contrato; ?></a> - <?php echo $numero_contrato; ?></TD>
        <?php } else { ?>
        <TD><b>Contrato: </b><?php echo $cod_contrato; ?></TD>
        <?php } ?>
        <TD><b>Nota Pedido: </b><a href="../../ModuleSales/VoucherOrderNote/index.php?pkyOrderNote=<?php echo $cod_pedido; ?>&showPrice=1&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Cotizacion y Nota de Pedido con Precio"><?php echo $cod_pedido; ?></a></TD>
        </TR>
        <TR>
        <TD><b>Asiento: </b><a href="../../ModuleAccounting/VoucherAccountEntry/index.php?pkyAccountEntry=<?php echo $cod_asiento; ?>&showCC=<?php echo $mostrar_asiento_cc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Asiento Contable"><?php echo $cod_asiento; ?></a></TD>
        <TD><b>Cuenta x Cobrar: </b><a href="../../ModuleCollections/VoucherAccountsReceivable/index.php?pkyAccountsReceivable=<?php echo $cod_cxc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Nota de Cuenta por Cobrar"><?php echo $cod_cxc; ?></a></TD>
        <TD><b>Mov. de Caja: </b><a href="../../ModulePettyCash/VoucherPettyCashMovement/index.php?pkyPettyCashMovement=<?php echo $cod_mov_caja; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Nota de Movimiento de Caja"><?php echo $cod_mov_caja; ?></a></TD>
        <TD><b>Mov. de Banco: </b><a href="../../ModuleTreasury/VoucherBankMovement/index.php?pkyBankMovement=<?php echo $cod_mov_banco; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Nota de Movimiento Bancario"><?php echo $cod_mov_banco; ?></a> <?php echo $banco_mov; ?> <?php echo $banco_cta_mov; ?></TD>
        </TR>
        <TR>
        <?php if($cod_cheque != NULL) { ?> 
        <TD><b>Cheque: </b><a href="../../ModuleTreasury/VoucherCheck/index.php?pkyCheck=<?php echo $cod_cheque; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Cheque"><?php echo $cod_cheque; ?></a> - <?php echo $nro_cheque; ?> - <?php echo $nom_banco; ?> (<?php echo $banco_cta; ?>) - <?php echo $nom_giro_cheque; ?></TD>
        <?php } else { ?>
        <TD><b>Cheque: </b><?php echo $cod_cheque; ?></TD>
        <?php } ?>
        <TD><b>Mov. de Mercader&iacute;a: </b><a href="../../ModuleInventory/VoucherItemMovement/index.php?pkyItemMovement=<?php echo $cod_mov_merc; ?>&showBatch=0&printAccountEntry=0&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Nota de Movimiento de Mercaderia"><?php echo $cod_mov_merc; ?></a></TD>
        <?php if($cod_factura != NULL) { ?> 
        <TD colspan="2"><b>Factura: </b><a href="../../ModuleTaxes/VoucherSalesLedger/index.php?pkySalesLedger=<?php echo $cod_factura; ?>&sheetSize=<?php echo $formato_factura; ?>&head=<?php echo $muestra_cabecera; ?>" title="Factura"><?php echo $cod_factura; ?></a> - <?php echo $numero_factura; ?></TD>
        <?php } else { ?>
        <TD colspan="2"><b>Factura: </b><?php echo $cod_factura; ?></TD>
        <?php } ?>
        </TR>
        <TR>
        <TD><b>Almac&eacute;n: </b><?php echo $almacen; ?></TD>
        <TD colspan="2"><b>Local Venta: </b><?php echo $local_venta; ?></TD>
        <TD><b>Vendedor: </b><a href="../../ModuleAgenda/VoucherPerson/index.php?pkyPerson=<?php echo $cod_vendedor; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Persona"><?php echo $cod_vendedor; ?></a> - <?php echo $vendedor; ?></TD>
        </TR>
        <TR>
        <TD><b>Desc. Parcial (%): </b><?php echo number_format($total_desc_porciento, $n_descuento); ?>%</TD>
        <TD><b>Desc. Parcial: </b><?php echo number_format($total_bruto * $total_desc_porciento / 100,$n_descuento); ?></TD>
        <TD><b>Desc. Global (%): </b><?php echo number_format($total_desc_porciento_global,$n_descuento); ?>%</TD>
        <TD><b>Desc. Global: </b><?php echo number_format($total_bruto * $total_desc_porciento_global / 100,$n_descuento); ?></TD>
        </TR>
        <TR>
        <TD colspan="2"><b>Total Bruto: </b><?php echo number_format($total_bruto, $n_decimales); ?></TD>
        <TD colspan="2"><b>Total Neto: </b><?php echo number_format($total_neto, $n_decimales); ?></TD>
        </TR>
        <TR>
        <TD colspan="4"><b>Glosa: </b><?php echo $glosa; ?></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 $cod_tc; ?>&user=<?php echo $usuario; ?>&token=<?php echo $token; ?>" title="Tipo de Cambio"><?php echo $cod_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="left" cellpadding="2" width="90%">
    <thead>
    <TR> 
    <TD width="60" align="center"><b>Cod. Item</b></TD>
    <TD align="center"><b>Item</b></TD>
    <TD width="100" align="center"><b>Cant.</b></TD>
    <TD width="100" align="center"><b>Precio</b></TD>
    <TD width="100" align="center"><b>Desc. %</b></TD>
    <TD width="100" align="center"><b>Total</b></TD>
    </TR>
    </thead>
    <tbody class="marcafila">
    <?php
    $color3 = 2;
    $suma_cant = 0;
    $suma_precio = 0;
    $suma_desc = 0;
    $suma_total3 = 0;
    while ($row = mysqli_fetch_array($result22)) { //while
    
        if($color3 % 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>%s</td>", $row['nombre']);//nombre item
        printf("<td align='right'>%s</td>", number_format($row['cantidad'],$n_cantidad));//cantidad
        printf("<td align='right'>%s</td>", number_format($row['precio'],$n_decimales));//precio
        printf("<td align='right'>%s</td>", number_format($row['descuento'],$n_descuento));//descuento
        printf("<td align='right'>%s</td></tr>", number_format($row['total'],$n_decimales));//total
        
        $suma_cant = $suma_cant + $row['cantidad'];
        $suma_precio = $suma_precio + $row['precio'];
        $suma_desc = $suma_desc + $row['descuento'];
        $suma_total3 = $suma_total3 + $row['total'];
        
        $color3++;
    }//fin while
mysqli_free_result($result22);
	
	//convierte el total en literal
	$letras=new NroEnLetra($suma_total3,2);
	
	$mostrar_letras = ucfirst($letras->getLetra());
	
	$busca_espacio = substr($mostrar_letras,-6,1);
	if($busca_espacio == ' ') {
		$fin_letras = substr($mostrar_letras,-5);
		$mostrar_letras = substr($mostrar_letras,0,-5);
		$mostrar_letras = $mostrar_letras .'0'. $fin_letras;
	}
	$resultmoneda = mysqli_query($link, "select txtDescription as nom_moneda
	from actCurrency
	where
	pkyCurrency = '$cod_moneda';");
	while ($row = mysqli_fetch_array($resultmoneda)) {
		$nom_moneda_letras_tot = $row['nom_moneda'];
	}
	mysqli_free_result($resultmoneda);
	?>
	<tr BGCOLOR='#ffcccc'>
    <td colspan="2"><b>Total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <?php echo $mostrar_letras; ?> <?php echo $nom_moneda_letras_tot; ?></b></td>
    <td align="right"><b><?php echo number_format($suma_cant, $n_cantidad); ?></b></td>
    <!--
    <td align="right"><b><?php echo number_format($suma_precio, $n_decimales); ?></b></td>
    <td align="right"><b><?php echo number_format($suma_desc, $n_descuento); ?></b></td>
    -->
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td align="right"><b><?php echo number_format($suma_total3, $n_decimales); ?></b></td></tr>
</tbody>    
</table>
