<?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 = "Offerte";
	

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

	
	$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'];
	$note = $rs[0]['note'];
	$note_aggiuntive = $rs[0]['note_aggiuntive'];
	$descrizione_prev = $rs[0]['descrizione_prev'];
	$riferimento_prev = $rs[0]['riferimento_prev'];
	$consegna = $rs[0]['consegna'];
	$validita = $rs[0]['validita'];
	$idreferente = $rs[0]['idreferente'];
	$stp_prezzi = $rs[0]['stp_prezzi'];
	$stp_sconti = $rs[0]['stp_sconti'];
	$stp_immagini = $rs[0]['stp_immagini'];
	$stp_descestesa = $rs[0]['stp_descestesa'];
	$created_by = $rs[0]['created_by'];
	
	$numero=$rs[0]['numero_documento'];

	$q1 = "SELECT nome FROM an_referenti WHERE id='$idreferente' ";
	$referente = $dbo->fetchArray( $q1 );
	$nomereferente = $referente[0]['nome'];
	
	//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/offerte/offerte.html");
	$body = file_get_contents ($docroot."/templates/offerte/offerte_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 );
	$body = str_replace( '$note$', $rs[0]['note'], $body );
	$body = str_replace( '$note_aggiuntive$', $rs[0]['note_aggiuntive'], $body );
	$body = str_replace( '$descrizione_prev$', $rs[0]['descrizione_prev'], $body );
	$body = str_replace( '$riferimento_prev$', $rs[0]['riferimento_prev'], $body );
	$body = str_replace( '$consegna$', $rs[0]['consegna'], $body );
	$body = str_replace( '$validita$', $rs[0]['validita'], $body );
	$body = str_replace( '$nomereferente$', $nomereferente, $body );
	$body = str_replace( '$created_by$', $created_by, $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();


	//Intestazione tabella per righe
	$body .= "<table class='table_values' cellspacing='0' style='table-layout:fixed; border:1px solid #aaa;' id='contents'>\n";
	if( $stp_prezzi != 0 ){
		$body .= "<col width='432' height='10' ><col width='25'><col width='25'><col width='56'><col width='56'><col width='28'>\n";
	}
	else {
		$body .= "<col width='628' height='10' ><col width='25'><col width='25'>\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";
	if( $stp_prezzi != 0 )
		$body .= "<th class='table_cell'  align='center' ><small>€/Unitario</small></th>\n";
	if( $stp_prezzi != 0 )
		$body .= "<th class='table_cell'  align='center'><small>€/Totale</small></th>\n";
	if( $stp_prezzi != 0 )
		$body .= "<th class='b-bottom'  align='center'><small>IVA</small></th>\n";
	$body .= "</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, IFNULL((SELECT immagine01 FROM mg_articoli WHERE id=idarticolo),'') AS immagine_articolo, IFNULL((SELECT note FROM mg_articoli WHERE id=idarticolo),'') AS note_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' style='border-top: 1px solid #aaa;'>\n";

		//Stampa con immagini articolo
		if( $stp_immagini != 0 ){	
			$body .= "<table style='vertical-align:top' border='0'>";
			  $body .= "<tr border='0'>";
				if( $righe[$i]['immagine_articolo']!='' )
					$body .= "<td border='0' valign='middle' ><img src=".$docroot."/files/articoli/".$righe[$i]['immagine_articolo']." width=\"60\" alt=\"Logo\" border=\"0\" /></td>";
				if( $stp_prezzi != 0 ){
					$body .= "<td width='355' valign='middle'>";
				}
				else {
					$body .= "<td width='540' valign='middle'>";
				}
				$body .= "<b>".nl2br( $righe[$i]['descrizione'] )."</b>";
				//Descrizione estesa
				if( $stp_descestesa != 0 ){
					if( $righe[$i]['note_articolo']!='' ){ $body .= "<br/><small>".nl2br($righe[$i]['note_articolo'])."</small>\n"; }
				}
				$body .= "</td>";
			  $body .= "</tr>";
			$body .= "</table>";
		}
		//Stampa senza immagini articolo
		else{
			$body .= "<b>".nl2br( $righe[$i]['descrizione'] )."</b>";
			if( $stp_descestesa != 0 ){
				if( $righe[$i]['note_articolo']!='' ){ $body .= "<br/><small>".nl2br($righe[$i]['note_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'], 0, ",", "");
		$body .= "<td class='center b-right' valign='middle' style='border-top: 1px solid #aaa;'>\n";
		$body .= $qta."\n";
		$body .= "</td>\n";
		
		
		//Unità di miusura
		$body .= "<td class='b-right'  align='center' valign='middle' style='border-top: 1px solid #aaa;'>\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;";
		if( $stp_prezzi != 0 ){
			$body .= "<td class='b-right'  align='right' valign='middle' style='border-top: 1px solid #aaa;'>\n";
			if ( $stampa_prezzi == '1' ) {		
				$body .= $subtotale;
			}
			$body .= "</td>\n";
		}

		//Imponibile
		( $righe[$i]['subtotale'] == 0 ) ? $subtot='' : $subtot=number_format( $righe[$i]['subtotale'], 2, ",", "." )." &euro;";
		if( $stp_prezzi != 0 ){
		$body .= "<td align='right' class='b-right' valign='middle' style='border-top: 1px solid #aaa;'>\n";
			if ( $stampa_prezzi == '1' ) {	
				$body .= "<b>".$subtot."</b>"."\n";
			}
			
			if( ( $righe[$i]['sconto']!=0) && ($stampa_prezzi == '1' ) && ($stp_sconti == '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
			if( $stp_prezzi != 0 ){
				$body .= "<td align='center' valign='middle' style='border-top: 1px solid #aaa;'>\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( $stp_prezzi != 0 ){
		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 = 10 - $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;
	}

	if( $stp_prezzi != 0 ){
	$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;



	//*****************************TOTALI PIE PAGINA*****************************************************************************
	/*
		SCADENZE  |  TOTALI
	*/
	

	
	
	//TABELLA PRINCIPALE
	$body .= "<table style='border:1px solid #aaa;' cellspacing='0'>\n";

	//Riga 1
	$body .= "	<tr>\n";
	$body .= "	<td style='width:158.6mm; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa;' valign='top' align='left'>\n";
	$body .= "		&nbsp;<small><small><b>Data Accettazione:</b></small></small>\n";
	$body .= "	</td>\n";
	$body .= "	<td style='width:33mm;' valign='top' class='b-bottom'>\n";
	$body .= "		<small><small><b>TOTALE IMPONIBILE</b></small></small>\n";
	$body .= "	</td>\n";
	$body .= "	</tr>\n";

	//Dati riga 1
	$body .= "	<tr>\n";
	$body .= "	<td rowspan='10' valign='top' class='b-right cell-padded'>\n";
	
	//Tabella (condizioni)
	$body .= "		<table align='left' style='border:0px solid #aaa;' cellspacing='0'>\n";
	$body .= "			<tr>\n";
	
	$body .= "				<td style='width:75mm; height:3mm; border: 1px solid #aaa; background: #ddd;'>\n";
	$body .= "					&nbsp;<small><small><b>Nome e cognome del responsabile</b></small></small>\n";
	$body .= "				</td>\n";
	$body .= "				<td style='width:79mm; border-top: 1px solid #aaa; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa; background: #ddd;'>\n";
	$body .= "					&nbsp;<small><small><b>Per conferma d'ordine - Timbro e Firma del responsabile</b></small></small>\n";
	$body .= "				</td>\n";
	$body .= "	</tr>\n";
	
		$body .= "			<tr>\n";
	
	$body .= "				<td style='width:75mm; height: 19mm; border-left: 1px solid #aaa; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa;'>\n";
	$body .= "				</td>\n";
	$body .= "				<td style='width:79mm; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa;'>\n";

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


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

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



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

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

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

		$totale_documento += $rivalsa_inps;
	}


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


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

	
	

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

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

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

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



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

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


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


	



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