<?php

/**
 *  \brief      	Define head array for tabs of ndfp setup pages
 *  \return			Array of head
 */
function recouvrement_admin_prepare_head($idetape=0,$fk_procedure=0)
{
	global $langs, $conf, $user;
	$h = 0;
	$head = array();
	
	$head[$h][0] = dol_buildpath('/recouvrement/admin/configuration.php', 1);
	$head[$h][1] = $langs->trans("RecAdminGlobal");
	$head[$h][2] = 'configuration';
	$h++;
	
	if($fk_procedure > 0){
		$head[$h][0] = dol_buildpath('/recouvrement/admin/procedure.php?id='.$fk_procedure, 1);
		$head[$h][1] = $langs->trans("RecAdminProcedure");
		$head[$h][2] = 'procedure';
		$h++;
	}
	else{
		$head[$h][0] = dol_buildpath('/recouvrement/admin/procedure.php', 1);
		$head[$h][1] = $langs->trans("RecAdminProcedure");
		$head[$h][2] = 'procedure';
		$h++;
	}
	
	if($idetape > 0 || $fk_procedure > 0){
		$head[$h][0] = dol_buildpath('/recouvrement/admin/etape.php?id='.$idetape.'&fk_procedure='.$fk_procedure, 1);
		$head[$h][1] = $langs->trans("RecAdminEtape");
		$head[$h][2] = 'etape';
		$h++;
	}
	
	return $head;
}


function _genEtat($filepath, &$TFactureToConcat, &$societe, $without_bills = false, $template = './tpl/tpl_etat_factures.odt', $keep_all_bills = false){
	global $db,$langs,$conf,$mysoc;
	
	dol_include_once('/core/lib/pdf.lib.php');
	
	$ext = '.odt';
	if(strpos($template, 'ods') !== false) $ext = '.ods';
	if(strpos($template, 'xlsx') !== false) $ext = '.xlsx';
	$deleteSRC = false;
	$convertToPDF = false;
	//echo (int)$conf->global->RECOUVREMENT_CONVERT_TO_PDF; exit;
	if(!empty($conf->global->RECOUVREMENT_CONVERT_TO_PDF)){
		$ext = '.pdf';
		$deleteSRC = true;
		$convertToPDF = true;
	}
	
	$TBS = new TTemplateTBS();
	
	$filename = 'etat_factures_'.date('dmY');

	if(!is_dir($filepath)){
		mkdir($filepath);
	}
	
	$TFactures = array();
	
	$TFileFacture = array();
	
	foreach($TFactureToConcat as $idFact){
		$facture = new Facture($db);
		$facture->fetch($idFact);

		$socDoss=new Societe($db);
		$socDoss->fetch($facture->socid);
		
		$TContacts = $socDoss->contact_array_objects();

		$totalpaye = $facture->getSommePaiement();
		$totalcreditnotes = $facture->getSumCreditNotesUsed();
		$totaldeposits = $facture->getSumDepositsUsed();
		
		$resteapayer = price2num($facture->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
		
		$TFactures[] = array(
			'ref'=>$facture->ref
			,'soc'=>encodeForODT($socDoss->name)
			,'adresse'=>encodeForODT($socDoss->address." ".$socDoss->zip." ".$socDoss->town)
			,'proprio'=>encodeForODT($socDoss->array_options['options_proprietaire'])
			,'contact'=>encodeForODT($TContacts[0]->lastname)
			,'total_ht'=>$facture->total_ht
			,'total_ttc'=>$facture->total_ttc
			,'total_tva'=>$facture->total_tva
			,'total_ttc_restant'=>$resteapayer
		);
		
		if($facture->total_ttc - $res->total_paiment <= 0 && !$keep_all_bills) array_pop($TFactures);
		
		$file_path = $conf->facture->multidir_output[$conf->entity].'/'.$facture->ref."/".$facture->ref.$ext;
		if(file_exists($file_path))$TFileFacture[] = $file_path;
		
		$totalTTc += $facture->total_ttc;
		$totalTTcRestant += $resteapayer;
	}

	$res = $TBS->render($template
			,array(
				'factures'=>$TFactures
			)
			,array(
				'emetteur' => array(
					'nom' => encodeForODT($mysoc->name),
					'address' => encodeForODT($mysoc->address),
					'address2' => encodeForODT($mysoc->zip." ".$mysoc->town),
					'tel' => $mysoc->phone,
					'fax' => $mysoc->fax,
					'email' => $mysoc->email,
					'web' => $mysoc->url,
					'logo' => DOL_DATA_ROOT."/mycompany/logos/".$mysoc->logo
				)
				,'destinataire' => array(
					'nom' => encodeForODT($societe->name),
					'address' => encodeForODT($societe->address),
					'address2' => encodeForODT($societe->zip." ".$societe->town),
					'tel' => $societe->phone,
					'fax' => $societe->fax,
					'email' => $societe->email,
					'web' => $societe->url
				)
				,'autre' => array(
					'total_ttc'=>$totalTTc
					,'total_ttc_restant'=>$totalTTcRestant
					,'dateDuJour'=>date('d/m/Y')
				)
			)
			,array()
			,array(
				'deleteSrc'=>$deleteSRC
				,'convertToPDF' =>$convertToPDF
				,'outFile' => $filepath.$filename.($ext !== '.pdf' ? $ext : '.odt')
			)
		);

	// Concaténation des factures associées au dossier
	//$without_bills = $conf->global->RECOUVREMENT_WITHOUT_BILLS;
	if (!$without_bills && $convertToPDF) {
		$TFilePath[] = $filepath.$filename.$ext;

		$TFilePath = array_merge( $TFilePath, $TFileFacture );
		
		// Create empty PDF
		$pdf=pdf_getInstance();
		if (class_exists('TCPDF'))
		{
			$pdf->setPrintHeader(false);
			$pdf->setPrintFooter(false);
		}
		$pdf->SetFont(pdf_getPDFFont($langs));
	
		if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);
		//$pdf->SetCompression(false);

		$pagecount = concat($pdf, $TFilePath);
	
		if ($pagecount)
		{
			$pdf->Output($TFilePath[0],'F');
			if (! empty($conf->global->MAIN_UMASK))
			{
				@chmod($file, octdec($conf->global->MAIN_UMASK));
			}
		}
	}

	header('Content-type: application/'.str_replace('.', '', $ext));
	header('Content-Disposition: attachment; filename="'.$filename.$ext.'"');
	readfile($filepath.$filename.$ext);

}

function encodeForODT($string)
{
	$originalEncoding = mb_detect_encoding($string);

	if(! empty($originalEncoding))
	{
		return mb_convert_encoding($string, 'ISO-8859-1', $originalEncoding);
	}

	return mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8');
}

function concat(&$pdf,$files)
{
	foreach($files as $file)
	{
		$pagecount = $pdf->setSourceFile($file);
		for ($i = 1; $i <= $pagecount; $i++)
		{
			$tplidx = $pdf->ImportPage($i);
			$s = $pdf->getTemplatesize($tplidx);
			$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
			$pdf->useTemplate($tplidx);
		}
	}
	
	return $pagecount;
}

function getSqlListeDossier($fk_soc, $limit = '') {
    global $conf;
    if(empty($fk_soc)) return;

    $sql = 'SELECT rd.rowid, rd.ref';
    $sql.= ' FROM '.MAIN_DB_PREFIX.'rec_dossier AS rd';
    $sql.= " WHERE rd.statut != 'CLOSED'";
    if(! empty($conf->global->RECOUVREMENT_PARENT_CASE)) $sql.= ' AND rd.fk_soc=(SELECT s.parent FROM '.MAIN_DB_PREFIX.'societe as s WHERE s.rowid = '.$fk_soc.')';
    else $sql.= ' AND rd.fk_soc='.$fk_soc;
    $sql.= ' ORDER BY date_start DESC';
    if(! empty($limit)) $sql.= ' LIMIT '.$limit;

    return $sql;
}

function _attribFacture(&$ATMdb,$request){
	global $db,$user,$conf, $langs;
	//Parcours des factures transmises par le formulaire
	/*echo "<pre>";
	print_r($request);
	echo "</pre>";
	exit;*/

	if (!empty($request['TProcedure'])) 
	{
        $TDossier = GETPOST('TDossier');
		foreach($request['TProcedure'] as $idfacture=>$idprocedure){
			
			if($idprocedure == 0) { // Les factures qui n'ont aucune procédure sélectionnée ne doivent pas être ajoutées à un dossier de recouvrement !
				continue;
			} else {
				$existeProcedure++; // Si au moins une procédure est sélectionnée, on n'affiche pas le message en dessous du foreach
			}
				
			//Pour la facture en cours rechercher si un dossier de recouvrement existe pour son client associé
			$facture = new Facture($db);
			$facture->fetch($idfacture);

            $selected = -1;
            if(! empty($conf->global->RECOUVREMENT_SHOW_SELECT_FOLDER)) {
                $selected = $TDossier[$facture->socid][$facture->id];
            }
            else {
                $sql = getSqlListeDossier($facture->socid, 1);
                $ATMdb->Execute($sql);

                if($obj = $ATMdb->Get_line()) {
                    $selected = $obj->rowid;
                }
            }

            $TRecDossier = new TRecDossier;

            //si dossier existe alors on le charge
            if($selected >= 0) {
                $client=new Societe($db);
                $client->fetch($facture->socid);

				$TRecDossier->load($ATMdb, $selected);
				setEventMessage("Dossier de recouvrement déjà existant pour client ".$client->name." : ".$TRecDossier->ref);
			}
			//sinon on créé le dossier
			else{
					
				if(isset($_REQUEST['save_procedure_without_step'])){
					$id_etape=0;
				}	
				else {
					$p=new TRecProcedure;
					$p->load($ATMdb, $idprocedure);	
					
					$etape1 = $p->getFirstEtape();
					
					$id_etape = $etape1->getId();
				}
				
				if($conf->global->RECOUVREMENT_PARENT_CASE){
					//Récupération du tier parent
					$societe = new Societe($db);
					$societe->fetch($facture->socid);
					
					if($societe->parent){
						$facture->socid = $societe->parent;
					}
				}
				
				$TRecDossier->entity = $conf->entity;
				$TRecDossier->fk_soc = $facture->socid;
				$TRecDossier->fk_user = $user->id;
				$TRecDossier->fk_procedure = $idprocedure;
				$TRecDossier->fk_etape = $id_etape; 
				$TRecDossier->status = 'DRAFT';
				$TRecDossier->date_start = time();
				$TRecDossier->date_end = 0;
				
				$TRecDossier->etape->load($ATMdb, $id_etape);
				
				$TRecDossier->save($ATMdb);
			}
			
			//on ajoute la facture au dossier
			
			$filepath = !empty($request['TProcedureFile'][$idfacture]) ? $request['TProcedureFile'][$idfacture] : '';
			//var_dump($id_etape,$filepath,$idfacture);exit;
			$TRecDossier->addFacture($idfacture, $filepath  );
			$TRecDossier->save($ATMdb);
			
			if($id_etape>0) $TRecDossier->doAction($user, $ATMdb);
		}	
	}

	if(!$existeProcedure) {
		setEventMessage($langs->trans('ErrorChooseProcedure'),'warnings');
	}
		
}