<?php
	$iddocumento = save($_GET['iddocumento']);

	//Lettura tipo documento
	$q = "SELECT (SELECT dir FROM co_tipidocumento WHERE id=idtipodocumento) AS dir FROM co_documenti WHERE id=\"".$iddocumento."\"";
	$rs = $dbo->fetchArray($q);

	
	$nome_modulo = "Fatture di vendita";
	

	$additional_where[$nome_modulo] = str_replace( "|idanagrafica|", "'".$user_idanagrafica."'", $additional_where[$nome_modulo] );
	$n_rows = 0;
	$words4row = 70;

	
	$vedi_transazionepdf = get_var_tipodoc2($iddocumento,'vedi_transazionepdf');
	$stampa_prezzi = get_var_tipodoc2($iddocumento,'stampa_prezzi');

	//Lettura info fattura
	$q = "SELECT *, (SELECT descrizione FROM co_statidocumento WHERE id=idstatodocumento) AS stato_doc, (SELECT txt_suffisso FROM co_tipidocumento WHERE id=idtipodocumento) AS suffisso, (SELECT descrizione FROM co_tipidocumento WHERE id=idtipodocumento) AS tipo_doc, (SELECT descrizione FROM co_pagamenti WHERE id=idpagamento) AS tipo_pagamento, (SELECT dir FROM co_tipidocumento WHERE id=idtipodocumento) AS dir FROM co_documenti WHERE id=\"".$iddocumento."\" ".$additional_where[$nome_modulo];		
	$rs = $dbo->fetchArray($q);
	$tipo_doc = $rs[0]['tipo_doc'];
	$idcliente = $rs[0]['idanagrafica'];
	$idsede = $rs[0]['idsede'];
	$idbanca_vendite = $rs[0]['idbanca_vendite'];
	
	$numero=$rs[0]['numero_documento'];

	//Lettura righe documento
	$q2 = "SELECT * FROM co_righe_documenti INNER JOIN co_documenti ON co_righe_documenti.iddocumento=co_documenti.id WHERE iddocumento='$iddocumento' ".$additional_where[$nome_modulo];
	$righe = $dbo->fetchArray( $q2 );

	//carica report html
	$report = file_get_contents ($docroot."/templates/preventivi/preventivi.html");
	$body = file_get_contents ($docroot."/templates/preventivi/preventivi_body.html");

	include_once( "pdfgen_variables.php" );
	

	
		

	$body = str_replace( '$tipo_doc$', strtoupper($tipo_doc), $body );
	$body = str_replace( '$numero_doc$', $numero, $body );
	$body = str_replace( '$data$', date( "d/m/Y", strtotime($rs[0]['data']) ), $body );
	$body = str_replace( '$pagamento$', $rs[0]['tipo_pagamento'], $body );
	
	
	// cerco dati banca
	if( $idbanca_vendite > 0 ){
		$rs_banca = $dbo->fetchArray("SELECT * FROM co_banche WHERE id='".$idbanca_vendite."'");						
		$body = str_replace( '$f_appoggiobancario$', $rs_banca[0]['nome'], $body );
		$body = str_replace( '$f_codiceiban$', $rs_banca[0]['iban'], $body );
	} else{
		$id_azienda=get_var("Azienda predefinita");
		$q = "SELECT appoggiobancario , filiale,codiceiban  FROM an_anagrafiche WHERE idanagrafica=\"".$id_azienda."\"";
		$rs_banca = $dbo->fetchArray($q);
		$body = str_replace( '$f_appoggiobancario$', $rs_banca[0]['appoggiobancario'], $body );
		$body = str_replace( '$f_codiceiban$', $rs_banca[0]['codiceiban'], $body );
	}		
	
	
	
	//$body = str_replace( '$f_banca_appoggio$', $f_codiceiban, $body );

	//Leggo i dati della destinazione (se 0=sede legale, se!=altra sede da leggere da tabella an_sedi)
	$destinazione = '';
	if( $rs[0]['idsede']==0 ){
		$destinazione = '';
	}

	else{
		$queryd = "SELECT (SELECT codice FROM an_anagrafiche WHERE idanagrafica=an_sedi.idanagrafica) AS codice, (SELECT ragione_sociale FROM an_anagrafiche WHERE idanagrafica=an_sedi.idanagrafica) AS ragione_sociale, indirizzo, indirizzo2, cap, citta, provincia, piva, codice_fiscale FROM an_sedi WHERE idanagrafica='".$idcliente."' AND id='".$rs[0]['idsede']."'";
		$rsd = $dbo->fetchArray($queryd);

		if( $rsd[0]['indirizzo']!='' )
			$destinazione .= $rsd[0]['indirizzo']."<br/>\n";
		if( $rsd[0]['indirizzo2']!='' )
			$destinazione .= $rsd[0]['indirizzo2']."<br/>\n";
		if( $rsd[0]['cap']!='' )
			$destinazione .= $rsd[0]['cap']." ";
		if( $rsd[0]['citta']!='' )
			$destinazione .= $rsd[0]['citta'];
		if( $rsd[0]['provincia']!='' )
			$destinazione .= " (".$rsd[0]['provincia'].")\n";
	}

	$body = str_replace( '$c_destinazione$', $destinazione, $body );
	$v_iva = array();
	$v_totale = array();

	
	$desc_note=$rs[0]['descrizione_prev'];
	
	$body .= "<table class=\"table_values\" border=\"0\" cellpadding=\"0\" style=\"table-layout:fixed; border-color:#aaa;\">\n";
		$body .= "<col width=\"730\">\n"; 
		$body .= "<tr><td align=\"left\" style=\"font-size:10pt;\" >";
		$body .= "<small><b>OGGETTO:</b></small>";
		$body .= "$desc_note";
		$body .= "</td></tr>";		
		$body .= "</table><br/>";
	
	

	//Intestazione tabella per righe
	$body .= "<table class='table_values' cellspacing='0' style='table-layout:fixed; border:1px solid #aaa;' id='contents'>\n";
	$body .= "<col width='422' height='20' ><col width='35'><col width='30'><col width='56'><col width='56'><col width='28'>\n";
	$body .= "<thead>\n";
	$body .= "<tr>\n";
	
	$body .= "<th class='table_cell' align='center' ><small>DESCRIZIONE</small></th>\n";
	$body .= "<th class='table_cell' align='center' ><small>Q.T&Agrave;</small></th>\n";
	$body .= "<th class='table_cell' align='center' ><small>UM</small></th>\n";
	$body .= "<th class='table_cell'  align='center' ><small>COSTO UNITARIO</small></th>\n";
	$body .= "<th class='table_cell'  align='center'><small>IMPORTO</small></th>\n";
	$body .= "<th class='b-bottom'  align='center'><small>IVA</small></th></tr>\n";
	$body .= "</thead>\n";

	$body .= "<tbody>\n";

	//Mostro le righe del documento
	$totale_documento = 0;
	$totale_imponibile = 0;
	$totale_iva = 0;
	$sconto = 0;
	$imponibile = 0;
	$iva = 0;
	
	// RIGHE FATTURA CON ORDINAMENTO UNICO
	$q = "SELECT *, IFNULL((SELECT codice FROM mg_articoli WHERE id=idarticolo),'') AS codice_articolo, (SELECT percentuale FROM co_iva WHERE id=idiva) AS perc_iva FROM `co_righe_documenti` WHERE iddocumento='".$iddocumento."' ORDER BY ordine";

	$righe = $dbo->fetchArray( $q );
	$tot_righe = sizeof($righe);

	for( $i=0; $i<$tot_righe; $i++ ){

		$n_rows += ceil( strlen($righe[$i]['descrizione'])/$words4row );

		$body .= "<tr class='row".($x++ & 1 )."'  >\n";
		
		
		
		$body .= "<td class='b-right' valign='top'>\n";
		$body .= nl2br( $righe[$i]['descrizione'] );
		
		if( $righe[$i]['codice_articolo']!='' ){ $body .= "<br/><small>COD. ".$righe[$i]['codice_articolo']."</small>\n"; }
			
		
		// cerco riferimento transazione
		if( $vedi_transazionepdf != 0 ){								
			$query="SELECT iddocumento , numero_documento , data  FROM `co_righe_documenti` left join co_documenti on co_documenti.id = co_righe_documenti.iddocumento
			WHERE co_righe_documenti.id='".$righe[$i]['id_riferimento']."'";
			$rs_rif = $dbo->fetchArray( $query );
			if ( sizeof($rs_rif) > 0 ) {
				$descrizione_documento = get_var_tipodoc2($rs_rif[0]['iddocumento'],'descrizione');												
				$body .= "<br/><small>Rif. ".$descrizione_documento." n<sup>o </sup>".$rs_rif[0]['numero_documento']." del ".date("d/m/Y", strtotime($rs_rif[0]['data']) )."</small>";	
				$n_rows += 2 ;				
			}
		}

		
		$body .= "</td>\n";

		( $righe[$i]['qta'] == 0 ) ? $qta='' : $qta=number_format($righe[$i]['qta'], 1, ",", "");
		$body .= "<td class='center b-right' valign='top'>\n";
		$body .= $qta."\n";
		$body .= "</td>\n";
		
		
		//Unità di miusura
		$body .= "<td class='b-right'  align='center'  valign='top'>\n";
		$body .= nl2br( strtoupper($righe[$i]['um']) );
		$body .= "</td>\n";
		
		
		//Costo unitario
		( $righe[$i]['subtotale'] == 0 ) ? $subtotale='' : $subtotale=number_format( $righe[$i]['subtotale']/$righe[$i]['qta'], 2, ",", "" )." &euro;";
		$body .= "<td class='b-right'  align='right'  valign='top'>\n";
		if ( $stampa_prezzi == '1' ) {		
			$body .= $subtotale;
		}
		$body .= "</td>\n";
	

		//Imponibile
		( $righe[$i]['subtotale'] == 0 ) ? $subtot='' : $subtot=number_format( $righe[$i]['subtotale'], 2, ",", "." )." &euro;";
		$body .= "<td align='right' class='b-right' valign='top'>\n";
		if ( $stampa_prezzi == '1' ) {	
			$body .= $subtot."\n";
		}
		if( ( $righe[$i]['sconto']!=0) && ($stampa_prezzi == '1' )){
			$body .= "<br/>\n<small style='color:#555;'>- sconto ".number_format( $righe[$i]['sconto'], 2, ",", "." )." &euro;</small>\n";
			$n_rows += 2 ;
		}

		$body .= "</td>\n";
		if (  $qta > 0  ){
		// Iva solo se qta > 0
			$body .= "<td align='center' valign='top'>\n";
			if( $righe[$i]['idiva']!=0 )
				$body .= "	".intval($righe[$i]['perc_iva'])."%\n";
			$body .= "</td>\n";
		}
		$body .= "</tr>\n";


		$imponibile += $righe[$i]['subtotale'];
		$iva += $righe[$i]['iva'];
		$sconto += $righe[$i]['sconto'];

		$v_iva[ $righe[$i]['desc_iva'] ] += $righe[$i]['iva'];
		$v_totale[ $righe[$i]['desc_iva'] ] += $righe[$i]['subtotale']-$righe[$i]['sconto'];
	}

	$imponibile_documento += $imponibile;
	$totale_iva += $iva;
	$totale_documento += $imponibile;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// aggiungo diciture per condizioni iva particolari
	if( sizeof($v_iva) > 0 ){

		$testo = "Operazione soggetta a reverse charge ex art. 17, comma 6, DPR 633/72";
		// controllo se è stata applicata questa tipologia di iva
		foreach( $v_iva as $desc_iva => $tot_iva ){

			if( $desc_iva == 'Reverse charge ex art. 17, comma 6, DPR 633/72' ){

				$n_rows += 2;

				$body .= "<tr>\n";
				$body .= "	<td class='b-right' align='center' valign='top'>\n";
				$body .= "		<b>".nl2br( $testo )."</b>\n";
				$body .= "	</td>\n";

				$body .= "	<td class='center b-right' valign='top'>\n";
				$body .= "	</td>\n";
				$body .= "	<td class='center b-right' valign='top'>\n";
				$body .= "	</td>\n";
				$body .= "	<td class='center' valign='top'>\n";
				$body .= "	</td>\n";

				$body .= "</tr>\n";
			}
		} // end foreach


		$testo = "Senza addebito iva ex art. 74 comma 8-9 del DPR 633/72.";
		// controllo se è stata applicata questa tipologia di iva
		foreach( $v_iva as $desc_iva => $tot_iva ){

			if( $desc_iva == 'Esente ex art. 74' ){

				$n_rows += 2;

				$body .= "<tr>\n";
				$body .= "	<td class='b-right' align='center' valign='top'>\n";
				$body .= "		<b>".nl2br( $testo )."</b>\n";
				$body .= "	</td>\n";

				$body .= "	<td class='center b-right' valign='top'>\n";
				$body .= "	</td>\n";
				$body .= "	<td class='center b-right' valign='top'>\n";
				$body .= "	</td>\n";
				$body .= "	<td class='center' valign='top'>\n";
				$body .= "	</td>\n";

				$body .= "</tr>\n";
			}

		} // end foreach



	} // end if sizeof($v_iva)



	$height = 105 - $n_rows * 4.5;

	if( $rs[0]['ritenutaacconto'] > 0 ){
		$height -= 20;
	}
	
	/* aggiustamento righe con scadenze */
	$rs2 = $dbo->fetchArray("SELECT * FROM co_scadenziario WHERE iddocumento=\"".$iddocumento."\" ORDER BY `data_emissione` ASC");
	for( $i=0; $i<sizeof($rs2); $i++ ){
		$height -= 2;
	}


	$body .= "<tr>\n";
	$body .= "	<td style='height:".intval($height)."mm;' class='b-right'>&nbsp;</td>\n";
	$body .= "	<td class='b-right'></td>\n";
	$body .= "	<td class='b-right'></td>\n";
	$body .= "	<td class='b-right'></td>\n";
	$body .= "	<td class='b-right'></td>\n";
	$body .= "	<td></td>\n";
	$body .= "</tr>\n";

	$body .= "</tbody>\n";
	$body .= "</table><br/>\n";


	$imponibile_documento -= $sconto;
	$totale_documento = $totale_documento - $sconto + $totale_iva;




	/*
		SCADENZE  |  TOTALI
	*/
	//TABELLA PRINCIPALE
	$footer .= "<table style='margin-left:2.5mm; border:1px solid #aaa;' cellspacing='0'>\n";

	//Riga 1
	$footer .= "	<tr>\n";
	$footer .= "	<td style='width:158.6mm;' valign='top' align='center' class='b-right'>\n";
	$footer .= "	</td>\n";
	$footer .= "	<td style='width:33mm;' valign='top' class='b-bottom'>\n";
	$footer .= "		<small><small><b>TOTALE IMPONIBILE</b></small></small>\n";
	$footer .= "	</td></tr>\n";


	//Dati riga 1
	$footer .= "	<tr><td rowspan='10' valign='top' class='b-right cell-padded'>\n";
	
	//Tabella (condizioni)
	$footer .= "		<table align='left' border=\"0\" >\n";
	$footer .= "			<tr>\n";
	
	
	$footer .= "			<td style='width:20mm;'>\n";
	
	$footer .= "			</td>\n";
	//Fine elenco condizioni

	//Separatore
	$footer .= "			<td style='width:17mm;'>&nbsp;</td>\n";
	$footer .= "			<td style='width:70mm;'>\n";

	$footer .= "			</td></tr>\n";
	//Fine tabelle 
	$footer .= "		</table>\n";
	//Fine tabella (scadenze + iva)	
	$footer .= "	</td>\n";
	
	//TOTALE IMPONIBILE
	$footer .= "	<td valign='top' style='text-align:right;' class='b-bottom cell-padded'>\n";
	if ( $stampa_prezzi == '1' )  $footer .= "		".number_format( $imponibile_documento, 2, ",", "." )." &euro;\n";
	$footer .= "	</td></tr>\n";


	//Riga 2
	$footer .= "	<tr><td style='width:33mm;' valign='top' class='b-bottom'>\n";
	$footer .= "		<small><small><b>TOTALE IVA</b></small></small>\n";
	$footer .= "	</td></tr>\n";

	$footer .= "	<tr><td valign='top' style='text-align:right;' class='b-bottom cell-padded'>\n";
	if ( $stampa_prezzi == '1' ) $footer .= "		".number_format( $totale_iva, 2, ",", "." )." &euro;\n";
	$footer .= "	</td></tr>\n";



	//Mostra INPS se c'è
	if( abs($rs[0]['rivalsainps'])>0 ){
		$footer .= "<tr><td valign='top' class='b-bottom'>\n";
		$footer .= "	<small><small><b>Rivalsa INPS:</b></small></small>\n";
		$footer .= "</td></tr>\n";

		$rivalsa_inps = str_replace( ",", ".", $rs[0]['rivalsainps'] );

		//Rivalsa INPS
		$footer .= "	<tr><td valign='top' style='text-align:right;' class='b-bottom cell-padded'>\n";
		if ( $stampa_prezzi == '1' ) $footer .= "		".number_format( $rivalsa_inps, 2, ",", "." )." &euro;\n";
		$footer .= "	</td></tr>\n";

		$totale_documento += $rivalsa_inps;
	}


	
	//Mostra marca da bollo se c'è
	if( abs($rs[0]['bollo'])>0 ){
		$footer .= "	<tr><td valign='top' class='b-bottom'>\n";
		$footer .= "		<small><small><b>Marca da Bollo</b></small></small>\n";
		$footer .= "	</td></tr>\n";


		$marca_da_bollo = str_replace( ",", ".", $rs[0]['bollo'] );
			
		$footer .= "	<tr><td valign='top' style='text-align:right;' class='b-bottom cell-padded'>\n";
		if ( $stampa_prezzi == '1' ) $footer .= "		".number_format( $marca_da_bollo, 2, ",", "." )." &euro;\n";
		$footer .= "	</td></tr>\n";
		
		$totale_documento += $marca_da_bollo;
	}

	
	

	//Riga 3
	$footer .= "	<tr><td valign='top' class='b-bottom'>\n";
	$footer .= "		<small><small><b>TOTALE DOCUMENTO</b></small></small>\n";
	$footer .= "	</td></tr>\n";

	$footer .= "	<tr><td valign='top' style='text-align:right;' class='cell-padded'>\n";
	if ( $stampa_prezzi == '1' ) $footer .= "		".number_format( $totale_documento, 2, ",", "." )." &euro;\n";
	$footer .= "	</td></tr>\n";

	

	//Riga 4 (opzionale, solo se c'è la ritenuta d'acconto)
	if( $rs[0]['ritenutaacconto'] != 0 ){
		$rs2 = $dbo->fetchArray("SELECT percentuale FROM co_ritenutaacconto WHERE id=(SELECT idritenutaacconto FROM co_righe_documenti WHERE iddocumento='".$iddocumento."' AND idritenutaacconto!=0 LIMIT 0,1)");

		$footer .= "	<tr><td valign='top' class='b-bottom b-top'>\n";
		$footer .= "		<small><small><b>RITENUTA D'ACCONTO ".intval( $rs2[0]['percentuale'] )."%</b></small></small>\n";
		$footer .= "	</td></tr>\n";

		$footer .= "	<tr><td valign='top' style='text-align:right;' class='b-bottom cell-padded'>\n";
		if ( $stampa_prezzi == '1' ) $footer .= "		".number_format( $rs[0]['ritenutaacconto'], 2, ",", "." )." &euro;\n";
		$footer .= "	</td></tr>\n";



		$footer .= "	<tr><td valign='top' class='b-bottom'>\n";
		$footer .= "		<small><small><b>NETTO A PAGARE</b></small></small>\n";
		$footer .= "	</td></tr>\n";

		$footer .= "	<tr><td valign='top' style='text-align:right;' class='cell-padded'>\n";
		if ( $stampa_prezzi == '1' ) $footer .= "		".number_format( $totale_documento - $rs[0]['ritenutaacconto'], 2, ",", "." )." &euro;\n";
		$footer .= "	</td></tr>\n";
	}


	$footer .= "</table>\n";

	
	



	$report_name = "fattura_".$numero.".pdf";
?>