<?php
require('fpdf.php');
define('EURO', chr(128) );
define('EURO_VAL', 6.55957 );

// Xavier Nicolay 2004
// Version 1.02
//
// Reste à faire :
// + Multipage (gestion automatique sur plusieurs pages)
// + Ajout de logo
//

//////////////////////////////////////
// fonctions à utiliser (publiques) //
//////////////////////////////////////
//  function sizeOfText( $texte, $larg )
//  function addSociete( $nom, $adresse )
//  function fact_dev( $libelle, $num )
//  function addDevis( $numdev )
//  function addFacture( $numfact )
//  function addDate( $date )
//  function addClient( $ref )
//  function addPageNumber( $page )
//  function addClientAdresse( $adresse )
//  function addReglement( $mode )
//  function addEcheance( $date )
//  function addNumTVA($tva)
//  function addReference($ref)
//  function addCols( $tab )
//  function addLineFormat( $tab )
//  function lineVert( $tab )
//  function addLine( $ligne, $tab )
//  function addRemarque($remarque)
//  function addCadreTVAs()
//  function addCadreEurosFrancs()
//  function addTVAs( $params, $tab_tva, $invoice )
//  function temporaire( $texte )

class PDF_Invoice extends FPDF
{
// variables privées
var $colonnes;
var $format;
var $angle=0;

// fonctions privées
function RoundedRect($x, $y, $w, $h, $r, $style = '')
{
	$k = $this->k;
	$hp = $this->h;
	if($style=='F')
		$op='f';
	elseif($style=='FD' || $style=='DF')
		$op='B';
	else
		$op='S';
	$MyArc = 4/3 * (sqrt(2) - 1);
	$this->_out(sprintf('%.2F %.2F m',($x+$r)*$k,($hp-$y)*$k ));
	$xc = $x+$w-$r ;
	$yc = $y+$r;
	$this->_out(sprintf('%.2F %.2F l', $xc*$k,($hp-$y)*$k ));

	$this->_Arc($xc + $r*$MyArc, $yc - $r, $xc + $r, $yc - $r*$MyArc, $xc + $r, $yc);
	$xc = $x+$w-$r ;
	$yc = $y+$h-$r;
	$this->_out(sprintf('%.2F %.2F l',($x+$w)*$k,($hp-$yc)*$k));
	$this->_Arc($xc + $r, $yc + $r*$MyArc, $xc + $r*$MyArc, $yc + $r, $xc, $yc + $r);
	$xc = $x+$r ;
	$yc = $y+$h-$r;
	$this->_out(sprintf('%.2F %.2F l',$xc*$k,($hp-($y+$h))*$k));
	$this->_Arc($xc - $r*$MyArc, $yc + $r, $xc - $r, $yc + $r*$MyArc, $xc - $r, $yc);
	$xc = $x+$r ;
	$yc = $y+$r;
	$this->_out(sprintf('%.2F %.2F l',($x)*$k,($hp-$yc)*$k ));
	$this->_Arc($xc - $r, $yc - $r*$MyArc, $xc - $r*$MyArc, $yc - $r, $xc, $yc - $r);
	$this->_out($op);
}

function _Arc($x1, $y1, $x2, $y2, $x3, $y3)
{
	$h = $this->h;
	$this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c ', $x1*$this->k, ($h-$y1)*$this->k,
						$x2*$this->k, ($h-$y2)*$this->k, $x3*$this->k, ($h-$y3)*$this->k));
}

function Rotate($angle, $x=-1, $y=-1)
{
	if($x==-1)
		$x=$this->x;
	if($y==-1)
		$y=$this->y;
	if($this->angle!=0)
		$this->_out('Q');
	$this->angle=$angle;
	if($angle!=0)
	{
		$angle*=M_PI/180;
		$c=cos($angle);
		$s=sin($angle);
		$cx=$x*$this->k;
		$cy=($this->h-$y)*$this->k;
		$this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm',$c,$s,-$s,$c,$cx,$cy,-$cx,-$cy));
	}
}

function _endpage()
{
	if($this->angle!=0)
	{
		$this->angle=0;
		$this->_out('Q');
	}
	parent::_endpage();
}

// fonctions publiques
function sizeOfText( $texte, $largeur )
{
	if (0 == $largeur) {
		return 1;
	}
	$index    = 0;
	$nb_lines = 0;
	$loop     = TRUE;
	while ( $loop )
	{
		$pos = strpos($texte, "\n");
		if (!$pos)
		{
			$loop  = FALSE;
			$ligne = $texte;
		}
		else
		{
			$ligne  = substr( $texte, $index, $pos);
			$texte = substr( $texte, $pos+1 );
		}
		$length = floor( $this->GetStringWidth( $ligne ) );
		$res = 1 + floor( $length / $largeur) ;
		$nb_lines += $res;
	}
	return $nb_lines;
}

// Cette fonction affiche en haut, a gauche,
// le nom de la societe dans la police Arial-12-Bold
// les coordonnees de la societe dans la police Arial-10
function addSociete( $nom, $adresse, $period = '', $node = '', $orders = '' )
{
	$this->Image(sfConfig::get('sf_web_dir') . '/images/logo.gif', 7, 5, 30, 37, 'gif', sfConfig::get('app_katao_frontend_url'));
	$x1 = 10 + 33;
	$y1 = 8;
	//Positionnement en bas
	$this->SetXY( $x1, $y1 );
	$this->SetFont('Arial','B',12);
	$length = $this->GetStringWidth( $nom );
	$this->Cell( $length, 2, $nom);
	$this->SetXY( $x1, $y1 + 4 );
	$this->SetFont('Arial','',10);
	$length = $this->GetStringWidth( $adresse );
	//Coordonnées de la société
	$lignes = $this->sizeOfText( $adresse, $length) ;
	$this->MultiCell($length, 4, $adresse);

	$data = "";
	if ("" != $period) {
		$data .= "Période : $period";
	}
	if ("" != $node) {
		if ("" != $data) {
			$data .= "\n";
		}
		$data .= "Noeud : $node";
	}
	if ("" != $orders) {
		if ("" != $data) {
			$data .= "\n";
		}
		$data .= "Commande(s) : $orders";
	}
	if ("" != $data) {
		$length = $this->GetStringWidth( $data );
		$this->SetXY( $x1-37, $y1+40 );
		$this->MultiCell($length, 4, $data);
	}
}

// Affiche en haut, a droite le libelle
// (FACTURE, DEVIS, Bon de commande, etc...)
// et son numero
// La taille de la fonte est auto-adaptee au cadre
function fact_dev( $libelle, $num )
{
    $r1  = $this->w - 80;
    $r2  = $r1 + 68;
    $y1  = 6;
    $y2  = $y1 + 2;
    $mid = ($r1 + $r2 ) / 2;

    $texte  = $libelle . " en " . EURO . " N° : " . $num;
    $szfont = 12;
    $loop   = 0;

    while ( $loop == 0 )
    {
       $this->SetFont( "Arial", "B", $szfont );
       $sz = $this->GetStringWidth( $texte );
       if ( ($r1+$sz) > $r2 )
          $szfont --;
       else
          $loop ++;
    }

    $this->SetLineWidth(0.1);
    $this->SetFillColor(192);
    $this->RoundedRect($r1, $y1, ($r2 - $r1), $y2, 2.5, 'DF');
    $this->SetXY( $r1+1, $y1+2);
    $this->Cell($r2-$r1 -1,5, $texte, 0, 0, "C" );
}

// Genere automatiquement un numero de devis
function addDevis( $numdev )
{
	$string = sprintf("DEV%04d",$numdev);
	$this->fact_dev( "Devis", $string );
}

// Genere automatiquement un numero de facture
function addFacture( $numfact )
{
	$string = sprintf("FA%04d",$numfact);
	$this->fact_dev( "Facture", $string );
}

// Affiche un cadre avec la date de la facture / devis
// (en haut, a droite)
function addDate( $date )
{
	$r1  = $this->w - 61;
	$r2  = $r1 + 30;
	$y1  = 17;
	$y2  = $y1 ;
	$mid = $y1 + ($y2 / 2);
	$this->RoundedRect($r1, $y1, ($r2 - $r1), $y2, 3.5, 'D');
	$this->Line( $r1, $mid, $r2, $mid);
	$this->SetXY( $r1 + ($r2-$r1)/2 - 5, $y1+3 );
	$this->SetFont( "Arial", "B", 10);
	$this->Cell(10,5, "DATE", 0, 0, "C");
	$this->SetXY( $r1 + ($r2-$r1)/2 - 5, $y1+9 );
	$this->SetFont( "Arial", "", 10);
	$this->Cell(10,5,$date, 0,0, "C");
}

// Affiche un cadre avec les references du client
// (en haut, a droite)
function addClient( $ref )
{
	$r1  = $this->w - 31;
	$r2  = $r1 + 19;
	$y1  = 17;
	$y2  = $y1;
	$mid = $y1 + ($y2 / 2);
	$this->RoundedRect($r1, $y1, ($r2 - $r1), $y2, 3.5, 'D');
	$this->Line( $r1, $mid, $r2, $mid);
	$this->SetXY( $r1 + ($r2-$r1)/2 - 5, $y1+3 );
	$this->SetFont( "Arial", "B", 10);
	$this->Cell(10,5, "REF", 0, 0, "C");
	$this->SetXY( $r1 + ($r2-$r1)/2 - 5, $y1 + 9 );
	$this->SetFont( "Arial", "", 10);
	$this->Cell(10,5,$ref, 0,0, "C");
}

// Affiche un cadre avec un numero de page
// (en haut, a droite)
function addPageNumber( $page )
{
	$r1  = $this->w - 80;
	$r2  = $r1 + 19;
	$y1  = 17;
	$y2  = $y1;
	$mid = $y1 + ($y2 / 2);
	$this->RoundedRect($r1, $y1, ($r2 - $r1), $y2, 3.5, 'D');
	$this->Line( $r1, $mid, $r2, $mid);
	$this->SetXY( $r1 + ($r2-$r1)/2 - 5, $y1+3 );
	$this->SetFont( "Arial", "B", 10);
	$this->Cell(10,5, "PAGE", 0, 0, "C");
	$this->SetXY( $r1 + ($r2-$r1)/2 - 5, $y1 + 9 );
	$this->SetFont( "Arial", "", 10);
	$this->Cell(10,5,$page, 0,0, "C");
}

// Affiche l'adresse du client
// (en haut, a droite)
function addClientAdresse( $adresse )
{
	$r1     = $this->w - 80;
	$r2     = $r1 + 68;
	$y1     = 40;
	$this->SetXY( $r1, $y1);
	$this->MultiCell( 60, 4, $adresse);
}

// Affiche un cadre avec le règlement (chèque, etc...)
// (en haut, a gauche)
function addReglement( $mode )
{
	$r1  = 10;
	$r2  = $r1 + 60;
	$y1  = 80;
	$y2  = $y1+10;
	$mid = $y1 + (($y2-$y1) / 2);
	$this->RoundedRect($r1, $y1, ($r2 - $r1), ($y2-$y1), 2.5, 'D');
	$this->Line( $r1, $mid, $r2, $mid);
	$this->SetXY( $r1 + ($r2-$r1)/2 -5 , $y1+1 );
	$this->SetFont( "Arial", "B", 10);
	$this->Cell(10,4, "MODE DE REGLEMENT", 0, 0, "C");
	$this->SetXY( $r1 + ($r2-$r1)/2 -5 , $y1 + 5 );
	$this->SetFont( "Arial", "", 10);
	$this->Cell(10,5,$mode, 0,0, "C");
}

// Affiche un cadre avec la date d'echeance
// (en haut, au centre)
function addEcheance( $date )
{
	$r1  = 80;
	$r2  = $r1 + 40;
	$y1  = 80;
	$y2  = $y1+10;
	$mid = $y1 + (($y2-$y1) / 2);
	$this->RoundedRect($r1, $y1, ($r2 - $r1), ($y2-$y1), 2.5, 'D');
	$this->Line( $r1, $mid, $r2, $mid);
	$this->SetXY( $r1 + ($r2 - $r1)/2 - 5 , $y1+1 );
	$this->SetFont( "Arial", "B", 10);
	$this->Cell(10,4, "DATE D'ECHEANCE", 0, 0, "C");
	$this->SetXY( $r1 + ($r2-$r1)/2 - 5 , $y1 + 5 );
	$this->SetFont( "Arial", "", 10);
	$this->Cell(10,5,$date, 0,0, "C");
}

// Affiche un cadre avec le numero de la TVA
// (en haut, au droite)
function addNumTVA($tva)
{
	$this->SetFont( "Arial", "B", 10);
	$r1  = $this->w - 80;
	$r2  = $r1 + 70;
	$y1  = 80;
	$y2  = $y1+10;
	$mid = $y1 + (($y2-$y1) / 2);
	$this->RoundedRect($r1, $y1, ($r2 - $r1), ($y2-$y1), 2.5, 'D');
	$this->Line( $r1, $mid, $r2, $mid);
	$this->SetXY( $r1 + 16 , $y1+1 );
	$this->Cell(40, 4, "TVA Intracommunautaire", '', '', "C");
	$this->SetFont( "Arial", "", 10);
	$this->SetXY( $r1 + 16 , $y1+5 );
	$this->Cell(40, 5, $tva, '', '', "C");
}

// Affiche une ligne avec des reference
// (en haut, a gauche)
function addReference($ref)
{
	$this->SetFont( "Arial", "", 10);
	$length = $this->GetStringWidth( $ref );
	$r1  = 10;
	$r2  = $r1 + $length;
	$y1  = 92;
	$y2  = $y1+5;
	$this->SetXY( $r1 , $y1 );
	$this->Cell($length,4, $ref);
}

// trace le cadre des colonnes du devis/facture
function addCols( $tab )
{
	global $colonnes;

	$r1  = 10;
	$r2  = $this->w - ($r1 * 2) ;
	$y1  = 100;
	$y2  = $this->h - 50 - $y1;
	$this->SetXY( $r1, $y1 );
	$this->Rect( $r1, $y1, $r2, $y2, "D");
	$this->Line( $r1, $y1+6, $r1+$r2, $y1+6);
	$colX = $r1;
	$colonnes = $tab;
	while ( list( $lib, $pos ) = each ($tab) )
	{
		$this->SetXY( $colX, $y1+2 );
		$this->Cell( $pos, 1, $lib, 0, 0, "C");
		$colX += $pos;
		$this->Line( $colX, $y1, $colX, $y1+$y2);
	}
}

// mémorise le format (gauche, centre, droite) d'une colonne
function addLineFormat( $tab )
{
	global $format, $colonnes;

	while ( list( $lib, $pos ) = each ($colonnes) )
	{
		if ( isset( $tab["$lib"] ) )
			$format[ $lib ] = $tab["$lib"];
	}
}

function lineVert( $tab )
{
	global $colonnes;

	reset( $colonnes );
	$maxSize=0;
	while ( list( $lib, $pos ) = each ($colonnes) )
	{
		$texte = $tab[ $lib ];
		$longCell  = $pos -2;
		$size = $this->sizeOfText( $texte, $longCell );
		if ($size > $maxSize)
			$maxSize = $size;
	}
	return $maxSize;
}

// Affiche chaque "ligne" d'un devis / facture
/*    $ligne = array( "REFERENCE"    => $prod["ref"],
                      "DESIGNATION"  => $libelle,
                      "QUANTITE"     => sprintf( "%.2F", $prod["qte"]) ,
                      "P.U. HT"      => sprintf( "%.2F", $prod["px_unit"]),
                      "MONTANT H.T." => sprintf ( "%.2F", $prod["qte"] * $prod["px_unit"]) ,
                      "TVA"          => $prod["tva"] );
*/
function addLine( $ligne, $tab )
{
	global $colonnes, $format;

	$ordonnee     = 10;
	$maxSize      = $ligne;

	reset( $colonnes );
	while ( list( $lib, $pos ) = each ($colonnes) )
	{
		$longCell  = $pos -2;
		$texte     = $tab[ $lib ];
		$length    = $this->GetStringWidth( $texte );
		$tailleTexte = $this->sizeOfText( $texte, $length );
		$formText  = $format[ $lib ];
		$this->SetXY( $ordonnee, $ligne-1);
		$this->MultiCell( $longCell, 4 , $texte, 0, $formText);
		if ( $maxSize < ($this->GetY()  ) )
			$maxSize = $this->GetY() ;
		$ordonnee += $pos;
	}
	return ( $maxSize - $ligne );
}

// Ajoute une remarque (en bas, a gauche)
function addRemarque($remarque)
{
	$this->SetFont( "Arial", "", 10);
	$length = $this->GetStringWidth( "Remarque : " . $remarque );
	$r1  = 10;
	$r2  = $r1 + $length;
	$y1  = $this->h - 45.5;
	$y2  = $y1+5;
	$this->SetXY( $r1 , $y1 );
	$this->Cell($length,4, "Remarque : " . $remarque);
}

// trace le cadre des TVA
function addCadreTVAs()
{
	$this->SetFont( "Arial", "B", 8);
	$r1  = 10;
	$r2  = $r1 + 120;
	$y1  = $this->h - 40;
	$y2  = $y1+20;
	$this->RoundedRect($r1, $y1, ($r2 - $r1), ($y2-$y1), 2.5, 'D');
	$this->Line( $r1, $y1+4, $r2, $y1+4);
	$this->Line( $r1+5,  $y1+4, $r1+5, $y2); // avant BASES HT
	$this->Line( $r1+27, $y1, $r1+27, $y2);  // avant REMISE
	$this->Line( $r1+43, $y1, $r1+43, $y2);  // avant MT TVA
	$this->Line( $r1+63, $y1, $r1+63, $y2);  // avant % TVA
	$this->Line( $r1+75, $y1, $r1+75, $y2);  // avant PORT
	$this->Line( $r1+91, $y1, $r1+91, $y2);  // avant TOTAUX
	$this->SetXY( $r1+9, $y1);
	$this->Cell(10,4, "BASES HT");
	$this->SetX( $r1+29 );
	$this->Cell(10,4, "REMISE");
	$this->SetX( $r1+48 );
	$this->Cell(10,4, "MT TVA");
	$this->SetX( $r1+63 );
	$this->Cell(10,4, "% TVA");
	$this->SetX( $r1+78 );
	$this->Cell(10,4, "PORT");
	$this->SetX( $r1+100 );
	$this->Cell(10,4, "TOTAUX");
	$this->SetFont( "Arial", "B", 6);
	$this->SetXY( $r1+93, $y2 - 8 );
	$this->Cell(6,0, "H.T.   :");
	$this->SetXY( $r1+93, $y2 - 3 );
	$this->Cell(6,0, "T.V.A. :");
}

// trace le cadre des totaux
function addCadreEurosFrancs()
{
	$r1  = $this->w - 70;
	$r2  = $r1 + 60;
	$y1  = $this->h - 40;
	$y2  = $y1+20;
	$this->RoundedRect($r1, $y1, ($r2 - $r1), ($y2-$y1), 2.5, 'D');
	$this->Line( $r1+20,  $y1, $r1+20, $y2); // avant EUROS
	$this->Line( $r1+20, $y1+4, $r2, $y1+4); // Sous Euros & Francs
	$this->Line( $r1+38,  $y1, $r1+38, $y2); // Entre Euros & Francs
	$this->SetFont( "Arial", "B", 8);
	$this->SetXY( $r1+22, $y1 );
	$this->Cell(15,4, "EUROS", 0, 0, "C");
	$this->SetFont( "Arial", "", 8);
	$this->SetXY( $r1+42, $y1 );
	$this->Cell(15,4, "FRANCS", 0, 0, "C");
	$this->SetFont( "Arial", "B", 6);
	$this->SetXY( $r1, $y1+5 );
	$this->Cell(20,4, "TOTAL TTC", 0, 0, "C");
	$this->SetXY( $r1, $y1+10 );
	$this->Cell(20,4, "ACOMPTE", 0, 0, "C");
	$this->SetXY( $r1, $y1+15 );
	$this->Cell(20,4, "NET A PAYER", 0, 0, "C");
}

// remplit les cadres TVA / Totaux et la remarque
// params  = array( "RemiseGlobale" => [0|1],
//                      "remise_tva"     => [1|2...],  // {la remise s'applique sur ce code TVA}
//                      "remise"         => value,     // {montant de la remise}
//                      "remise_percent" => percent,   // {pourcentage de remise sur ce montant de TVA}
//                  "FraisPort"     => [0|1],
//                      "portTTC"        => value,     // montant des frais de ports TTC
//                                                     // par defaut la TVA = 19.6 %
//                      "portHT"         => value,     // montant des frais de ports HT
//                      "portTVA"        => tva_value, // valeur de la TVA a appliquer sur le montant HT
//                  "AccompteExige" => [0|1],
//                      "accompte"         => value    // montant de l'acompte (TTC)
//                      "accompte_percent" => percent  // pourcentage d'acompte (TTC)
//                  "Remarque" => "texte"              // texte
// tab_tva = array( "1"       => 19.6,
//                  "2"       => 5.5, ... );
// invoice = array( "px_unit" => value,
//                  "qte"     => qte,
//                  "tva"     => code_tva );
function addTVAs( $params, $tab_tva, $invoice, $katao_supplier_invoice = null )
{
	$this->SetFont('Arial','',8);

	reset ($invoice);
	$px = array();
	while ( list( $k, $prod) = each( $invoice ) )
	{
		$tva = $prod["tva"];
		@ $px[$tva] += $prod["qte"] * $prod["px_unit"];
	}

	$prix     = array();
	$totalHT  = 0;
	$totalTTC = 0;
	$totalTVA = 0;
	$y = 261;
	reset ($px);
	natsort( $px );
	while ( list($code_tva, $articleHT) = each( $px ) )
	{
		$tva = $tab_tva[$code_tva];
		$this->SetXY(17, $y);
		$this->Cell( 19,4, Utils::formatCurrency($articleHT),'', '','R' );
		if ( $params["RemiseGlobale"]==1 )
		{
			if ( $params["remise_tva"] == $code_tva )
			{
				$this->SetXY( 37.5, $y );
				if ($params["remise"] > 0 )
				{
					if ( is_int( $params["remise"] ) )
						$l_remise = $param["remise"];
					else
						$l_remise = sprintf ("%0.2F", $params["remise"]);
					$this->Cell( 14.5,4, $l_remise, '', '', 'R' );
					$articleHT -= $params["remise"];
				}
				else if ( $params["remise_percent"] > 0 )
				{
					$rp = $params["remise_percent"];
					if ( $rp > 1 )
						$rp /= 100;
					$rabais = $articleHT * $rp;
					$articleHT -= $rabais;
					if ( is_int($rabais) )
						$l_remise = $rabais;
					else
						$l_remise = sprintf ("%0.2F", $rabais);
					$this->Cell( 14.5,4, $l_remise, '', '', 'R' );
				}
				else
					$this->Cell( 14.5,4, "ErrorRem", '', '', 'R' );
			}
		}

		$totalHT += $articleHT;
		$totalTTC += $articleHT * ( 1 + $tva/100 );
		$tmp_tva = $articleHT * $tva/100;

		/* Custom - Begin */
		if (!is_null($katao_supplier_invoice)) {
			$getTauxAmount = sprintf('getTaux%dAmount', $code_tva);
			$tmp_tva = $katao_supplier_invoice->$getTauxAmount();
		}
		/* Custom - End */

		$a_tva[ $code_tva ] = $tmp_tva;
		$totalTVA += $tmp_tva;
		$this->SetXY(11, $y);
		$this->Cell( 5,4, $code_tva);
		$this->SetXY(53, $y);
		$this->Cell( 19,4, Utils::formatCurrency($tmp_tva),'', '' ,'R');
		$this->SetXY(74, $y);
		$this->Cell( 10,4, Utils::formatCurrency($tva) ,'', '', 'R');
		$y+=4;
	}

	if ( $params["FraisPort"] == 1 )
	{
		if ( $params["portTTC"] > 0 )
		{
			$pTTC = sprintf("%0.2F", $params["portTTC"]);
			$pHT  = sprintf("%0.2F", $pTTC / 1.196);
			$pTVA = sprintf("%0.2F", $pHT * 0.196);
			$this->SetFont('Arial','',6);
			$this->SetXY(85, 261 );
			$this->Cell( 6 ,4, "HT : ", '', '', '');
			$this->SetXY(92, 261 );
			$this->Cell( 9 ,4, $pHT, '', '', 'R');
			$this->SetXY(85, 265 );
			$this->Cell( 6 ,4, "TVA : ", '', '', '');
			$this->SetXY(92, 265 );
			$this->Cell( 9 ,4, $pTVA, '', '', 'R');
			$this->SetXY(85, 269 );
			$this->Cell( 6 ,4, "TTC : ", '', '', '');
			$this->SetXY(92, 269 );
			$this->Cell( 9 ,4, $pTTC, '', '', 'R');
			$this->SetFont('Arial','',8);
			$totalHT += $pHT;
			$totalTVA += $pTVA;
			$totalTTC += $pTTC;
		}
		else if ( $params["portHT"] > 0 )
		{
			$pHT  = sprintf("%0.2F", $params["portHT"]);
			$pTVA = sprintf("%0.2F", $params["portTVA"] * $pHT / 100 );
			$pTTC = sprintf("%0.2F", $pHT + $pTVA);
			$this->SetFont('Arial','',6);
			$this->SetXY(85, 261 );
			$this->Cell( 6 ,4, "HT : ", '', '', '');
			$this->SetXY(92, 261 );
			$this->Cell( 9 ,4, $pHT, '', '', 'R');
			$this->SetXY(85, 265 );
			$this->Cell( 6 ,4, "TVA : ", '', '', '');
			$this->SetXY(92, 265 );
			$this->Cell( 9 ,4, $pTVA, '', '', 'R');
			$this->SetXY(85, 269 );
			$this->Cell( 6 ,4, "TTC : ", '', '', '');
			$this->SetXY(92, 269 );
			$this->Cell( 9 ,4, $pTTC, '', '', 'R');
			$this->SetFont('Arial','',8);
			$totalHT += $pHT;
			$totalTVA += $pTVA;
			$totalTTC += $pTTC;
		}
	}

	/* Custom - Begin */
	if (!is_null($katao_supplier_invoice)) {
		$totalHT = $katao_supplier_invoice->getTotalHt();
		$totalTVA = $katao_supplier_invoice->getTotalTva();
	}
	/* Custom - End */

	$this->SetXY(114,266.4);
	$this->Cell(15,4, Utils::formatCurrency($totalHT), '', '', 'R' );
	$this->SetXY(114,271.4);
	$this->Cell(15,4, Utils::formatCurrency($totalTVA), '', '', 'R' );

	$params["totalHT"] = $totalHT;
	$params["TVA"] = $totalTVA;
	$accompteTTC=0;
	if ( $params["AccompteExige"] == 1 )
	{
		if ( $params["accompte"] > 0 )
		{
			$accompteTTC=sprintf ("%.2F", $params["accompte"]);
			if ( strlen ($params["Remarque"]) == 0 )
				$this->addRemarque( "Acompte de $accompteTTC Euros exigé à la commande.");
			else
				$this->addRemarque( $params["Remarque"] );
		}
		else if ( $params["accompte_percent"] > 0 )
		{
			$percent = $params["accompte_percent"];
			if ( $percent > 1 )
				$percent /= 100;
			$accompteTTC=sprintf("%.2F", $totalTTC * $percent);
			$percent100 = $percent * 100;
			if ( strlen ($params["Remarque"]) == 0 )
				$this->addRemarque( "Acompte de $percent100 % (soit $accompteTTC Euros) exigé à la commande." );
			else
				$this->addRemarque( $params["Remarque"] );
		}
		else
			$this->addRemarque( "Drôle d'acompte !!! " . $params["Remarque"]);
	}
	else
	{
		if ( strlen ($params["Remarque"]) > 0 )
			$this->addRemarque( $params["Remarque"] );
	}

	/* Custom - Begin */
	if (!is_null($katao_supplier_invoice)) {
		$totalTTC = $totalHT+$totalTVA;
	}
	$totalTTC = round($totalTTC, 2);
	$accompteTTC = round($accompteTTC, 2);
	/* Custom - End */

	$re  = $this->w - 50;
	$rf  = $this->w - 29;
	$y1  = $this->h - 40;
	$this->SetFont( "Arial", "", 8);
	$this->SetXY( $re, $y1+5 );
	$this->Cell( 17,4, Utils::formatCurrency($totalTTC), '', '', 'R');
	$this->SetXY( $re, $y1+10 );
	$this->Cell( 17,4, Utils::formatCurrency($accompteTTC), '', '', 'R');
	$this->SetXY( $re, $y1+14.8 );
	$this->Cell( 17,4, Utils::formatCurrency($totalTTC - $accompteTTC), '', '', 'R');
	$this->SetXY( $rf, $y1+5 );
	$this->Cell( 17,4, Utils::formatCurrency($totalTTC * EURO_VAL), '', '', 'R');
	$this->SetXY( $rf, $y1+10 );
	$this->Cell( 17,4, Utils::formatCurrency($accompteTTC * EURO_VAL), '', '', 'R');
	$this->SetXY( $rf, $y1+14.8 );
	$this->Cell( 17,4, Utils::formatCurrency(($totalTTC - $accompteTTC) * EURO_VAL), '', '', 'R');
}

// Permet de rajouter un commentaire (Devis temporaire, REGLE, DUPLICATA, ...)
// en sous-impression
// ATTENTION: APPELER CETTE FONCTION EN PREMIER
function temporaire( $texte )
{
	$this->SetFont('Arial','B',50);
	$this->SetTextColor(203,203,203);
	$this->Rotate(45,55,190);
	$this->Text(55,190,$texte);
	$this->Rotate(0);
	$this->SetTextColor(0,0,0);
}

	/**
	 * PDF_Invoice::addPageHeaderInvoice()
	 *
	 * @param int $page
	 * @param KataoInvoice $katao_invoice
	 * @param KataoMember $katao_member
	 * @return
	 */
	function addPageHeaderInvoice($page, $katao_invoice, $katao_member){
		$this->AddPage();
		$this->addSociete($katao_invoice->getKataoName(),
            $katao_invoice->getKataoAddress() . "\n" .
            "SIRET " . $katao_invoice->getKataoSiretNumber() . "\n" .
            "R.C.S. " . $katao_invoice->getKataoRcsNumber() . "\n" .
            "Capital : " . $katao_invoice->getKataoCapital() . " " . EURO, utf8_decode($katao_invoice->getKataoPeriod()->getName()), $katao_invoice->getKataoNode()->getCity());
		$this->fact_dev("Facture", $katao_invoice->getNumber());
		// $this->temporaire("Devis temporaire");
		$this->addDate($katao_invoice->getCreatedAt('d/m/Y'));
		$this->addClient($katao_member->getAccountingCode());
		$this->addPageNumber($page++);
		$this->addClientAdresse(utf8_decode(sprintf("%s %s\n%s%s\n%s%s", $katao_invoice->getMemberLastName(), $katao_invoice->getMemberFirstName(), $katao_invoice->getMemberAddress1(), $katao_invoice->getMemberAddress2()?sprintf("\n%s", $katao_invoice->getMemberAddress2()):'', $katao_invoice->getMemberZip()?sprintf("%s ", $katao_invoice->getMemberZip()):'', $katao_invoice->getMemberCity())));
		$this->addReglement("Payée");
		$this->addEcheance($katao_invoice->getCreatedAt('d/m/Y'));
		$this->addNumTVA(wpConfig::getTvaNumber());
		$this->addReference('Votre solde est désormais de ' . number_format($katao_member->getCurrentAmountEuro(), 2, ',', ' ') . ' ' . EURO . ' et ' . $katao_member->getCurrentAmountSolStr());
		$cols = array("REFERENCE" => 23,
            "DESIGNATION" => 78,
            "QUANTITE" => 22,
            "P.U. TTC" => 26,
            "MONTANT TTC" => 30,
            "TVA" => 11);
		$this->addCols($cols);
		$cols = array("REFERENCE" => "L",
            "DESIGNATION" => "L",
            "QUANTITE" => "C",
            "P.U. TTC" => "R",
            "MONTANT TTC" => "R",
            "TVA" => "C");
		$this->addLineFormat($cols);
		$this->addLineFormat($cols);
		return $page;
	}

	/**
	 * PDF_Invoice::addPageHeaderOrder()
	 *
	 * @param int $page
	 * @param KataoOrder $katao_order
	 * @param KataoSupplier $katao_supplier
	 * @return
	 */
	function addPageHeaderOrder($page, $katao_order, $katao_supplier){
		$this->AddPage();
		$this->addSociete($katao_order->getKataoName(),
            $katao_order->getKataoAddress() . "\n" .
            "SIRET " . $katao_order->getKataoSiretNumber() . "\n" .
            "R.C.S. " . $katao_order->getKataoRcsNumber() . "\n" .
            "Capital : " . $katao_order->getKataoCapital() . " " . EURO, utf8_decode($katao_order->getKataoPeriod()->getName()), $katao_order->getKataoNode()->getCity());
		$this->fact_dev("Commande", $katao_order->getNumber());
		// $this->temporaire("Devis temporaire");
		$this->addDate($katao_order->getCreatedAt('d/m/Y'));
		$this->addClient($katao_supplier->getAccountingCode());
		$this->addPageNumber($page++);
		$this->addClientAdresse(utf8_decode(sprintf("%s\n%s%s\n%s%s", $katao_order->getSupplierName(), $katao_order->getSupplierAddress1(), $katao_order->getSupplierAddress2()?sprintf("\n%s", $katao_order->getSupplierAddress2()):'', $katao_order->getSupplierZip()?sprintf("%s ", $katao_order->getSupplierZip()):'', $katao_order->getSupplierCity())));
		//$this->addReglement("Payée");
		//$this->addEcheance($katao_order->getCreatedAt('d/m/Y'));
		$this->addNumTVA(wpConfig::getTvaNumber());
		if ('' != $katao_order->getDeliveryAddress()) {
			$this->addReference('Adresse de livraison : ' . str_replace("\n", ' - ', $katao_order->getDeliveryAddress()));
		}
		$cols = array("REFERENCE" => 23,
            "DESIGNATION" => 78,
            "QUANTITE" => 22,
            "P.U. TTC" => 26,
            "MONTANT TTC" => 30,
            "TVA" => 11);
		$this->addCols($cols);
		$cols = array("REFERENCE" => "L",
            "DESIGNATION" => "L",
            "QUANTITE" => "C",
            "P.U. TTC" => "R",
            "MONTANT TTC" => "R",
            "TVA" => "C");
		$this->addLineFormat($cols);
		$this->addLineFormat($cols);
		return $page;
	}

	/**
	 * PDF_Invoice::addPageHeaderCart()
	 *
	 * @param int $page
	 * @param KataoCart $katao_cart
	 * @param KataoMember $katao_member
	 * @param KataoUser $katao_user
	 * @return
	 */
	function addPageHeaderCart($page, $katao_cart, $katao_member, $katao_user){
		$this->AddPage();
		$this->addSociete(wpConfig::getName(),
            wpConfig::getAddress() . "\n" .
            "SIRET " . wpConfig::getSiretNumber() . "\n" .
            "R.C.S. " . wpConfig::getRcsNumber() . "\n" .
            "Capital : " . wpConfig::getCapital() . " " . EURO, utf8_decode($katao_cart->getKataoPeriod()->getName()), $katao_cart->getKataoNode()->getCity());
		$this->fact_dev("Demande", $katao_cart->getNumber());
		$this->temporaire("Demande");
		$this->addDate($katao_cart->getCreatedAt('d/m/Y'));
		$this->addClient($katao_member->getAccountingCode());
		$this->addPageNumber($page++);
		$this->addClientAdresse(utf8_decode(sprintf("%s %s\n%s%s\n%s%s", $katao_member->getLastName(), $katao_member->getFirstName(), $katao_user->getAddress1(), $katao_user->getAddress2()?sprintf("\n%s", $katao_user->getAddress2()):'', $katao_user->getZip()?sprintf("%s ", $katao_user->getZip()):'', $katao_user->getCity())));
		//$this->addReglement("Payée");
		//$this->addEcheance($katao_cart->getCreatedAt('d/m/Y'));
		$this->addNumTVA(wpConfig::getTvaNumber());
		//$this->addReference('Votre solde est actuellement de ' . number_format($katao_member->getCurrentAmountEuro(), 2, ',', ' ') . ' ' . EURO . ' et '.$katao_member->getCurrentAmountSol().' SOL');
		$cols = array("REFERENCE" => 23,
            "DESIGNATION" => 78,
            "QUANTITE" => 22,
            "P.U. TTC" => 26,
            "MONTANT TTC" => 30,
            "TVA" => 11);
		$this->addCols($cols);
		$cols = array("REFERENCE" => "L",
            "DESIGNATION" => "L",
            "QUANTITE" => "C",
            "P.U. TTC" => "R",
            "MONTANT TTC" => "R",
            "TVA" => "C");
		$this->addLineFormat($cols);
		$this->addLineFormat($cols);
		return $page;
	}

	/**
	 * PDF_Invoice::addPageHeaderSupplierInvoice()
	 *

	 * @param int $page
	 * @param KataoSupplierInvoice $katao_supplier_invoice
	 * @param KataoSupplier $katao_supplier
	 * @return
	 */
	function addPageHeaderSupplierInvoice($page, $katao_supplier_invoice, $katao_supplier){
		$this->AddPage();
		$this->addSociete($katao_supplier_invoice->getKataoName(),
            $katao_supplier_invoice->getKataoAddress() . "\n" .
            "SIRET " . $katao_supplier_invoice->getKataoSiretNumber() . "\n" .
            "R.C.S. " . $katao_supplier_invoice->getKataoRcsNumber() . "\n" .
            "Capital : " . $katao_supplier_invoice->getKataoCapital() . " " . EURO, utf8_decode($katao_supplier_invoice->getKataoPeriod()->getName()), '', $katao_supplier_invoice->getOrdersStr());
		$this->fact_dev("Facture", $katao_supplier_invoice->getReference());
		// $this->temporaire("Devis temporaire");
		$this->addDate($katao_supplier_invoice->getInvoiceDate('d/m/Y'));
		$this->addClient($katao_supplier->getAccountingCode());
		$this->addPageNumber($page++);
		$this->addClientAdresse(utf8_decode(sprintf("%s\n%s%s\n%s%s", $katao_supplier_invoice->getSupplierName(), $katao_supplier_invoice->getSupplierAddress1(), $katao_supplier_invoice->getSupplierAddress2()?sprintf("\n%s", $katao_supplier_invoice->getSupplierAddress2()):'', $katao_supplier_invoice->getSupplierZip()?sprintf("%s ", $katao_supplier_invoice->getSupplierZip()):'', $katao_supplier_invoice->getSupplierCity())));
		//$this->addReglement("Payée");
		//$this->addEcheance($katao_order->getCreatedAt('d/m/Y'));
		$this->addNumTVA(wpConfig::getTvaNumber());
		$reference = wpConfig::getAdditionalCurrencyName() . ' utilisés : ' . $katao_supplier_invoice->getUsedSolTotal();
		if ('' != $comment = $katao_supplier_invoice->getComment()) {
			$reference .= " - Observations : " . $comment;
		}
		$this->addReference($reference);
		$cols = array("REFERENCE" => 23,
            "DESIGNATION" => 78,
            "QUANTITE" => 22,
            "P.U. TTC" => 26,
            "MONTANT TTC" => 30,
            "TVA" => 11);

		$this->addCols($cols);
		$cols = array("REFERENCE" => "L",
            "DESIGNATION" => "L",
            "QUANTITE" => "C",
            "P.U. TTC" => "R",
            "MONTANT TTC" => "R",
            "TVA" => "C");
		$this->addLineFormat($cols);
		$this->addLineFormat($cols);
		return $page;
	}

}
?>