<?php
/* Copyright (C) 2004-2012	Laurent Destailleur	<eldy@users.sourceforge.net>
 * Copyright (C) 2005-2012	Regis Houssin		<regis.houssin@capnetworks.com>
 * Copyright (C) 2008		Raphael Bertrand	<raphael.bertrand@resultic.fr>
 * Copyright (C) 2010-2012	Juanjo Menent		<jmenent@2byte.es>
 * Copyright (C) 2012      	Christophe Battarel <christophe.battarel@altairis.fr>
 * Copyright (C) 2013 ethicweb
 *
 */

/**
 *	\file       relanceTiers/core/modules/relance/doc/pdf_crabe_module.php
 */
if(file_exists(DOL_DOCUMENT_ROOT."/custom/relanceTiers"))
require_once DOL_DOCUMENT_ROOT.'/custom/relanceTiers/core/modules/relance/modules_relance.php';
else
require_once DOL_DOCUMENT_ROOT.'/relanceTiers/core/modules/relance/modules_relance.php';

require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';

require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
 
 function text_decode($text){
		return html_entity_decode($text, ENT_QUOTES, 'UTF-8');
	}

function strcoupe($str,$pos){
	if ( strlen($str)>$pos)
	{
		$str=substr($str,0,$pos);
		$pos=strrpos($str," ");
		$str=substr($str,0,$pos);
	
		return $str;
	}
	else return $str;
}
/**
 *	Class to manage PDF invoice template Crabe
 */
class pdf_crabe extends ModeleRelance
{
    var $db;
    var $name;
    var $description;
    var $type;

    var $phpmin = array(4,3,0); // Minimum version of PHP required by module
    var $version = 'dolibarr';

    var $page_largeur;
    var $page_hauteur;
    var $format;
	var $marge_gauche;
	var	$marge_droite;
	var	$marge_haute;
	var	$marge_basse;

	var $emetteur;	// Objet societe qui emet


	/**
	 *	Constructor
	 *
	 *  @param		DoliDB		$db      Database handler
	 */
	function __construct($db)
	{
		global $conf,$langs,$mysoc;


		$this->db = $db;
		$this->name = "crabe";
		$this->description = $langs->trans('PDFCrabeDescription');

		// Dimension page pour format A4
		$this->type = 'pdf';
		$formatarray=pdf_getFormat();
		$this->page_largeur = $formatarray['width'];
		$this->page_hauteur = $formatarray['height'];
		$this->format = array($this->page_largeur,$this->page_hauteur);
		$this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10;
		$this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10;
		$this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10;
		$this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;

		$this->option_logo = 1;                    // Affiche logo
		$this->option_tva = 1;                     // Gere option tva FACTURE_TVAOPTION
		$this->option_modereg = 1;                 // Affiche mode reglement
		$this->option_condreg = 1;                 // Affiche conditions reglement
		$this->option_codeproduitservice = 1;      // Affiche code produit-service
		$this->option_multilang = 1;               // Dispo en plusieurs langues
		$this->option_escompte = 1;                // Affiche si il y a eu escompte
		$this->option_credit_note = 1;             // Support credit notes
		$this->option_freetext = 1;				   // Support add of a personalised text
		$this->option_draft_watermark = 1;		   // Support add of a watermark on drafts

		$this->franchise=!$mysoc->tva_assuj;

		// Get source company
		$this->emetteur=$mysoc;
		if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // By default, if was not defined

		// Define position of columns
		$this->posxdesc=$this->marge_gauche+1;
		$this->posxtva=111;
		$this->posxup=126;
		$this->posxqty=145;
		$this->posxdiscount=162;
		$this->postotalht=174;
		if ($this->page_largeur < 210) // To work with US executive format
		{
			$this->posxtva-=20;
			$this->posxup-=20;
			$this->posxqty-=20;
			$this->posxdiscount-=20;
			$this->postotalht-=20;
		}

		$this->tva=array();
		$this->localtax1=array();
		$this->localtax2=array();
		$this->atleastoneratenotnull=0;
		$this->atleastonediscount=0;
		
	}
	
	
	function converToDoppleDecimal($var){
	if(strpos($var,".")===FALSE)return $var.".00";
	else if(strlen($var) - strpos($var,".") == 2)
	return $var."0";
	else if(strlen($var) - strpos($var,".") == 1)
	return $var."00";
	else return substr($var,0,strpos($var,'.')+3);
	
	}
	


	/**
     *  Function to build pdf onto disk
     *
     *  @param		Object		$object				Object to generate
     *  @param		Translate	$outputlangs		Lang output object
     *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
     *  @param		int			$hidedetails		Do not show line details
     *  @param		int			$hidedesc			Do not show desc
     *  @param		int			$hideref			Do not show ref
     *  @return     int         	    			1=OK, 0=KO
	 */
	function write_file($object,$outputlangs,$srctemplatepath='',$hidedetails=0,$hidedesc=0,$hideref=0)
	{
		global $user,$langs,$conf,$mysoc,$db,$hookmanager;
		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("pdfRelanceTiers@relanceTiers");
		$outputlangs->load("payment");
		$outputlangs->load("bank");
		$outputlangs->load("invoice");
		$outputlangs->load("withdrawals");
		if ($conf)
		{

			// Definition of $dir and $file
			if ($object->specimen)
			{
				$dir = DOL_DATA_ROOT."/relanceTiers/relance/";
				$file = $dir . "/SPECIMEN.pdf";
			}
			else
			{
				$objectref = dol_sanitizeFileName($object->id);
				$dir = DOL_DATA_ROOT."/relanceTiers/receipts/relance/".$object->id;
				$file = $dir . "/" . $objectref . ".pdf";
			}
			if (! file_exists($dir))
			{
				if (dol_mkdir($dir) < 0)
				{
					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
					return 0;
				}
			}

			if (file_exists($dir))
			{
				$sql= "SELECT count(amount) as nb_ligne, sum(amount) as somme, nom FROM(
    SELECT pf.amount,s.nom,p.rowid
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				inner join llx_paiement_facture pf on  pf.fk_facture=f.rowid 
				inner join llx_paiement p on pf.fk_paiement=p.rowid 
				inner join llx_c_paiement ty on ty.id=p.fk_paiement 
				WHERE s.rowid=".$object->id." 
				AND f.paye =0
			AND f.fk_statut=1
			AND f.date_lim_reglement < CURDATE()
			
UNION ALL SELECT f.total_ttc*(-1) as amount,s.nom,f.rowid
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
				AND f.paye =0
			AND f.fk_statut=1
			AND f.total_ttc>0
			AND f.date_lim_reglement < CURDATE()

UNION ALL SELECT f.total_ttc*(-1) as amount,s.nom,f.rowid
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
					AND f.paye =0
					AND f.fk_statut =1
			AND f.total_ttc < 0 
			
UNION ALL SELECT r.amount_ttc as amount,s.nom,r.rowid
				FROM `llx_societe` s 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				WHERE s.rowid=".$object->id."
				AND r.fk_facture IS NULL
				AND r.fk_facture_line IS NULL
						
UNION ALL SELECT r.amount_ttc as amount,s.nom,r.rowid
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				inner join llx_facture f2 on f2.rowid=r.fk_facture_source
				WHERE s.rowid=".$object->id."
					AND f.paye =0
					AND f.fk_statut =1
					AND f.total_ttc>0
				AND f.date_lim_reglement < CURDATE()
					AND r.fk_facture = f.rowid
					AND r.fk_facture_line IS NULL
) as a;";
				$resql=$this->db->query($sql);
				if ($resql)
				{
					$row = $this->db->fetch_row($resql);
					$nblignes = $row[0];
					$solde = $row[1];
					$cli_nom= $row[2];
				}
				
				$sql= "SELECT count(f.rowid)
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
				AND f.paye =0
			AND f.fk_statut=1
			AND f.date_lim_reglement < CURDATE();";
				$resql=$this->db->query($sql);
				if ($resql)
				{
					$row = $this->db->fetch_row($resql);
					$nb_fac = $row[0];
				}
				
				
				
				

                $pdf=pdf_getInstance($this->format);
                $default_font_size = pdf_getPDFFontSize($outputlangs);	// Must be after pdf_getInstance
				$heightforinfotot = 50;	// Height reserved to output the info and total part
		        $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
	            $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
                $pdf->SetAutoPageBreak(1,0);

                $pdf->SetFont(pdf_getPDFFont($outputlangs));

                // Set path to the background PDF File
                if (empty($conf->global->MAIN_DISABLE_FPDI) && ! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
                {
				    $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
				    $tplidx = $pdf->importPage(1);
                }

				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				$pdf->SetTitle($outputlangs->convToOutputCharset($object->id));
				$pdf->SetSubject($outputlangs->transnoentities("Invoice"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->id)." ".$outputlangs->transnoentities("Invoice"));
				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);

				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
				
				
				// New page
				$pdf->AddPage();
				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
				$pagenb++;
//avoir
				//$this->_pagehead($pdf, $object, 1, $outputlangs);
				$pdf->SetFont('','', 8);
				$pdf->MultiCell(0, 3, '');		// Set interline to 3
				$pdf->SetTextColor(0,0,0);
				if(file_exists(DOL_DATA_ROOT.'/mycompany/logos/'.$conf->global->MAIN_INFO_SOCIETE_LOGO))$pdf->Image(DOL_DATA_ROOT.'/mycompany/logos/'.$conf->global->MAIN_INFO_SOCIETE_LOGO, 10, 5);

				$tab_top = 70;
				$tab_height = 110;

				
				$this->_print_head($pdf, $cli_nom, $outputlangs);
				$this->_print_first_head_total($pdf, $nblignes, $solde, $outputlangs);

				$iniY = $tab_top + 7;
				$curY = $tab_top + 7;
				$nexY = $tab_top + 7;
				$nbDePage=$nblignes/50;   
				$nbDePage=ceil($nbDePage);
				
				$this->_print_page($pdf, $pagenb, $nbDePage);

				$diffX=Array($this->marge_gauche,$this->marge_gauche+70,$this->marge_gauche+100,$this->marge_gauche+130,$this->marge_gauche+160);
				
				// Loop on each lines
				
					$sql= "SELECT 
					title, 
					date, 
					debit, 
					credit, 
					(@csum := @csum + amount)as solde,
					fac,
					label 
					FROM(
    SELECT 
		CONCAT(\"->".text_decode($outputlangs->trans("PaiementRel"))." ( \",ty.code,\" ) : \",p.num_paiement,\"-\") as title,
		p.datec as date,
		IF(pf.amount<0,round(pf.amount*(-1),2),'' )as debit,
		IF(pf.amount>0,round(pf.amount,2),'') as credit,round(pf.amount,2) as amount,
		f.rowid,
		0 as fac,
		b.label,
		p.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				inner join llx_paiement_facture pf on  pf.fk_facture=f.rowid 
				inner join llx_paiement p on pf.fk_paiement=p.rowid 
				inner join llx_c_paiement ty on ty.id=p.fk_paiement 
				inner join llx_bank b on b.rowid=p.fk_bank 
				WHERE s.rowid=".$object->id." 
				AND f.paye =0
			AND f.fk_statut=1
			AND f.date_lim_reglement < CURDATE()
UNION ALL SELECT 
	CONCAT(\"".text_decode($outputlangs->trans("FactureRel"))." : \",f.facnumber) as title,
	f.datef as date,
	IF(f.total_ttc>0,round(f.total_ttc,2),'' )as debit,
	IF(f.total_ttc<0,round(f.total_ttc*(-1),2),'') as credit,
	round(f.total_ttc*(-1),2) as amount,
	f.rowid, 
	1 as fac,
	\"\" as label,
		f.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
				AND f.paye =0
			AND f.fk_statut=1
			AND f.total_ttc>0
			AND f.date_lim_reglement < CURDATE()
			
UNION ALL  SELECT 
CONCAT(\"".text_decode($outputlangs->trans("Avoir"))." : \",f.facnumber) as title,
f.datef as date,
IF(f.total_ttc>0,round(f.total_ttc,2),'' )as debit,
IF(f.total_ttc<0,round(f.total_ttc*(-1),2),'') as credit,round(f.total_ttc*(-1),2) as amount,
f.rowid, 
1 as fac,
\"\" as label,
		f.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				WHERE s.rowid=".$object->id."
					AND f.paye =0
					AND f.fk_statut =1
			AND f.total_ttc < 0 
UNION ALL  SELECT 
CONCAT(\"".text_decode($outputlangs->trans("Remise"))." : \",r.description) as title,
r.datec as date,
IF(r.amount_ttc<0,round(r.amount_ttc*(-1),2),'' )as debit,
IF(r.amount_ttc>0,round(r.amount_ttc,2),'') as credit,
round(r.amount_ttc,2) as amount,
999999 as rowid, 
3 as fac,
\"\" as label,
		r.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				WHERE s.rowid=".$object->id."
				AND r.fk_facture IS NULL
				AND r.fk_facture_line IS NULL
				AND r.fk_facture_source IS NULL
   
UNION ALL  SELECT 
CONCAT(\"".text_decode($outputlangs->trans("RemiseAvoir"))." : \",f2.facnumber) as title,
r.datec as date,
IF(r.amount_ttc<0,round(r.amount_ttc*(-1),2),'' )as debit,
IF(r.amount_ttc>0,round(r.amount_ttc,2),'') as credit,
round(r.amount_ttc,2) as amount,
999998 as rowid, 
3 as fac,
\"\" as label,
		r.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				inner join llx_facture f2 on f2.rowid=r.fk_facture_source
				WHERE s.rowid=".$object->id."
				AND r.fk_facture IS NULL
				AND r.fk_facture_line IS NULL
   
UNION ALL  SELECT 
CONCAT(\"->".text_decode($outputlangs->trans("UtilisationAvoir"))." : \",f2.facnumber) as title,
f.datef as date,
IF(r.amount_ttc<0,round(r.amount_ttc*(-1),2),'' )as debit,
IF(r.amount_ttc>0,round(r.amount_ttc,2),'') as credit,
round(r.amount_ttc,2) as amount,
f.rowid as rowid, 
3 as fac,
\"\" as label,
		r.rowid as coupe
				FROM `llx_societe` s 
				inner join llx_facture f on f.fk_soc=s.rowid 
				inner join llx_societe_remise_except r on s.rowid=r.fk_soc
				inner join llx_facture f2 on f2.rowid=r.fk_facture_source
				WHERE s.rowid=".$object->id."
					AND f.paye =0
					AND f.fk_statut =1
					AND f.total_ttc>0
				AND f.date_lim_reglement < CURDATE()
					AND r.fk_facture = f.rowid
					AND r.fk_facture_line IS NULL
) as aa 
JOIN (SELECT @csum := 0) cc
				
order by rowid,date,amount;";
				$resql=$this->db->query($sql);
				if ($resql)
				{
					$num = $this->db->num_rows($resql);
					if ($num)
					{
						$i = 0;
						$saut_page=0;
						while ($i < $num)
						{
							if($saut_page==50){
							
							// Show square
								$this->_tableau($pdf, $tab_top, 200, 0, $outputlangs, 0, 0);
								$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;




								// Pied de page
								//$this->_pagefoot($pdf,$object,$outputlangs);
								if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
				
				
							// New page
								$saut_page=0;
								$pdf->AddPage();
								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
								$pagenb++;
								//avoir
								//$this->_pagehead($pdf, $object, 1, $outputlangs);
								$pdf->SetFont('','', 8);
								$pdf->MultiCell(0, 3, '');		// Set interline to 3
								$pdf->SetTextColor(0,0,0);

				if(file_exists(DOL_DATA_ROOT.'/mycompany/logos/'.$conf->global->MAIN_INFO_SOCIETE_LOGO))$pdf->Image(DOL_DATA_ROOT.'/mycompany/logos/'.$conf->global->MAIN_INFO_SOCIETE_LOGO, 10, 5);
								$tab_top = 70;
								$tab_height = 110;
								

								$iniY = $tab_top + 7;
								$curY = $tab_top + 7;
								$nexY = $tab_top + 7;
								$this->_print_page($pdf, $pagenb, $nbDePage);
								
								$this->_print_head($pdf, $cli_nom, $outputlangs);
								$this->_print_first_head_total($pdf, $nb_fac, $solde, $outputlangs);
							}
							
							if($saut_page%2==0)
								$pdf->SetFillColor(200,200,200);
								
							$row = $this->db->fetch_row($resql);
							
							
								$type=$row[6];
								$type=str_replace(array("(",")"),array("",""),$type);
								$type=text_decode($outputlangs->trans($type));
								$descr=strcoupe($row[0].$type,50);	
								
														
							$pdf->SetXY($diffX[0], $curY);
							$pdf->MultiCell(70,2, $descr,'','L',true);
							
							$pdf->SetXY($diffX[1], $curY);
							$date=new DateTime($row[1]);
							$pdf->MultiCell(30,2, $date->format('d/m/Y'),'','C',true);
							
							$pdf->SetXY($diffX[2], $curY);
							if($row[2])$res2=$this->converToDoppleDecimal($row[2]).' '.$conf->currency.'';else $res2='';
							$pdf->MultiCell(30,2, $res2,'','C',true);
							
							$pdf->SetXY($diffX[3], $curY);
							if($row[3])$res3=$this->converToDoppleDecimal($row[3]).' '.$conf->currency.'';else $res3='';
							$pdf->MultiCell(30,2, $res3,'','C',true);
							
							$pdf->SetXY($diffX[4], $curY);
							$res4=$this->converToDoppleDecimal($row[4]).' '.$conf->currency.'';
							$pdf->MultiCell(30,2, $res4,'','R',true);
														
							$iniY += 4;
							$curY += 4;
							$nexY += 4;
							
							$i++;$saut_page++;
							
							$pdf->SetFillColor(255,255,255);
							
						}
					}
					
							$pdf->SetXY($diffX[3], $curY);
							$pdf->MultiCell(30,2, text_decode($outputlangs->trans("SoldeActu")),'','C',true);
							
							$pdf->SetXY($diffX[4], $curY);
							$solde=$this->converToDoppleDecimal($solde).' '.$conf->currency.'';
							$pdf->MultiCell(30,2, $solde,'','R',true);
					
					
				}

				// Show square
					$this->_tableau($pdf, $tab_top, 200, 0, $outputlangs, 0, 0);
					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;




				// Pied de page
				//$this->_pagefoot($pdf,$object,$outputlangs);
				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');

				// Add pdfgeneration hook
				if (! is_object($hookmanager))
				{
					include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
					$hookmanager=new HookManager($this->db);
				}
				$hookmanager->initHooks(array('pdfgeneration'));
				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
				global $action;
				$reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks

				if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));

				return 1;   // Pas d'erreur
			}
			else
			{
				$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}
		else
		{
			$this->error=$langs->trans("ErrorConstantNotDefined","FAC_OUTPUTDIR");
			return 0;
		}
		$this->error=$langs->trans("ErrorUnknown");
		return 0;   // Erreur par defaut
	}




	/**
	 *   Show miscellaneous information (payment mode, payment term, ...)
	 *
	 *   @param		PDF			&$pdf     		Object PDF
	 *   @param		Object		$object			Object to show
	 *   @param		int			$posy			Y
	 *   @param		Translate	$outputlangs	Langs object
	 *   @return	void
	 */
	function _tableau_info(&$pdf, $object, $posy, $outputlangs)
	{
		global $conf;

		$default_font_size = pdf_getPDFFontSize($outputlangs);

		$pdf->SetFont('','', $default_font_size - 1);


		$posxval=52;

		if ($object->type != 2)
		{

				$pdf->SetFont('','', $default_font_size - 2);
				$pdf->SetXY($posxval, $posy);

				$posy=$pdf->GetY()+2;

			
					$bankid=(empty($object->fk_bank)?$conf->global->FACTURE_RIB_NUMBER:$object->fk_bank);
					$account = new Account($this->db);
					$account->fetch($bankid);

					$curx=$this->marge_gauche;
					$cury=$posy;

					$posy=pdf_bank($pdf,$outputlangs,$curx,0,$account,0,$default_font_size);

					$posy+=2;
		}

		return $posy;
	}

function _print_page(&$pdf, $num_page, $total_page)
	{
		global $conf;

			$pdf->SetXY(160, 270);
			$pdf->MultiCell(30,1, "Page : ".$num_page." / ".$total_page,'','L');
	}

function _print_head(&$pdf,$cli_nom,$outputlangs)
	{
		global $conf;
			if (! empty($conf->global->MAIN_INFO_SOCIETE_NOM)) $socname = $conf->global->MAIN_INFO_SOCIETE_NOM;
			$pdf->SetXY(10, 10);
			$pdf->MultiCell(190,1, $conf->global->ADRESSE_RELANCE_MAIL,'','R');
			
			
			$pdf->SetXY(10, 48);
			$pdf->MultiCell(180,1, text_decode($outputlangs->trans("Client")).' '.$cli_nom,'','L');
			$pdf->SetXY(10, 48);
			$pdf->MultiCell(180,1, text_decode($outputlangs->trans("Edite")).' '.date('j/n/Y'),'','R');
	}
	
function _print_first_head_total(&$pdf, $nblignes, $solde, $outputlangs, $hidetop=0, $hidebottom=0)
	{
		global $conf;

			$pdf->SetXY(10, 53);
			$pdf->MultiCell(180,1, text_decode($outputlangs->trans("NbEcriture")).' '.$nblignes,'','L');
			$pdf->SetXY(10, 53);
			$pdf->MultiCell(180,1, text_decode($outputlangs->trans("SoldeActuel")).' '.converToDoppleDecimal($solde).' '.$conf->currency.'','','R');
			
		$this->printRect($pdf,$this->marge_gauche,45, $this->page_largeur-$this->marge_gauche-$this->marge_droite, 15, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param

	}
	/*
	/**
	 *   Show table for lines
	 *
	 *   @param		PDF			&$pdf     		Object PDF
	 *   @param		string		$tab_top		Top position of table
	 *   @param		string		$tab_height		Height of table (rectangle)
	 *   @param		int			$nexY			Y (not used)
	 *   @param		Translate	$outputlangs	Langs object
	 *   @param		int			$hidetop		1=Hide top bar of array and title, 0=Hide nothing, -1=Hide only title
	 *   @param		int			$hidebottom		Hide bottom bar of array
	 *   @return	void
	 */
	function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop=0, $hidebottom=0)
	{
		global $conf;

		// Force to disable hidetop and hidebottom
		$hidebottom=0;
		if ($hidetop) $hidetop=-1;

		$default_font_size = pdf_getPDFFontSize($outputlangs);

		// Amount in (at tab_top - 1)
		$pdf->SetTextColor(0,0,0);
		$pdf->SetFont('','', $default_font_size - 2);

		if (empty($hidetop))
		{
			$titre = $outputlangs->transnoentities("AmountInCurrency",$outputlangs->transnoentitiesnoconv("Currency".$conf->currency));
			$pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4);
			$pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);

			//$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230';
			if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',',$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
		}

		$pdf->SetDrawColor(128,128,128);
		$pdf->SetFont('','', $default_font_size - 3);

		// Output Rect
		$this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param

		if (empty($hidetop))      /// CREATION DU TABLEAU VIDE ICI
		{
			$avancee=0;
		
			$pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);	// line prend une position y en 2eme param et 4eme param
			$pdf->SetXY($this->posxdesc-1, $tab_top+1);
			$pdf->MultiCell(70,2, text_decode($outputlangs->trans("Transac")),'','C');
			$avancee+=70;
			
			$pdf->line($this->marge_gauche+$avancee, $tab_top,$this->marge_gauche+$avancee, $tab_top + $tab_height);
			$pdf->SetXY($this->marge_gauche+$avancee, $tab_top+1);
			$pdf->MultiCell(30,2, text_decode($outputlangs->trans("Date")),'','C');
			$avancee+=30;
			
		
			$pdf->line($this->marge_gauche+$avancee, $tab_top,$this->marge_gauche+$avancee, $tab_top + $tab_height);
			$pdf->SetXY($this->marge_gauche+$avancee, $tab_top+1);
			$pdf->MultiCell(30,2, text_decode($outputlangs->trans("DebitRel")),'','C');
			$avancee+=30;
			
			
			$pdf->line($this->marge_gauche+$avancee, $tab_top,$this->marge_gauche+$avancee, $tab_top + $tab_height);
			$pdf->SetXY($this->marge_gauche+$avancee, $tab_top+1);
			$pdf->MultiCell(30,2, text_decode($outputlangs->trans("CreditRel")),'','C');
			$avancee+=30;
			
			
			$pdf->line($this->marge_gauche+$avancee, $tab_top,$this->marge_gauche+$avancee, $tab_top + $tab_height);
			$pdf->SetXY($this->marge_gauche+$avancee, $tab_top+1);
			$pdf->MultiCell(30,2, text_decode($outputlangs->trans("SoldeCum")),'','C');
			$avancee+=30;
		}

	}

	/**
	 *  Show top header of page.
	 *
	 *  @param	PDF			&$pdf     		Object PDF
	 *  @param  Object		$object     	Object to show
	 *  @param  int	    	$showaddress    0=no, 1=yes
	 *  @param  Translate	$outputlangs	Object lang for output
	 *  @return	void
	 */
	function _pagehead(&$pdf, $object, $showaddress, $outputlangs)
	{
		global $conf,$langs;


		$default_font_size = pdf_getPDFFontSize($outputlangs);

		pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);

		// Show Draft Watermark
		if($object->statut==0 && (! empty($conf->global->FACTURE_DRAFT_WATERMARK)) )
        {
		      pdf_watermark($pdf,$outputlangs,$this->page_hauteur,$this->page_largeur,'mm',$conf->global->FACTURE_DRAFT_WATERMARK);
        }

		$pdf->SetTextColor(0,0,60);
		$pdf->SetFont('','B', $default_font_size + 3);

		$posy=$this->marge_haute;
        $posx=$this->page_largeur-$this->marge_droite-100;

		$pdf->SetXY($this->marge_gauche,$posy);

		// Logo
		$logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
		if ($this->emetteur->logo)
		{
			if (is_readable($logo))
			{
			    $height=pdf_getHeightForLogo($logo);
				$pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
			}
			else
			{
				$pdf->SetTextColor(200,0,0);
				$pdf->SetFont('','B',$default_font_size - 2);
				$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
				$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
			}
		}
		else
		{
			$text=$this->emetteur->name;
			$pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
		}

		$pdf->SetFont('','B', $default_font_size + 3);
		$pdf->SetXY($posx,$posy);
		$pdf->SetTextColor(0,0,60);
		$title=$outputlangs->transnoentities("Invoice");
		if ($object->type == 1) $title=$outputlangs->transnoentities("InvoiceReplacement");
		if ($object->type == 2) $title=$outputlangs->transnoentities("InvoiceAvoir");
		if ($object->type == 3) $title=$outputlangs->transnoentities("InvoiceDeposit");
		if ($object->type == 4) $title=$outputlangs->transnoentities("InvoiceProFormat");
		$pdf->MultiCell(100, 3, $title, '', 'R');

		$pdf->SetFont('','B',$default_font_size);

		$posy+=5;
		$pdf->SetXY($posx,$posy);
		$pdf->SetTextColor(0,0,60);
		$pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : " . $outputlangs->convToOutputCharset($object->ref), '', 'R');

		$posy+=1;
		$pdf->SetFont('','', $default_font_size - 2);

		if ($object->ref_client)
		{
			$posy+=4;
			$pdf->SetXY($posx,$posy);
			$pdf->SetTextColor(0,0,60);
			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : " . $outputlangs->convToOutputCharset($object->ref_client), '', 'R');
		}

		$objectidnext=$object->getIdReplacingInvoice('validated');
		if ($object->type == 0 && $objectidnext)
		{
			$objectreplacing=new Facture($this->db);
			$objectreplacing->fetch($objectidnext);

			$posy+=3;
			$pdf->SetXY($posx,$posy);
			$pdf->SetTextColor(0,0,60);
			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ReplacementByInvoice").' : '.$outputlangs->convToOutputCharset($objectreplacing->ref), '', 'R');
		}
		if ($object->type == 1)
		{
			$objectreplaced=new Facture($this->db);
			$objectreplaced->fetch($object->fk_facture_source);

			$posy+=4;
			$pdf->SetXY($posx,$posy);
			$pdf->SetTextColor(0,0,60);
			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ReplacementInvoice").' : '.$outputlangs->convToOutputCharset($objectreplaced->ref), '', 'R');
		}
		if ($object->type == 2)
		{
			$objectreplaced=new Facture($this->db);
			$objectreplaced->fetch($object->fk_facture_source);

			$posy+=3;
			$pdf->SetXY($posx,$posy);
			$pdf->SetTextColor(0,0,60);
			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("CorrectionInvoice").' : '.$outputlangs->convToOutputCharset($objectreplaced->ref), '', 'R');
		}

		$posy+=4;
		$pdf->SetXY($posx,$posy);
		$pdf->SetTextColor(0,0,60);
		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("DateInvoice")." : " . dol_print_date($object->date,"day",false,$outputlangs), '', 'R');

		if ($object->type != 2)
		{
			$posy+=3;
			$pdf->SetXY($posx,$posy);
			$pdf->SetTextColor(0,0,60);
			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("DateEcheance")." : " . dol_print_date($object->date_lim_reglement,"day",false,$outputlangs,true), '', 'R');
		}

		if ($object->client->code_client)
		{
			$posy+=3;
			$pdf->SetXY($posx,$posy);
			$pdf->SetTextColor(0,0,60);
			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->client->code_client), '', 'R');
		}

		$posy+=1;

		// Show list of linked objects
		$posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size);

		if ($showaddress)
		{
			// Sender properties
			$carac_emetteur = pdf_build_address($outputlangs,$this->emetteur);

			// Show sender
			$posy=42;
			$posx=$this->marge_gauche;
			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80;
			$hautcadre=40;

			// Show sender frame
			$pdf->SetTextColor(0,0,0);
			$pdf->SetFont('','', $default_font_size - 2);
			$pdf->SetXY($posx,$posy-5);
			$pdf->MultiCell(66,5, $outputlangs->transnoentities("BillFrom").":", 0, 'L');
			$pdf->SetXY($posx,$posy);
			$pdf->SetFillColor(230,230,230);
			$pdf->MultiCell(82, $hautcadre, "", 0, 'R', 1);
			$pdf->SetTextColor(0,0,60);

			// Show sender name
			$pdf->SetXY($posx+2,$posy+3);
			$pdf->SetFont('','B', $default_font_size);
			$pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
			$posy=$pdf->getY();

			// Show sender information
			$pdf->SetXY($posx+2,$posy);
			$pdf->SetFont('','', $default_font_size - 1);
			$pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L');



			// If BILLING contact defined on invoice, we use it
			$usecontact=false;
			$arrayidcontact=$object->getIdContact('external','BILLING');
			if (count($arrayidcontact) > 0)
			{
				$usecontact=true;
				$result=$object->fetch_contact($arrayidcontact[0]);
			}

			// Recipient name
			if (! empty($usecontact))
			{
				// On peut utiliser le nom de la societe du contact
				if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socname = $object->contact->socname;
				else $socname = $object->client->nom;
				$carac_client_name=$outputlangs->convToOutputCharset($socname);
			}
			else
			{
				$carac_client_name=$outputlangs->convToOutputCharset($object->client->nom);
			}

			$carac_client=pdf_build_address($outputlangs,$this->emetteur,$object->client,($usecontact?$object->contact:''),$usecontact,'target');

			// Show recipient
			$widthrecbox=100;
			if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
			$posy=42;
			$posx=$this->page_largeur-$this->marge_droite-$widthrecbox;
			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;

			// Show recipient frame
			$pdf->SetTextColor(0,0,0);
			$pdf->SetFont('','', $default_font_size - 2);
			$pdf->SetXY($posx+2,$posy-5);
			$pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("BillTo").":",0,'L');
			$pdf->Rect($posx, $posy, $widthrecbox, $hautcadre);

			// Show recipient name
			$pdf->SetXY($posx+2,$posy+3);
			$pdf->SetFont('','B', $default_font_size);
			$pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L');

			// Show recipient information
			$pdf->SetFont('','', $default_font_size - 1);
			$pdf->SetXY($posx+2,$posy+4+(dol_nboflines_bis($carac_client_name,50)*4));
			$pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L');
		}

		$pdf->SetTextColor(0,0,0);
	}

	/**
	 *   	Show footer of page. Need this->emetteur object
     *
	 *   	@param	PDF			&$pdf     			PDF
	 * 		@param	Object		$object				Object to show
	 *      @param	Translate	$outputlangs		Object lang for output
	 *      @param	int			$hidefreetext		1=Hide free text
	 *      @return	int								Return height of bottom margin including footer text
	 */
	function _pagefoot(&$pdf,$object,$outputlangs,$hidefreetext=0)
	{
		return pdf_pagefoot($pdf,$outputlangs,'FACTURE_FREE_TEXT',$this->emetteur,$this->marge_basse,$this->marge_gauche,$this->page_hauteur,$object,0,$hidefreetext);
	}

}

?>
