<?php

class TRecDossier extends TObjetStd {
	function __construct() {
		parent::set_table(MAIN_DB_PREFIX.'rec_dossier');
		parent::add_champs('entity,fk_soc,fk_user,fk_procedure,fk_etape','type=entier;index');
		parent::add_champs('ref,statut,commentaire','type=chaine;index');
		parent::add_champs('date_last_etape,date_start,date_end','type=date;');
		parent::start();
		parent::_init_vars();

		$this->setChild('TRecDossierFacture', 'fk_dossier');
		$this->setChild('TRecEtapeHistory', 'fk_dossier');



		$this->TStatut = array(
			'DRAFT' => 'Brouillon'
			,'OPEN'=>'En cours'
			,'CLOSED' => 'Fermé'
		);

		require_once("etape.class.php");

		$this->etape = new TRecEtape;
		$this->statut = 'OPEN';
		require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
	}

	function getNomUrl() {
		return img_picto ( '', 'object_dir' ) . '<a href="'.dol_buildpath('/recouvrement/dossier.php?id='.$this->rowid, 1).'">&nbsp;'.$this->ref.'</a>';
	}

	function getPath(){
		global $conf;
		return $conf->recouvrement->multidir_output[$this->entity].'/'.dol_sanitizeFileName($this->ref);
	}
	
	function save(&$db) {

		foreach($this->TRecDossierFacture as $rdf){
			if($rdf->facture->paye == 1){
				 $rdf->setPaye($db);
				 if($this->getFactureUnpayed() == 0){
				 	$this->date_end = dol_now();
				 	$this->statut = "CLOSED";
				 }
			}
		}

		parent::save($db);

		if(empty($this->ref)) {
			$this->ref = 'REC'.date('ym').'-'.sprintf("%04d", $this->getId());
			parent::save($db);
		}


	}

	function addFacture($idFacture,$filepath='') {
		if(!$this->existeFactureDansDossier($idFacture)) {
			$iLien = $this->addChild($db, 'TRecDossierFacture');
			$this->TRecDossierFacture[$iLien]->fk_facture = (int)$idFacture;
			$this->TRecDossierFacture[$iLien]->filepath = $filepath;
		}
	}
	
	function existeFactureDansDossier($fk_facture) {
		
		if(!empty($this->TRecDossierFacture)) {
			foreach($this->TRecDossierFacture as &$rec_dossier_facture) {
				if($rec_dossier_facture->fk_facture == $fk_facture) return true;
			}
		}
		
		return false;
		
	}

	function delFacture($idFacture) {

		foreach($this->TRecDossierFacture as &$link) {

			if($link->fk_facture == $idFacture)$link->to_delete = true;

		}

	}

	function load(&$db,$idDossier, $loadChild=true){

		$this->withChild = $loadChild;

		$res = parent::load($db,$idDossier);
		$this->etape->load($db,$this->fk_etape);
		return $res;
	}
	function fetch($idDossier) {

		$PDOdb = new TPDOdb;
		return $this->load($PDOdb, $idDossier);

	}
	function getDelaiProchaineEtape(&$PDOdb) {
		$sql = 'SELECT e.rowid, e.name, e.delais,e.rang
			FROM '.MAIN_DB_PREFIX.'rec_etape as e INNER JOIN '.MAIN_DB_PREFIX.'rec_dossier as d ON( e.fk_procedure = d.fk_procedure )
			WHERE d.rowid = '.$this->getId().' AND e.rang>'.$this->etape->rang.'
			ORDER BY e.rang ASC
			LIMIT 1';

		$PDOdb->Execute($sql);

		if($obj = $PDOdb->Get_line())	return $obj;
		else return false;

	}
	function getMontant($currency = "EUR", $fk_facture='') {
		global $conf;
		$TFacture=array();

		$montant = 0;
		foreach($this->TRecDossierFacture as &$rdf) {
			$montant += $rdf->facture->total_ttc;
			if(!empty($fk_facture) && $rdf->facture->id == $fk_facture) {
				$montant = $rdf->facture->total_ttc;break;
			}
		}
		return number_format(round($montant,2),2,',',' ').' '.$currency;
	}
	function getResteAPayer($currency = "EUR", $fk_facture='', $no_format=false) {
	    global $conf;
	    $TFacture=array();

	    $montant = 0;
	    foreach($this->TRecDossierFacture as &$rdf) {

	        $dejaPaye = $rdf->facture->getSommePaiement();
	        $dejaPaye+= $rdf->facture->getSumDepositsUsed();
	        $dejaPaye+= $rdf->facture->getSumCreditNotesUsed();

	        $montant += $rdf->facture->total_ttc - $dejaPaye;
	        if(!empty($fk_facture) && $rdf->facture->id == $fk_facture) {
	            return $rdf->facture->total_ttc - $dejaPaye;
	        }
	    }
		
		if (!$no_format) return number_format(round($montant,2),2,',',' ').' '.$currency;
		else return $montant;
	}

	//Execute l'action correspondant à l'étape en cours du dossier
	function doAction(&$user, &$PDOdb)
	{
		$this->date_last_etape = time();
		$fk_commaction = 0;

		switch($this->etape->fk_action)
		{
			case 'mail':

				$mailEnvoiOk = $this->doActionMail($user);

				break;
			case 'doc':
				$this->doActionDoc();

				break;
			case 'externaliser':
				$this->doActionExternaliser();
				$fk_commaction = $this->doActionEvenement($user);

				break;
			case 'evenement':
				$fk_commaction = $this->doActionEvenement($user);

				break;
			case 'penalty':
				
				$this->doActionPenalty($user);
				
				break;
		}
	}

	/**
	 * Création d'une facture de pénalité
	 * 
	 * @global type $db
	 * @global type $langs
	 * @global type $conf
	 * @param type $user
	 * @return int
	 */
	private function doActionPenalty(&$user)
	{
		global $db,$langs,$conf;

		require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
		require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
		require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
		require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';
		
		$client = new Societe($db);
		if ($client->fetch($this->fk_soc) <= 0)
		{
			$this->errors[] = $langs->trans('recouvrement_error_fetch_client', $this->ref, $this->fk_soc);
			return -1;
		}
		
		$service = new Product($db);
		if ($service->fetch($this->etape->fk_service) <= 0)
		{
			$this->errors[] = $langs->trans('recouvrement_error_fetch_service_penalite', $this->ref, $this->etape->fk_service);
			return -2;
		}

		$facture = new Facture($db);

		$facture->date = dol_now();
		$facture->socid = $client->id;
		$facture->cond_reglement_id = $client->cond_reglement_id;
		$facture->mode_reglement_id = $client->mode_reglement_id;

		if ($facture->create($user) <= 0)
		{
			$this->errors[] = $langs->trans('recouvrement_error_create_facture_penalite', $this->ref);
			return -3;
		}
		
		if (!empty($conf->global->RECOUVREMENT_USE_ETAPE_DESC_AS_PUBLIC_NOTE_ON_PENALTY_INVOICE))
		{
			$desc = $this->etape->description;
			if (strpos($this->etape->description, '__FACTURE_REF_LIST__') !== false)
			{
				$TRef = array();
				foreach ($this->TRecDossierFacture as &$recDossierFacture)
				{
					if ($this->getResteAPayer($conf->currency, $recDossierFacture->fk_facture) > 0)
					{
						$TRef[] = $recDossierFacture->facture->ref;
					}
				}
				
				$desc = str_replace('__FACTURE_REF_LIST__', implode(', ', $TRef), $desc);
			}
			
			$facture->update_note($desc, '_public');
		}

		// TODO ->addline
		if ($facture->addline(!empty($service->description)?$service->description:$service->desc, $service->price, 1, $service->tva_tx, $service->localtax1_tx, $service->localtax2_tx, $service->id, 0, '', '', 0, 0, '', 'HT', 0, $service->type) <= 0)
		{
			$this->errors[] = $langs->trans('recouvrement_error_addline_facture_penalite', $this->ref);
			$facture->delete($user);
			return -4;
		}
		
		// @INFO si on ne valide pas la facture alors il faudra ajouter du code sur le trigger BILL_VALIDATE pour mettre à jour le champs "filepath" de "llx_rec_dossier_facture" car la relance par mail utilise l'attribut
		$facture->validate($user);
		
		// PDF
		$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
		$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
		$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
		
		// Define output language
		$outputlangs = $langs;
		$newlang = '';
		if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
		if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = !empty($facture->client->default_lang) ? $facture->client->default_lang : $facture->thirdparty->default_lang;
		if (! empty($newlang)) {
			$outputlangs = new Translate("", $conf);
			$outputlangs->setDefaultLang($newlang);
		}
		$model=$facture->modelpdf;
		$facture->fetch($facture->id); // Reload to get new records

		$filpath = '';
		$result = $facture->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
		if ($result < 0)
		{
			$this->errors[] = $facture->error;
//			return; // Pas de return, je procède malgrés tout à la liaison entre la facture et le dossier
		}
		else
		{
			$filedir = $conf->facture->multidir_output[$conf->entity] . '/' . dol_sanitizeFileName($facture->ref);
			$recent = dol_most_recent_file($filedir,'(\.pdf)$');
			$filpath = $recent['fullname'];
		}
		
		$PDOdb = new TPDOdb;
		
		$link = new TRecDossierFacture;
		$link->fk_dossier = $this->getId();
		$link->fk_facture = $facture->id;
		$link->filepath = $filpath;
		$link->save($PDOdb);
		
		return 1;
	}
	
	function doActionEvenement(&$user, $moreTitle='', $moreBody='',$TContact=array())
	{
		global $db, $user, $conf;

		dol_include_once('/comm/action/class/actioncomm.class.php');
		dol_include_once('/contact/class/contact.class.php');

		$TabFactures = $this->doA_get_facture();

		/*echo '<pre>';
		print_r($TabFactures);
		echo '</pre>';*/
		$str = '';
		foreach($TabFactures as $f) {
			$str .= ' '.$f->ref;
			$soc_id = $f->socid;
		}

		$sql = 'SELECT u.rowid ';
		$sql .= 'FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'societe_commerciaux as sc, '.MAIN_DB_PREFIX.'user as u ';
		$sql .= 'WHERE s.rowid = sc.fk_soc ';
		$sql .= 'AND u.rowid = sc.fk_user ';
		$sql .= 'AND s.rowid = '.$soc_id;

		$PDOdb = new TPDOdb;

		$PDOdb->Execute($sql);
		$PDOdb->Get_line();

		$event = new ActionComm($db);
		$event->id = 1;
		$event->fk_element = $this->id;
		$event->elementtype = 'recouvrement_TRecDossier';

		if($this->etape->fk_action == "evenement"){
			 //type = événement divers
			$event->label = $this->etape->name;
			$event->note = $this->etape->description.' Dossier de recouvrement '.$this->ref.' concernant les factures suivantes : '.$str;
		}
		else{
			$event->label = $this->etape->description;
			$event->note = 'Dossier de recouvrement '.$this->ref.' concernant les factures suivantes : '.$str;
		}

		if(!empty($moreTitle)) $event->label.=' '.$moreTitle;
		if(!empty($moreBody)) $event->note.="\n\n\n".$moreBody;

		$event->type_id = 1;
		$event->datep = dol_now();
		$event->type_code = 1;
		$event->type = 1;
		$event->location = '';
		$default_percent = $conf->global->RECOUVREMENT_DEFAULT_AGENDA_EVENT_PERCENTAGE;
		$event->percentage = ($default_percent !== '' && $default_percent !== null) ? $conf->global->RECOUVREMENT_DEFAULT_AGENDA_EVENT_PERCENTAGE : 100;

		$soc = new Societe($db);
		$soc->fetch($this->fk_soc);

		$event->socid = $soc->id;
		$event->societe = $soc;

		if (!empty($TContact[0]['id'])) {
			$contact = new Contact($db);
			$contact->fetch($TContact[0]['id']);

			$event->contact = $contact;
		}

		$event->type_id=50;

		$usertodo=new User($db);
		$usertodo->fetch($user->id);
		//$usertodo->fetch($PDOdb->Get_field('rowid'));
		$event->usertodo = $usertodo;

		// Pas sûr que l'attribut existe avant 3.7 du coup je teste avec la fonction property_exists
		if(property_exists('ActionComm', 'userownerid')) $event->userownerid = $user->id;

		$event_id = $event->add($user);

		if($event_id>0)
		{
			$PDOdb=new TPDOdb;
			$h=new TRecEtapeHistory;
			$h->fk_dossier = $this->getId();
			$h->fk_etape = $this->etape->getId();
			$h->fk_commaction=$event_id;
			$h->date_etape = time();
			$h->save($PDOdb);

		}


		return $event_id;
	}

	//Envoi un mail au tiers associé au dossier
	private function doActionMail(&$user){
		global $conf, $langs, $db;
		//On récupère les contact associé aux factures
		$TContact = $this->doA_get_contact();

		$mailEnvoiOk = false;

		$soc = new Societe($db);
		$soc->fetch($this->fk_soc);

		/*print_r($TContact);
		exit;*/
		
		if(!empty($TContact[0]['email'])){ // Avant : "if(!empty($TContact))" ne convenait pas car $TContact contient toujours "Array ( [0] => Array ( [email] => ) )", on ne passait donc jamais dans l'affichage de l'erreur

			$mailEnvoiOk = true;

			//Construction du tableau d'email destinataire
			$TEmail = array();
			foreach($TContact as $contact) $TEmail[] = $contact['email'];

			$TEmail=array_unique($TEmail);
			$emailTo = implode(',', $TEmail);
			$emailFrom = ($conf->global->RECOUVREMENT_MAIL_FROM ? $conf->global->RECOUVREMENT_MAIL_FROM : $user->lastname.' '.$user->firstname.' <'.$user->email.'>');

			list($dummy, $contact1) = each($TContact);

			//On charge toutes les factures
			$TFacture = $this->doA_get_facture();

			$TBS=new TTemplateTBS();

            $ref_factures='';
			// Construction du tableau de factures avec leur montant
			$total_paiements = 0;
			foreach($TFacture as $fact) {
				$somme_paiements_fact = $fact->getSommePaiement();
				$somme_paiements_fact+= $fact->getSumCreditNotesUsed();
				$somme_paiements_fact+= $fact->getSumDepositsUsed();
				$total_paiements += $somme_paiements_fact;

				$total_ttc = price($fact->total_ttc, 0, '', 1, -1, -1, $conf->global->MAIN_MONNAIE);
				$reste_a_payer = price(price2num($this->getMontant("", $fact->id))-$somme_paiements_fact, 0, '', 1, -1, -1, $conf->global->MAIN_MONNAIE);
				$TFact[] = array(
					"ref" => $fact->ref
					, "total_ttc" => $total_ttc
					, "date"=>date("d/m/Y", $fact->date)
					, "reste_a_payer"=>$reste_a_payer
				);

                if(!empty($ref_factures)) $ref_factures.=', ';
                $ref_factures.=  $fact->ref;
			}

			// Construction du tableau de factures avec leur montant (version html)
			$TFacturesHTML = $TBS->render(dol_buildpath('/recouvrement/tpl/mail.tpl.php')
				,array(
					'facture'=>$TFact
				)/*
				,array(
					'total_ttc_dossier'=>price(price2num($this->getMontant(''))-$total_paiements, 0, '', 1, -1, -1, $conf->global->MAIN_MONNAIE)
				)*/
			);

			//echo $tabFact;exit;
			$body = $TBS->render(nl2br($this->etape->body_mail),array(
				//'facture'=>$TFacture

			),array(
				'contact'=>$contact1
				,'ref_factures'=>$ref_factures
				,'factures'=>$TFacturesHTML
				,'montant_total'=>$this->getMontant()
				,'total_ttc_restant'=>price(price2num($this->getMontant(''))-$total_paiements, 0, '', 1, -1, -1, $conf->global->MAIN_MONNAIE)
				,'recouvrement'=>array(
					'montant'=>$this->getMontant()
				)
			));

			//echo DOL_DATA_ROOT."/facture/"."";exit;
			/*echo "de : ".$emailFrom.", à : ".$emailTo."<br />".$body;
			exit;*/

			$titre_mail = $TBS->render($this->etape->titre_mail,array(
                //'facture'=>$TFacture

            ),array(
                'contact'=>$contact1
                ,'ref_factures'=>$ref_factures
                ,'factures'=>$TFacturesHTML
                ,'montant_total'=>$this->getMontant()
                ,'recouvrement'=>array(
                    'montant'=>$this->getMontant()
                )
            ));

			$rep=new TReponseMail($emailFrom, $emailTo, $titre_mail, $body);
			$rep->emailtoBcc = $this->etape->bcc_mail;

			// Ajout de la pièce jointe
			/*foreach($TFacture as $fact) {
				if(is_file(DOL_DATA_ROOT."/facture/".$fact->ref."/".$fact->ref.".pdf")) {
					$rep->add_piece_jointe($fact->ref.".pdf", DOL_DATA_ROOT."/facture/".$fact->ref."/".$fact->ref.".pdf");
				}
			}*/

			if(!empty($this->TRecDossierFacture)) {
				foreach($this->TRecDossierFacture as $lFacture) {

					if(empty($lFacture->filepath)) {
						if(empty($PDOdb))$PDOdb=new TPDOdb;

						$lFacture->save($PDOdb);
					}

					if(is_file($lFacture->filepath)) {
						$rep->add_piece_jointe(basename($lFacture->filepath), $lFacture->filepath);
					}
				}


			}
			

			$rep->send(true);

			$fk_commaction = $this->doActionEvenement($user, $langs->trans('RecouvrementMailTo',$titre_mail,$emailTo,$this->ref), $body,$TContact);
	/*
			if($fk_commaction>0) { // à factoriser
				$PDOdb=new TPDOdb; // TODO parameters
				$h=new TRecEtapeHistory;
				$h->fk_dossier = $this->getId();
				$h->fk_etape = $this->etape->getId();
				$h->fk_commaction=$fk_commaction;
				$h->date_etape = time();
				$h->save($PDOdb);

			}
		*/
		}
		else{
			$mess = $langs->trans("ErrorNoEmailAdress");
			setEventMessage($mess." '".$soc->name."'",'errors');
		}

		return $mailEnvoiOk;

	}


	//Génère un document
	private function doActionDoc(){
		//echo DOL_DATA_ROOT; exit;

		global $db, $user, $conf,$langs, $mysoc;

		$TContact = $this->doA_get_contact();
		$TFacture = $this->doA_get_facture();


		$soc = new Societe($db);
		$soc->fetch($TFacture[0]->socid);

		/*echo "<pre>";
		print_r($TFacture);
		echo "</pre>";
		exit;*/

		/*echo '<pre>';
		print_r(DOL_DATA_ROOT.'/recouvrement/file/'.$this->etape->tpl_doc);
		echo '</pre>'; exit;*/

		list($dummy, $contact1) = each($TContact);

		$TBS=new TTemplateTBS();

		$dir = $this->getPath().'/';

		/*echo '<pre>';
		print_r($TFacture);
		echo '</pre>';
		exit;*/
		
		if (! file_exists($dir))
		{
			if (dol_mkdir($dir) < 0)
			{
				$langs->load('main');
				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
			}
		}

		//echo $dir.$this->etape->tpl_doc;exit;
		$TFact[] = array();
		$date_facturation='';
		$factures='';
		$total_paiements = 0;

		foreach($TFacture as $fact) {
			
			// Pour document plus détaillés utilisation de liste par tableau
			$somme_paiements_fact = $fact->getSommePaiement();
			$somme_paiements_fact+= $fact->getSumCreditNotesUsed();
			$somme_paiements_fact+= $fact->getSumDepositsUsed();
			$total_paiements += $somme_paiements_fact;
			
			$total_ttc = price($fact->total_ttc, 0, '', 1, -1, -1, $conf->global->MAIN_MONNAIE);
			$reste_a_payer = price(price2num($this->getMontant("", $fact->id))-$somme_paiements_fact, 0, '', 1, -1, -1); //, $conf->global->MAIN_MONNAIE

			// TODO : add this array to tbs block
			$TFact[] = array( 
					"ref" => $fact->ref
					, "total_ttc" => $total_ttc
					, "date"=>date("d/m/Y", $fact->date)
					, "reste_a_payer"=>$reste_a_payer
			);
			
			// Pour une utilisation plus standard
			$factures.= '- '.$fact->ref."\n"; //.' du '.$f->date_creation;
			$date_facturation.= date("d/m/Y", $fact->date)."\n";
			$factures_reste_a_payer.= $reste_a_payer."\n"; 
			
		}
		
		if (!defined('OPENTBS_ALREADY_UTF8')) define('OPENTBS_ALREADY_UTF8', 'already_utf8');
		//var_dump($contact1);exit;
		
		$renderDocFile = $conf->recouvrement->multidir_output[$conf->entity].'/'.$this->etape->tpl_doc;
		if( !file_exists($renderDocFile) ){
		    // fallback with old place
		    $renderDocFile = DOL_DATA_ROOT.'/recouvrement/'.$this->etape->tpl_doc;
		}
		
		
		$body = $TBS->render( $renderDocFile ,array(
				'facture'=>$TFacture

			),array(
				//'contact'=>empty($contact1->name)?"coucou":"salut"
				'nom'=>$conf->global->MAIN_INFO_SOCIETE_NOM
				,'address'=>$conf->global->MAIN_INFO_SOCIETE_ADDRESS
				,'address2'=>$conf->global->MAIN_INFO_SOCIETE_ZIP
				,'tel'=>$conf->global->MAIN_INFO_SOCIETE_TEL
				,'email'=>$conf->global->MAIN_INFO_SOCIETE_MAIL
				,'nomSoc'=>$soc->name
				,'addressSoc1'=>$soc->address
				,'addressSoc2'=>$soc->zip.' '.$soc->town
				,"telSoc"=>$soc->tel
				,'emailSoc'=>$contact1['email']
				,"dateDuJour"=>date("d/m/Y")
				,'ville'=>$conf->global->MAIN_INFO_SOCIETE_TOWN
					//,"fax"=>"fax !!!"
				,'fac'=>$factures // vue en liste
				,'fac_date'=>$date_facturation // vue en liste
				,'fac_reste_a_payer' => $factures_reste_a_payer // vue en liste
				,'total_ttc_restant'=>$this->getResteAPayer('')
				,'montant'=>$this->getMontant('')
                ,'contact'=>$contact1
				,'societe' => $soc
				,'mysoc' => $mysoc
				,'numDossier' => $this->ref
			),
			array()
			,array(
				'convertToPDF' => true
				,'outFile'=>$dir.$this->etape->tpl_doc
				,'charset' => OPENTBS_ALREADY_UTF8
			)
		);

		$fk_commaction = $this->doActionEvenement($user,$langs->trans('RecouvrementDocGen', $this->ref),'',array());

	}

	//Génère un fichier zip contenant l'ensemble des documents du dossier
	private function doActionExternaliser(){
		global $langs,$user,$db;

		if (defined('ODTPHP_PATHTOPCLZIP'))
        {

            include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';

			if(file_exists($this->getPath().'/dossier.zip'))
			{
			    unlink($this->getPath().'/dossier.zip');
			}

			$archive = new PclZip($this->getPath().'/dossier.zip');

			$TFile = dol_dir_list( $this->getPath().'/');

			/*echo "<pre>";
			print_r($TFile);
			echo "</pre>";
			exit;*/

			$i = 0;

			foreach($TFile as $f) {
				if(is_file($f['fullname'])) {
					$i++;
				}
			}

			if($i==0){
				setEventMessage($langs->trans('NoFileInDirectory'),'warnings');
				return;
			}

			$inputfile = array();
			foreach($TFile as $file) {
				if($inputfile != 'dossier.zip') {
					$inputfile[] = $file['fullname'];
				}
			}
			$archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, $this->getPath().'/');
        }
		 else {

			print "ERREUR : Librairie Zip non trouvée";
		 }

		 $fk_commaction = $this->doActionEvenement($user,$langs->trans('RecouvrementTOExterne', $this->ref));
	}

	private function doA_get_facture() {

		$TFacture=array();

		foreach($this->TRecDossierFacture as &$rdf) {
			$TFacture[] = $rdf->facture;
		}

		return $TFacture;
	}

	private function doA_get_contact() {

		$Tab=array();
		$TEmail=array();

		foreach($this->TRecDossierFacture as &$rdf) {
			/*echo '<pre>';
			print_r($rdf);
			echo '</pre>';*/
			$TContact = $rdf->getContact();

			if(!empty($TContact)){
				//print_r($TContact);
				foreach ($TContact as $type => $contact) {
					if($type=='BILLING' && !in_array($email, $TEmail)) {
						$Tab[]=$contact;
					}
				}
			}
		}

		return $Tab;

	}

	function getFactureUnpayed(){
		$i = 0;
		foreach ($this->TRecDossierFacture as $rdf) {
			if($rdf->facture->paye == 0)
				$i++;
		}

		return $i;
	}
	
	public static function getTheMostUnpayedDossierByClient($limit=5)
	{
		global $db;
		
		$TRestToPay = array();
		
		// Get total des factures par client et par dossier
		$sql = 'SELECT d.fk_soc, d.rowid, SUM(f.total_ttc) as total_facture';
		$sql.= ' FROM '.MAIN_DB_PREFIX.'rec_dossier d';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'rec_dossier_facture df ON (d.rowid = df.fk_dossier)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (df.fk_facture = f.rowid)';
		$sql.= ' GROUP BY d.fk_soc, d.rowid';
		
		$resql = $db->query($sql);
		if ($resql)
		{
			while ($obj = $db->fetch_object($resql))
			{
				$TRestToPay[$obj->fk_soc][$obj->rowid] = $obj->total_facture;
			}
		}
		
		// Get total des paiements par client et par dossier sur les factures associées
		$sql = 'SELECT d.fk_soc, d.rowid, SUM(pf.amount) as sum_paiement';
		$sql.= ' FROM '.MAIN_DB_PREFIX.'rec_dossier d';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'rec_dossier_facture df ON (d.rowid = df.fk_dossier)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'paiement_facture pf ON (pf.fk_facture = df.fk_facture)';
		$sql.= ' GROUP BY d.fk_soc, d.rowid';
		
		$resql = $db->query($sql);
		if ($resql)
		{
			while ($obj = $db->fetch_object($resql))
			{
				$TRestToPay[$obj->fk_soc][$obj->rowid] -= $obj->sum_paiement;
			}
		}
		
		// getSumDepositsUsed()
		$sql = 'SELECT d.fk_soc, d.rowid, SUM(rc.amount_ttc) as sum_credit_not_used';
		$sql.= ' FROM '.MAIN_DB_PREFIX.'rec_dossier d';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'rec_dossier_facture df ON (d.rowid = df.fk_dossier)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (df.fk_facture = f.rowid)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'societe_remise_except rc ON (f.rowid = rc.fk_facture)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'facture f2 ON (rc.fk_facture_source = f2.rowid AND f2.type = 3) ';
		$sql.= ' GROUP BY d.fk_soc, d.rowid';
		
		// getSumCreditNotesUsed()
		$sql = 'SELECT d.fk_soc, d.rowid, SUM(rc.amount_ttc) as sum_credit_not_used';
		$sql.= ' FROM '.MAIN_DB_PREFIX.'rec_dossier d';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'rec_dossier_facture df ON (d.rowid = df.fk_dossier)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (df.fk_facture = f.rowid)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'societe_remise_except rc ON (f.rowid = rc.fk_facture)';
		$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'facture f2 ON (rc.fk_facture_source = f2.rowid AND (f2.type = 2 OR f2.type = 0) ) ';
		$sql.= ' GROUP BY d.fk_soc, d.rowid';
		
		$resql = $db->query($sql);
		if ($resql)
		{
			while ($obj = $db->fetch_object($resql))
			{
				$TRestToPay[$obj->fk_soc][$obj->rowid] -= $obj->sum_credit_not_used;
			}
		}
		
		uasort($TRestToPay, array(self, 'usortMostUnpayed'));
		
		$PDOdb = new TPDOdb;
		$TDossier = array_slice($TRestToPay, 0, $limit, true);
		foreach ($TDossier as $fk_soc => &$TDossierId)
		{
			foreach ($TDossierId as $fk_dossier => &$val)
			{
				$val = new TRecDossier;
				$val->load($PDOdb, $fk_dossier);
			}
		}
		
		return $TDossier;
	}

	public static function usortMostUnpayed($a, $b)
	{
		$sum_a = array_sum($a);
		$sum_b = array_sum($b);
		if ($sum_a > $sum_b) return -1;
		else if ($sum_a < $sum_b) return 1;
		
		return 0;
	}

    public static function getCombo($fk_soc, $fk_facture, $selected = '') {
        global $langs;

        if(empty($fk_soc)) return;
        dol_include_once('/recouvrement/lib/recouvrement.lib.php');

        $PDOdb = new TPDOdb;
        $form = new TFormCore;

        $TDossier = array(-1 => $langs->trans('RecNewDossier'));

        $sql = getSqlListeDossier($fk_soc);
        $resql = $PDOdb->Execute($sql);
        if($resql) {
            $TRes = $PDOdb->Get_All();
            foreach($TRes as $res) {
                $dossierRec = new self;
                $dossierRec->load($PDOdb, $res->rowid);

                if(! $dossierRec->existeFactureDansDossier($fk_facture)) $TDossier[$dossierRec->id] = $dossierRec->ref;
            }
        }
        else {
            var_dump($PDOdb->error, $PDOdb->query);
            exit;
        }
        if(empty($selected)) {
            if(count($TDossier) == 1) $selected = -1;
            else {
                $TKey = array_keys($TDossier);
                $selected = $TKey[1];
            }
        }

        return $form->combo('', 'TDossier['.$fk_soc.']['.$fk_facture.']', $TDossier, $selected, 1, '', 'style="width: 100%;"');
    }
}

class TRecDossierFacture extends TObjetStd {
	function __construct() {
		parent::set_table(MAIN_DB_PREFIX.'rec_dossier_facture');
		parent::add_champs('fk_dossier,fk_facture,paye','type=entier;index;');
		parent::add_champs('filepath');
		parent::start();
		parent::_init_vars();

		$this->facture=null;
	}

	function load(&$db, $id, $loadChild = true) {
		$res = parent::load($db, $id);

		$this->load_facture();

		return $res;
	}

	function save(&$db) {
		//$PDOdb->debug=true;
		if(empty($this->filepath)) {
			global $conf,$user,$langs;
			dol_include_once('/core/lib/files.lib.php');
			if(empty($this->facture))$this->load_facture();
			$dir = $conf->facture->dir_output.'/'.$this->facture->ref.'/'; // FIXME [PH] : ne devrait on pas utiliser $conf->facture->multidir_output[$this->facture->entity] ?

			$recent = dol_most_recent_file($dir,'(\.pdf)$');
			$this->filepath = $recent['fullname'];

		}

		parent::save($db);
	}

	function load_facture() {
		dol_include_once('/compta/facture/class/facture.class.php');
		global $db;

		$this->facture = new Facture($db);
		$this->facture->fetch($this->fk_facture);

	}

	static function comboFile($fk_facture,$htmlname='facture_file') {
		global $conf,$db,$langs,$user;

		$o=new TRecDossierFacture;
		$o->fk_facture =$fk_facture;

		return $o->getComboFile($htmlname);

	}

	function getComboFile ($htmlname='facture_file') {
		global $conf,$db;

		dol_include_once('/core/lib/files.lib.php');

		if(empty($this->facture))$this->load_facture();
		$dir = $conf->facture->dir_output.'/'.$this->facture->ref.'/';


		if(empty($this->filepath)) {

			$recent = dol_most_recent_file($dir,'(\.pdf)$');
			//var_dump($recent);
			$this->filepath = $recent['fullname'];

		}

		$TFile = dol_dir_list($dir);

		$combo ='<select name="'.$htmlname.'">';

		foreach($TFile as $f) {

			$combo.='<option value="'.$f['fullname'].'" '.($f['fullname'] == $this->filepath ? 'selected="selected"' : '').'>'.$f['name'].'</option>';

		}

		$combo.='</select>';

		return $combo;
	}

	function setPaye(&$PDOdb){
		global $user;

		$this->paye = 1;
		$this->save($PDOdb);
	}

	function getContact() {

		global $db;

		dol_include_once('/contact/class/contact.class.php');

		if(is_null($this->facture)) $this->load_facture();

		$TRes = array();
			$TContact = $this->facture->liste_contact(-1,'external');

			if(empty($TContact)) {

				$soc=new Societe($db);
				$soc->fetch($this->facture->socid);

				$TRes['BILLING']=array(
					'email'=>$soc->email
					,'civility'=>''
					,'lastname'=>''
					,'firstname'=>''
				);
			}
			else {

				foreach($TContact as $contact) {
					$c = new Contact($db);
					$c->fetch($contact['id']);

					$TRes[$contact['code']] = array(
						'id' => $c->id,
						'civility' => $c->getCivilityLabel(),
						'firstname' => $c->firstname,
						'lastname' => $c->lastname,
						'address' => $c->address,
						'cp' => $c->zip,
						'ville' => $c->town,
						'pays' => $c->country,
						'email' => $c->email,
						'phone' => $c->phone_pro,
						'fax' => $c->fax,
						'societe' => $c->societe->nom
					);
				}
			}

		return $TRes;

	}
}
