<?php
require_once("../../../../inc/confNetisse.php");
require_once('../tcpdf_include.php');
session_start();

$NOM = (isset($_GET['nom'])) ? $_GET['nom'] : ""; $NOM = str_replace("_"," ",$NOM);
$AGENCE = htmlspecialchars($_GET['agence']); $AGENCE = str_replace("_"," ",$AGENCE);
$MATRICULE = (isset($_GET['matricule'])) ? $_GET['matricule'] : "";
$EDS = $_GET['eds'];
$TYPE_AGENCE = $_GET['type_agence'];
$DATE = date("d-m-Y_H-i-s"); 
$RDV_AGENT = (isset($_GET['rdv_agent'])) ? $_GET['rdv_agent'] : "";
$RDV_AGENCE = $_GET['rdv_agence'];
$SRDV_AGENT = (isset($_GET['srdv_agent'])) ? $_GET['srdv_agent'] : "";
$SRDV_AGENCE = $_GET['srdv_agence'];
$SHIP_AGENT = (isset($_GET['ship_agent'])) ? $_GET['ship_agent'] : "";
$SHIP_AGENCE = $_GET['ship_agence'];
$DA_AGENT = (isset($_GET['da_agent'])) ? str_replace('-',':',$_GET['da_agent']) : "";
$DA_AGENCE = str_replace('-',':',$_GET['da_agence']);
$DA_RDV_AGENT = (isset($_GET['da_rdv_agent'])) ? str_replace('-',':',$_GET['da_rdv_agent']) : "";
$DA_RDV_AGENCE = str_replace('-',':',$_GET['da_rdv_agence']);
$DA_SRDV_AGENT = (isset($_GET['da_srdv_agent'])) ? str_replace('-',':',$_GET['da_srdv_agent']) : "";
$DA_SRDV_AGENCE = str_replace('-',':',$_GET['da_srdv_agence']);
$DA_SHIP_AGENT = (isset($_GET['da_ship_agent'])) ? str_replace('-',':',$_GET['da_ship_agent']) : "";
$DA_SHIP_AGENCE = str_replace('-',':',$_GET['da_ship_agence']);
$NBCLIAG =  $_GET['nb_clt'];
$NFC_AGENCY = $_GET['nfc'];
$ISMOTIF = $_GET['is_motif'];
// $NBCLISRDVPRESTA1 = $_GET['NBCLISRDVPRESTA1'];
// $NBCLISRDVPRESTA1C = $_GET['NBCLISRDVPRESTA1C'];
// $NBCLISRDVPRESTA2 = $_GET['NBCLISRDVPRESTA2'];
// $NBCLISRDVPRESTA2C = $_GET['NBCLISRDVPRESTA2C'];
// $NBCLISRDVPRESTA3 = $_GET['NBCLISRDVPRESTA3'];
// $NBCLISRDVPRESTA3C = $_GET['NBCLISRDVPRESTA3C'];
// $NBCLISRDVPRESTA4 = $_GET['NBCLISRDVPRESTA4'];
// $NBCLISRDVPRESTA4C = $_GET['NBCLISRDVPRESTA4C'];
$START = "-TOUT-";
$END = "-TOUT-";

class MYPDF extends TCPDF {

	public function Header() {
		$this->SetFillColorArray(array(255,255,255));
		$this->SetTextColorArray(array(0,0,0));
		$this->SetDrawColorArray(array(0,0,0));
		$content = <<<EOD
		<img src="/assets/img/pdf-header.jpg" width="1200" height="160"  />
EOD;
		$this->MultiCell(300, 160, $content, 0, 'J', true, 0, $x='0', $y='0', true, 0, true, false, 0, 'T', true);
		$this->SetXY(10, 8);
		$this->SetFont('helvetica', '', 16);
		//$this->Cell(0, 0, "Agence ".$_GET['agence'], 0, 0, 'R');
		$TABAGENCE = $_GET['nom'];
		$AGENCE = str_replace('_',' ',$_GET['agence']);// $AGENCE = str_replace('_',' ',$TABAGENCE[0]);
		if(!isset($GLOBALS["PILE_CONF"]["PDF"]["HEADER"]["AGENCY"]))
			$this->Cell(0, 0, $AGENCE, 0, 0, 'R');
		else{
			$AGENCE_HEADER = str_replace("[AGENCY]",$AGENCE,$GLOBALS["PILE_CONF"]["PDF"]["HEADER"]["AGENCY"]);
			$this->Cell(0, 0, $AGENCE_HEADER, 0, 0, 'R');
		}

		$this->SetXY(0, 40);
		$this->SetFont('helvetica', '', 14);
		//$NOM = (isset($_GET['nom'])) ? $_GET['nom'] : ""; $NOM = str_replace("_"," ",$NOM);
		//$this->Cell(200, 0, str_replace('-',' ',$NOM), 0, 1, 'C', true, '',0,false,'C','M');
		$NOMCONS = (isset($_GET['nomcons'])) ? $_GET['nomcons'] : ""; $NOMCONS = str_replace("_"," ",$NOMCONS);
		if(isset($_GET['matricule']) && !(isset($_SESSION['profiles']) && in_array("DA",$_SESSION['profiles']))) {
			$this->Cell(300, 0, $NOMCONS, 0, 1, 'C', true, '',0,false,'C','M');
		} else if(!isset($GLOBALS["PILE_CONF"]["PDF"]["HEADER"]["TEXT"]) || $GLOBALS["PILE_CONF"]["PDF"]["HEADER"]["TEXT"]) {
			$this->Cell(300, 0, $AGENCE, 0, 1, 'C', true, '',0,false,'C','M');
		}

		$this->SetXY(225, 30);
		$this->SetFont('helvetica', '', 10);
		setlocale (LC_TIME, "fr_FR");
		$this->Cell(40, 0, iconv("ISO-8859-9","UTF-8",strftime("%A %d %B %Y")), 0, 1, 'R', true, '',0,false,'C','M');
		$this->SetXY(215, 35);
		$this->Cell(40, 0, strftime("%H:%M:%S"), 0, 1, 'R', true, '',0,false,'C','M');


	}
	public function Footer() {
		$this->SetY(-13);
		$this->SetTextColor(77,77,77);
		$this->SetFillColor(77,77,77);
		$logo = $this->Image("../../tcpdf/examples/images/footercadif.png", 0, 197, 297);
		$this->Cell(0,0, $logo, 0, 0, 'R');

	}

	public function ColoredTable($data, $cancelled = 0) {
		$clientFields = getClientFields($data);
		$header = getHeader($data, $clientFields, $cancelled);
		$date = date('Y-m-d');
		$CHECK = "";
		$typesBindInsert = "isss";
		$valuesBindInsert = array(':data'=>$data, ':code_agence'=>$_REQUEST['code_agence'], ':deb'=>($date.' 00:00:00'), ':fin'=>($date.' 23:59:59'));
		$MATRICULE = (isset($_GET['matricule'])) ? $_GET['matricule'] : "0";
		$AFA = $_GET['afa'];
		$AFA_MOTIFS = (isset($GLOBALS["BO_CONF"]["AFA_MOTIFS"]) && $GLOBALS["BO_CONF"]["AFA_MOTIFS"]) ? true : false;
		if(isset($_SESSION['profiles']) && in_array("DA",$_SESSION['profiles'])) $MATRICULE = 0;
		if($MATRICULE != '0'){
			$CHECK = "AND ca_clients.id_action = ( SELECT id_conseiller FROM ca_conseillers WHERE id_agent = :id_agent AND supp=0 AND ca_clients.id_agence = (SELECT id_agence from ca_agences WHERE eds=:eds and supp=0)) ";
			$valuesBindInsert[':id_agent'] = $MATRICULE;
			$valuesBindInsert[':eds'] = $_REQUEST['eds'];
		}
		if($GLOBALS["PILE_CONF"]["CANCEL_CLIENT"]){
			$CHECK .= "	AND cancelled = :cancelled";
			$valuesBindInsert[':cancelled'] = $cancelled;
		}
		$leftJoins = ($GLOBALS["BO_CONF"]["MOTIFS"] || $_GET['is_motif']) ? " LEFT JOIN ca_client_motifs cm ON ca_clients.id_client=cm.id_client LEFT JOIN ca_motifs m ON cm.id_motif=m.id_motif" : "";
		$leftJoins .= ($GLOBALS["BO_CONF"]["AFA"] && $AFA && !$AFA_MOTIFS && ($_GET['is_motif'] == 0)) ? " LEFT JOIN ca_actions ac ON ca_clients.rdv_type=ac.id_action" : "";
		$additionalColumns .= ($GLOBALS["BO_CONF"]["MOTIFS"] || $_GET['is_motif']) ? ", group_concat(COALESCE(m.code,m.code,m.titre) SEPARATOR ', ') as motif" : "";
		$additionalColumns .= ($GLOBALS["BO_CONF"]["AFA"] && $AFA && !$AFA_MOTIFS && ($_GET['is_motif'] == 0)) ? ", group_concat(ac.titre SEPARATOR ', ') as motif_action" : "";
		$query = "SELECT ca_clients.*,ca_conseillers.nom nomCons, ca_conseillers.prenom prenomCons, DATE_FORMAT(ca_clients.date_arrivee,'%H:%i:%s') AS HEURE_ARRIVEE,
		DATE_FORMAT(ca_clients.date_priseencharge,'%H:%i:%s') AS HEURE_PRISEENCHARGE,
		DATE_FORMAT(ca_clients.date_cloture,'%H:%i:%s') AS HEURE_CLOTURE,
		TIMESTAMPDIFF(SECOND,date_arrivee,date_priseencharge) as DUREE_ATTENTE,
		TIMESTAMPDIFF(SECOND, date_priseencharge,date_cloture) as DUREE_ENTRETIEN".
		$additionalColumns." 
		FROM ca_clients
		LEFT JOIN ca_conseillers ON ca_conseillers.id_conseiller = ca_clients.id_action
		".$leftJoins."
		WHERE rdv=:data
		AND ca_clients.id_agence=(SELECT id_agence FROM ca_agences WHERE code_agence = :code_agence and supp=0)
		AND date_priseencharge > date_arrivee AND date_arrivee > :deb
		AND date_arrivee < :fin
		".$CHECK."
		GROUP BY ca_clients.id_client
		ORDER BY ca_clients.date_arrivee ASC";
		$stmt = excuteQuery($query, $valuesBindInsert);
		$nb=0;
		if ($stmt['status']) {
				$result = $stmt['stmt'];
				
				$nb = $result->rowCount();
				if($nb>0){
					if($cancelled){
						switch ($data) {
							case 0:
								$title = 'Sans RDV Annulés';
							break;
							case 1:
								$title = 'RDV Annulés';
							break;
							case 5:
								$title = 'LIVRAISON Annulés';
							break;
						}
					}
					else{
						switch ($data) {
							case 0:
								$title = 'Sans RDV';
							break;
							case 1:
								$title = 'RDV';
							break;
							case 5:
								$title = 'LIVRAISON';
							break;
						}
					}
					// if($cancelled){
					// 	$title = $data ? "       RDV Annulés" : "Sans RDV Annulés";
					// }
					// else{
					// 	$title = $data ? "RDV" : "      Sans RDV";
					// }
					// add a page
					$this->SetFillColorArray(false);
					$this->SetTextColorArray(array(0,0,0));
					$this->SetDrawColorArray(array(0,0,0));
					$this->Ln();$this->Ln();$this->Ln();
					$this->SetFont('helvetica', '', 16);
					$this->Cell('', 10, $title, 0, 1, 'C', false, '',0,false,'C','M');
					$this->SetFont('helvetica', '', 8);

					// Colors, line width and bold font
					$this->SetFillColor(196, 21, 17);
					$this->SetTextColor(255);
					$this->SetDrawColor(196, 21, 17);
					$this->SetLineWidth(0.2);
					$this->SetFont('', 'B');
					// Header
					/*
					$length = 7;
					if($MATRICULE == '0'){
						$length++;
					}
					if($GLOBALS["BORNE_CONF"]["NFC"]){
						$length++;
					}
					
					if($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]){
						$length++;
					}
					*/
					$num_headers = count($header);
					
					$w = calculateWidths($header, $data);
					for($i = 0; $i < $num_headers; ++$i) {
						$this->Cell($w[$i], $num_headers-1, $header[$i], 1, 0, 'C', 1);
					}

					
					$this->Ln();
					// Color and font restoration
					$this->SetFillColor(255, 240, 234);//$this->SetFillColor(224, 235, 255);
					$this->SetTextColor(0);
					$this->SetFont('');
					// Data
					$fill = 0;
					$comp=1;
					$replace = array('&lt;' => '', '&gt;' => '', '&#039;' => '', '&amp;' => '',
					'&quot;' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'Ae',
					'&Auml;' => 'A', 'Å' => 'A', 'Ā' => 'A', 'Ą' => 'A', 'Ă' => 'A', 'Æ' => 'Ae',
					'Ç' => 'C', 'Ć' => 'C', 'Č' => 'C', 'Ĉ' => 'C', 'Ċ' => 'C', 'Ď' => 'D', 'Đ' => 'D',
					'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ē' => 'E',
					'Ę' => 'E', 'Ě' => 'E', 'Ĕ' => 'E', 'Ė' => 'E', 'Ĝ' => 'G', 'Ğ' => 'G',
					'Ġ' => 'G', 'Ģ' => 'G', 'Ĥ' => 'H', 'Ħ' => 'H', 'Ì' => 'I', 'Í' => 'I',
					'Î' => 'I', 'Ï' => 'I', 'Ī' => 'I', 'Ĩ' => 'I', 'Ĭ' => 'I', 'Į' => 'I',
					'İ' => 'I', 'IJ' => 'IJ', 'Ĵ' => 'J', 'Ķ' => 'K', 'Ł' => 'K', 'Ľ' => 'K',
					'Ĺ' => 'K', 'Ļ' => 'K', 'Ŀ' => 'K', 'Ñ' => 'N', 'Ń' => 'N', 'Ň' => 'N',
					'Ņ' => 'N', 'Ŋ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
					'Ö' => 'Oe', '&Ouml;' => 'Oe', 'Ø' => 'O', 'Ō' => 'O', 'Ő' => 'O', 'Ŏ' => 'O',
					'Œ' => 'OE', 'Ŕ' => 'R', 'Ř' => 'R', 'Ŗ' => 'R', 'Ś' => 'S', 'Š' => 'S',
					'Ş' => 'S', 'Ŝ' => 'S', 'Ș' => 'S', 'Ť' => 'T', 'Ţ' => 'T', 'Ŧ' => 'T',
					'Ț' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'Ū' => 'U',
					'&Uuml;' => 'Ue', 'Ů' => 'U', 'Ű' => 'U', 'Ŭ' => 'U', 'Ũ' => 'U', 'Ų' => 'U',
					'Ŵ' => 'W', 'Ý' => 'Y', 'Ŷ' => 'Y', 'Ÿ' => 'Y', 'Ź' => 'Z', 'Ž' => 'Z',
					'Ż' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
					'ä' => 'ae', '&auml;' => 'ae', 'å' => 'a', 'ā' => 'a', 'ą' => 'a', 'ă' => 'a',
					'æ' => 'ae', 'ç' => 'c', 'ć' => 'c', 'č' => 'c', 'ĉ' => 'c', 'ċ' => 'c',
					'ď' => 'd', 'đ' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
					'ë' => 'e', 'ē' => 'e', 'ę' => 'e', 'ě' => 'e', 'ĕ' => 'e', 'ė' => 'e',
					'ƒ' => 'f', 'ĝ' => 'g', 'ğ' => 'g', 'ġ' => 'g', 'ģ' => 'g', 'ĥ' => 'h',
					'ħ' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ī' => 'i',
					'ĩ' => 'i', 'ĭ' => 'i', 'į' => 'i', 'ı' => 'i', 'ij' => 'ij', 'ĵ' => 'j',
					'ķ' => 'k', 'ĸ' => 'k', 'ł' => 'l', 'ľ' => 'l', 'ĺ' => 'l', 'ļ' => 'l',
					'ŀ' => 'l', 'ñ' => 'n', 'ń' => 'n', 'ň' => 'n', 'ņ' => 'n', 'ʼn' => 'n',
					'ŋ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
					'&ouml;' => 'oe', 'ø' => 'o', 'ō' => 'o', 'ő' => 'o', 'ŏ' => 'o', 'œ' => 'oe',
					'ŕ' => 'r', 'ř' => 'r', 'ŗ' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
					'û' => 'u', 'ü' => 'ue', 'ū' => 'u', '&uuml;' => 'ue', 'ů' => 'u', 'ű' => 'u',
					'ŭ' => 'u', 'ũ' => 'u', 'ų' => 'u', 'ŵ' => 'w', 'ý' => 'y', 'ÿ' => 'y',
					'ŷ' => 'y', 'ž' => 'z', 'ż' => 'z', 'ź' => 'z', 'þ' => 't', 'ß' => 'ss',
					'ſ' => 'ss', 'ый' => 'iy', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G',
					'Д' => 'D', 'Е' => 'E', 'Ё' => 'YO', 'Ж' => 'ZH', 'З' => 'Z', 'И' => 'I',
					'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
					'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F',
					'Х' => 'H', 'Ц' => 'C', 'Ч' => 'CH', 'Ш' => 'SH', 'Щ' => 'SCH', 'Ъ' => '',
					'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'YU', 'Я' => 'YA', 'а' => 'a',
					'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo',
					'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l',
					'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's',
					'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch',
					'ш' => 'sh', 'щ' => 'sch', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e',
					'ю' => 'yu', 'я' => 'ya');
					
					$row = "";
					while ($row = $result->fetchObject()) {
						$motif = "";
						if($data == 0 && $GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) {
								$motif = $row->motif . $row->motif_action;
						}
						if($comp == 1) $START = date('d/m/Y',strtotime($row->date_arrivee));


						$headerIndex = 0;
						$DA = ($row->DUREE_ATTENTE != "") ? gmdate("H:i:s",$row->DUREE_ATTENTE) : '-';
						$DR = ($row->DUREE_ENTRETIEN != "") ? gmdate("H:i:s",$row->DUREE_ENTRETIEN) : '-';

						$row->nomCons = str_replace(array_keys($replace), $replace, $row->nomCons);
						$row->prenomCons = str_replace(array_keys($replace), $replace, $row->prenomCons);
						
						$num_pages = $this->getNumPages();
						$this->startTransaction();

						$this->Cell($w[$headerIndex], 6, $comp, 'LR', 0, 'C', $fill);$headerIndex++;
						if((!$GLOBALS["BO_CONF"]["NFCBYAGENCY"] && $GLOBALS["BORNE_CONF"]["NFC"]) || ($GLOBALS["BO_CONF"]["NFCBYAGENCY"] && (isset($_GET['nfc']) && $_GET['nfc']))) {$this->Cell($w[$headerIndex], 6, ($row->nfcprov?'Oui':"Non"), 'LR', 0, 'C', $fill);$headerIndex++;}
						$this->SetFont('dejavusans');
						if($clientFields["nom"]){ $this->Cell($w[$headerIndex], 6, addslashes(strtoupper($row->nom)), 'LR', 0, 'L', $fill);$headerIndex++;}
						if($clientFields["prenom"]){ $this->Cell($w[$headerIndex], 6, addslashes($row->prenom), 'LR', 0, 'L', $fill);$headerIndex++;}
						$this->SetFont('helvetica');
						$this->Cell($w[$headerIndex], 6, $row->HEURE_ARRIVEE, 'LR', 0, 'C', $fill);$headerIndex++;
						$this->Cell($w[$headerIndex], 6, $row->HEURE_PRISEENCHARGE, 'LR', 0, 'C', $fill);$headerIndex++;
						$this->Cell($w[$headerIndex], 6, $DA, 'LR', 0, 'C', $fill);$headerIndex++;
						if(!$cancelled){$this->Cell($w[$headerIndex], 6, $DR, 'LR', 0, 'C', $fill);$headerIndex++;}
						if($data == 0 && $GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) {
							$this->Cell($w[$headerIndex], 6, $motif, 'LR', 0, 'C', $fill);
							$headerIndex++;
						}
						if($MATRICULE == '0'){ $this->Cell($w[$headerIndex], 6, strtoupper($row->nomCons).".".strtoupper(substr($row->prenomCons,0,1)), 'LR', 0, 'C', $fill);$headerIndex++; }
										

						if($num_pages < $this->getNumPages())
						{
							//Undo adding the row.
							$this->rollbackTransaction(true);
							$this->Ln();	
							//$tableType = $data ? 'RDV' : '      Sans RDV'; 
							switch ($data) {
								case 0:
									$tableType = 'Sans RDV';
								break;
								case 1:
									$tableType = 'RDV';
								break;
								case 5:
									$tableType = 'LIVRAISON';
								break;
							}
							$this->SetFont('helvetica', '', 16);
							$this->Cell('', 10, $tableType, 0, 1, 'C', false, '',0,false,'C','M');
							$this->SetFont('helvetica', '', 8);
							//Draw the header.				
							$this->SetFillColor(196, 21, 17);
							$this->SetTextColor(255);
							$this->SetDrawColor(196, 21, 17);
							$this->SetLineWidth(0.2);
							$this->SetFont('', 'B');	
							for($i = 0; $i < $num_headers; ++$i) {
								$this->Cell($w[$i], $num_headers-1, $header[$i], 1, 0, 'C', 1);
							}
							$this->Ln();		
							$this->SetFillColor(255, 240, 234);//$this->SetFillColor(224, 235, 255);
							$this->SetTextColor(0);
							$this->SetFont('');
							$fill=!$fill;
							$headerIndex = 0;
							//Re-do the row.
							$this->Cell($w[$headerIndex], 6, $comp, 'LR', 0, 'C', $fill);$headerIndex++;
							if((!$GLOBALS["BO_CONF"]["NFCBYAGENCY"] && $GLOBALS["BORNE_CONF"]["NFC"]) || ($GLOBALS["BO_CONF"]["NFCBYAGENCY"] && (isset($_GET['nfc']) && $_GET['nfc']))) {$this->Cell($w[$headerIndex], 6, ($row->nfcprov?'Oui':"Non"), 'LR', 0, 'C', $fill);$headerIndex++;}
							$this->SetFont('dejavusans');
							if($clientFields["nom"]){ $this->Cell($w[$headerIndex], 6, addslashes(strtoupper($row->nom)), 'LR', 0, 'L', $fill);$headerIndex++;}
							if($clientFields["prenom"]){ $this->Cell($w[$headerIndex], 6, addslashes($row->prenom), 'LR', 0, 'L', $fill);$headerIndex++;}
							$this->SetFont('helvetica');
							$this->Cell($w[$headerIndex], 6, $row->HEURE_ARRIVEE, 'LR', 0, 'C', $fill);$headerIndex++;
							$this->Cell($w[$headerIndex], 6, $row->HEURE_PRISEENCHARGE, 'LR', 0, 'C', $fill);$headerIndex++;
							$this->Cell($w[$headerIndex], 6, $DA, 'LR', 0, 'C', $fill);$headerIndex++;
							if(!$cancelled){$this->Cell($w[$headerIndex], 6, $DR, 'LR', 0, 'C', $fill);$headerIndex++;}
							if($data == 0 && $GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) {$this->Cell($w[$headerIndex], 6, $motif, 'LR', 0, 'C', $fill);$headerIndex++;}
							if($MATRICULE == '0'){ $this->Cell($w[$headerIndex], 6, strtoupper($row->nomCons).".".strtoupper(substr($row->prenomCons,0,1)), 'LR', 0, 'C', $fill);$headerIndex++; }			
						}
						else
						{
							//Otherwise we are fine with this row, discard undo history.
							$this->commitTransaction();
						}
						$this->Ln();
						$fill=!$fill;
						$comp++;
						if($comp == $result->rowCount()) $END = $row->date_arrivee;
					}

					$this->Cell(array_sum($w), 0, '', 'T');
				}			
			}
	}
}

function getClientFields($rdv){
	if(in_array('keyboard-page',$GLOBALS["BORNE_CONF"]["SCREENS"][$rdv])){
		$prenom = $GLOBALS["BO_CONF"]["CLIENT"]["prenom"] || $GLOBALS["BORNE_CONF"]["FIELDS"]["FIRSTNAME"]["ENABLED"];
		$nom = !!$GLOBALS["BORNE_CONF"]["FIELDS"]["LASTNAME"]["ENABLED"];
		$civ = !!$GLOBALS["BORNE_CONF"]["FIELDS"]["GENDER"]["ENABLED"];
		return array("civ"=>$civ,"nom"=>$nom,"prenom"=>$prenom);
	}
	return array("civ"=>false,"nom"=>false,"prenom"=>false);

}
function calculateWidths($header, $rdv){
	$MAX_WIDTH = 60;
	$dynamicColumnCount = $diffWidth = 0;
	$staticColumnCount = 4;
	$w = array_fill(0,count($header),12);
	//Rest 277
	$da = array_search("DA",$header); //20
	$de = array_search("DE",$header);//20
	$arr = array_search("Arrivée",$header);//20
	$pe = array_search("Prise en charge",$header); //30
	$nfc = array_search("NFC",$header); //15

	$w[$da] = $w[$de] = $w[$arr] = 20;
	$w[$pe] = 30;
	$restWidth = 175;
	if($nfc){
		$w[$nfc] = 15;
		$restWidth = 160;
		$staticColumnCount++;
	}

	// Dynamic width
	if($rdv<5){
	$nom = array_search("Nom",$header) ? array_search("Nom",$header) : array_search("Nom et prénom",$header);
	$prenom = array_search("Prénom",$header);
	}else{
		$nom = false;
		$prenom = false;
	}
	$motif = array_search("Motif",$header);
	$conseiller = array_search("Conseiller",$header);
	$cancelled = array_search("Annulation",$header);
	if($rdv == 5){
		$dynamicColumnCount = count($header);
	}else{
		if($nom){
			$dynamicColumnCount++;
		}
		if($prenom){
			$dynamicColumnCount++;
		}
		if($motif){
			$dynamicColumnCount++;
		}
		if($conseiller){
			$dynamicColumnCount++;
		}
		if($cancelled){
			$dynamicColumnCount++;
		}
	}
	$dynamicWidth = round($restWidth/$dynamicColumnCount);
	$tooLarge =  ($dynamicWidth > $MAX_WIDTH) ? true : false;
	if($tooLarge){
		$diffWidth = ($dynamicWidth - $MAX_WIDTH) * $dynamicColumnCount;
		$dynamicWidth = $MAX_WIDTH;
	}
	if($nom && $rdv != 5){
		$w[$nom] = $dynamicWidth;
	}
	if($prenom && $rdv != 5){
		$w[$prenom] = $dynamicWidth;
	}
	if($motif){
		$w[$motif] = $dynamicWidth;
	}
	if($conseiller){
		$w[$conseiller] = $dynamicWidth;
	}
	if($cancelled){
		$w[$cancelled] = $dynamicWidth;
	}
	if($tooLarge){
		$staticWidth = 20 + round($diffWidth/$staticColumnCount);
		$w[$da] = $w[$de] = $w[$arr] = $staticWidth;	
		
		if($nfc){
			$w[$nfc] = $staticWidth;
		}
	}	
	$ws = 277 - array_sum($w);
	if($ws > 0){
		$w[$arr] += $ws/4;
		$w[$da] += $ws/4;
		$w[$pe] += $ws/4;
		$w[$de] += $ws/4;
	}

	return $w;
}

function getHeader($rdv, $clientFields, $cancelled = 0){
	$header = array();
	if($rdv == 5){
		if(isset($_GET['matricule'])){
			$header = array('Clts', 'Arrivée', 'Prise en charge', 'DA', 'DE');
		}
		else{
			$header = array('Clts', 'Arrivée', 'Prise en charge', 'DA', 'DE','Conseiller');
		}
		if(isset($_SESSION['profiles']) && in_array("DA",$_SESSION['profiles'])) {
			$header = array('Clts', 'Arrivée', 'Prise en charge', 'DA', 'DE','Conseiller');
		}
		if((!$GLOBALS["BO_CONF"]["NFCBYAGENCY"] && $GLOBALS["BORNE_CONF"]["NFC"]) || ($GLOBALS["BO_CONF"]["NFCBYAGENCY"] && (isset($_GET['nfc']) && $_GET['nfc'])))
			array_splice($header, 1, 0, 'NFC');
		if($GLOBALS["PILE_CONF"]["CANCEL_CLIENT"] && $cancelled){
			$pecIndex = array_search('Prise en charge',$header);
			$deIndex = array_search('DE',$header);
			array_splice($header, $deIndex, 1);
			$header[$pecIndex] = 'Annulation';
		}
	}elseif($rdv <=1){
		if($rdv == 1){
			if(isset($_GET['matricule'])){
				$header = array('Clts', 'Nom', 'Prénom', 'Arrivée', 'Prise en charge', 'DA', 'DE');
			}
			else{
				$header = array('Clts', 'Nom', 'Prénom', 'Arrivée', 'Prise en charge', 'DA', 'DE','Conseiller');
			}
			if(isset($_SESSION['profiles']) && in_array("DA",$_SESSION['profiles'])) {
				$header = array('Clts', 'Nom', 'Prénom', 'Arrivée', 'Prise en charge', 'DA', 'DE','Conseiller');
			}
			$prenomIndex = array_search('Prénom',$header);
			$nomIndex = array_search('Nom',$header);
			if(!$clientFields["prenom"] && $prenomIndex){
				array_splice($header, $prenomIndex, 1);
				$header[$nomIndex] = 'Nom et prénom';
			}
			if(!$clientFields["nom"]){
				array_splice($header, $nomIndex, 1);
			}
			if((!$GLOBALS["BO_CONF"]["NFCBYAGENCY"] && $GLOBALS["BORNE_CONF"]["NFC"]) || ($GLOBALS["BO_CONF"]["NFCBYAGENCY"] && (isset($_GET['nfc']) && $_GET['nfc'])))
				array_splice($header, 1, 0, 'NFC');
			if($GLOBALS["PILE_CONF"]["CANCEL_CLIENT"] && $cancelled){
				$pecIndex = array_search('Prise en charge',$header);
				$deIndex = array_search('DE',$header);
				array_splice($header, $deIndex, 1);
				$header[$pecIndex] = 'Annulation';
			}
		}
		else {
			if(isset($_GET['matricule'])) {	
				$header = array('Clts', 'Nom', 'Prénom', 'Arrivée', 'Prise en charge', 'DA', 'DE');
		
				$nfcIndex = array_search('NFC',$header);
				if((!$GLOBALS["BO_CONF"]["NFCBYAGENCY"] && $GLOBALS["BORNE_CONF"]["NFC"]) || ($GLOBALS["BO_CONF"]["NFCBYAGENCY"] && (isset($_GET['nfc']) && $_GET['nfc'])))
					array_splice($header, 1, 0, 'NFC');
		
				$motifIndex = array_search('Conseiller',$header) ? (count($header)-1) : count($header);
				if($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"])
					array_splice($header,$motifIndex, 0, 'Motif');
		
				$prenomIndex = array_search('Prénom',$header);
				$nomIndex = array_search('Nom',$header);
				if(!$clientFields["prenom"] && $prenomIndex){
					array_splice($header, $prenomIndex, 1);
					$header[$nomIndex] = 'Nom et prénom';
				}
				if(!$clientFields["nom"]){
					array_splice($header, $nomIndex, 1);
				}
			}
			else{
				$header = array('Clts', 'Nom', 'Prénom', 'Arrivée', 'Prise en charge', 'DA', 'DE','Conseiller');
		
				$motifIndex = array_search('Conseiller',$header) ? (count($header)-1) : count($header);
				if($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"])
					array_splice($header, $motifIndex, 0, 'Motif');
		
				if((!$GLOBALS["BO_CONF"]["NFCBYAGENCY"] && $GLOBALS["BORNE_CONF"]["NFC"]) || ($GLOBALS["BO_CONF"]["NFCBYAGENCY"] && (isset($_GET['nfc']) && $_GET['nfc'])))
					array_splice($header, 1, 0, 'NFC');
		
				$prenomIndex = array_search('Prénom',$header);
				$nomIndex = array_search('Nom',$header);
				if(!$clientFields["prenom"] && $prenomIndex){
					array_splice($header, $prenomIndex, 1);
					$header[$nomIndex] = 'Nom et prénom';
				}
				if(!$clientFields["nom"]){
					array_splice($header, $nomIndex, 1);
				}
			}
			if(isset($_SESSION['profiles']) && in_array("DA",$_SESSION['profiles'])) {
				$header = array('Clts', 'Nom', 'Prénom', 'Arrivée', 'Prise en charge', 'DA', 'DE','Conseiller');
				
				$motifIndex = array_search('Conseiller',$header) ? (count($header)-1) : count($header);
				if($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"])
					array_splice($header, $motifIndex, 0, 'Motif');
		
				if((!$GLOBALS["BO_CONF"]["NFCBYAGENCY"] && $GLOBALS["BORNE_CONF"]["NFC"]) || ($GLOBALS["BO_CONF"]["NFCBYAGENCY"] && (isset($_GET['nfc']) && $_GET['nfc'])))
					array_splice($header, 1, 0, 'NFC');
		
				$prenomIndex = array_search('Prénom',$header);
				$nomIndex = array_search('Nom',$header);
				if(!$clientFields["prenom"] && $prenomIndex){
					array_splice($header, $prenomIndex, 1);
					$header[$nomIndex] = 'Nom et prénom';
				}
				if(!$clientFields["nom"]){
					array_splice($header, $nomIndex, 1);
				}
			}
			if($GLOBALS["PILE_CONF"]["CANCEL_CLIENT"] && $cancelled){
				$pecIndex = array_search('Prise en charge',$header);
				$deIndex = array_search('DE',$header);
				array_splice($header, $deIndex, 1);
				$header[$pecIndex] = 'Annulation';
			}
		}
	}
	return $header;
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

if($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]){
	$CPRESTAS = $PRESTAS = "";
	$motifs = (isset($_GET["MOTIFS"]) || $ISMOTIF) ? json_decode($_GET["MOTIFS"]) : array();
	foreach($motifs as $key => $motif){
		$PRESTAS .= strip_tags(str_replace("<br/>"," ",$motif->titre)).($motif->code ? " [".$motif->code."] " : "")." : ".($motif->nb_agence?$motif->nb_agence:0)."<br/>";
		$CPRESTAS .= strip_tags(str_replace("<br/>"," ",$motif->titre)).($motif->code ? " [".$motif->code."] " : "")." : ".($motif->nb_agent?$motif->nb_agent:0) . " / " . ($motif->nb_agence?$motif->nb_agence:0) ."<br/>";
	}
	$PRESTAS .= "<br/>";
	$CPRESTAS .= "<br/>";
}

/*
// Form validation functions
$js = <<<EOD
function CheckField(name,message) {
	var f = getField(name);
	if(f.value == '') {
	    app.alert(message);
	    f.setFocus();
	    return false;
	}
	return true;
}
function Print() {
	if(!CheckField('debut','Date de début requise')) {return;}
	if(!CheckField('fin','Date de fin requise')) {return;}
	print();
}
function SubmitForm() {
	if(!CheckField('debut','Date de début requise')) {return;}
	if(!CheckField('fin','Date de fin requise')) {return;}
	var start = getField('debut');
	start = start.value;
	var end = getField('fin');
	end = end.value;
	var rdv = getField('rdv');
	rdv = rdv.value;
	app.console.log(this);
	app.console.log(window);
	app.console.log(app);
	window.location.href = window.location.href + '&type_rdv='+rdv+'&start='+start.replace('/','-')+'&end='+end.replace('/','-')+'"';
}
EOD;

// Add Javascript code
$pdf->IncludeJS($js);
*/
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor($PROJECT_ABBREVIATION);
$pdf->SetTitle('Rapport '.$PROJECT_ABBREVIATION);
$pdf->SetSubject('Rapport du '.date('d-m-Y H:i:s'));
$pdf->SetKeywords('Rapport, PDF, Statistiques, CAAQ');


// set default header data
//$pdf->SetHeaderData('headercadif.jpg', '210', '', "Agence ".$NOM_AGENCE->nom_agence);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(10, 30, 30, 10);
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(13);

//$pdf->setPrintHeader(false);
//$pdf->setPrintFooter(false);


// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->SetTopMargin(50);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/fra.php')) {
    require_once(dirname(__FILE__).'/lang/fra.php');
    $pdf->setLanguageArray($l);
}

// set font
$pdf->SetFont('helvetica', 'B', 20);

// add a page
$pdf->AddPage('L');

$pdf->SetFillColorArray(array(255,255,255));
$pdf->SetTextColorArray(array(0,0,0));
$pdf->SetDrawColorArray(array(0,0,0));

$pdf->SetXY(20, 50);
$pdf->SetFont('helvetica', '', 10);


if($MATRICULE == "" || (isset($_SESSION['profiles']) && in_array("DA",$_SESSION['profiles']))){
	$SRDV_DATA = "";
	if(!$GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] || $TYPE_AGENCE == 1 || $TYPE_AGENCE == 3){
		$SRDV_DATA = "Nombre total SRDV : ".$SRDV_AGENCE."<br/>
		Temps moyen d'attente SRDV : ".$DA_SRDV_AGENCE."<br/><br/>";
	}
	$SHIP_DATA = "Nombre total LIVRAISON : ".$SHIP_AGENCE."<br/>
		Temps moyen d'attente LIVRAISON : ".$DA_SHIP_AGENCE."<br/><br/>";
	if((($_GET['is_motif'] || $GLOBALS["BO_CONF"]["MOTIFS"]) && $GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) && $TYPE_AGENCE == 1)
		$content=<<<EOD
		<div>
			<b>Nombre de clients de la journée : $NBCLIAG</b><br/><br/>
			Nombre total RDV : $RDV_AGENCE<br/>
			Temps moyen d'attente RDV : $DA_RDV_AGENCE<br/><br/>
			$SRDV_DATA
			$PRESTAS
			$SHIP_DATA
		</div>
EOD;
	else
		$content=<<<EOD
		<div>
			<b>Nombre de clients de la journée : $NBCLIAG</b><br/><br/>
			Nombre total RDV : $RDV_AGENCE<br/>
			Temps moyen d'attente RDV : $DA_RDV_AGENCE<br/><br/>
			$SRDV_DATA
			$SHIP_DATA
		</div>
EOD;
}
else{
	$SRDV_DATA = "";
	if(!$GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] || $TYPE_AGENCE == 1 || $TYPE_AGENCE == 3){
		$SRDV_DATA = "Nombre total SRDV : ".$SRDV_AGENT." / ".$SRDV_AGENCE."<br/>
		Temps moyen d'attente SRDV : ".$DA_SRDV_AGENT." / ".$DA_SRDV_AGENCE."<br/><br/>";
	}
	$SHIP_DATA = "Nombre total LIVRAISON : ".$SHIP_AGENT." / ".$SHIP_AGENCE."<br/>
	Temps moyen d'attente LIVRAISON : ".$DA_SHIP_AGENT." / ".$DA_SHIP_AGENCE."<br/><br/>";
	if($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"] && $TYPE_AGENCE == 1)
		$content=<<<EOD
		<div>
			<b>Nombre de clients de la journée : $NBCLIAG</b><br/><br/>
			Nombre total RDV : $RDV_AGENT / $RDV_AGENCE<br/>
			Temps moyen d'attente RDV : $DA_RDV_AGENT / $DA_RDV_AGENCE<br/><br/>
			$SRDV_DATA
			$CPRESTAS
			$SHIP_DATA
		</div>
EOD;
	else
		$content=<<<EOD
		<div>
			<b>Nombre de clients de la journée : $NBCLIAG</b><br/><br/>
			Nombre total RDV : $RDV_AGENT / $RDV_AGENCE<br/>
			Temps moyen d'attente RDV : $DA_RDV_AGENT / $DA_RDV_AGENCE<br/><br/>
			$SRDV_DATA
			$SHIP_DATA
		</div>
EOD;
}

$tablePos = $GLOBALS["PILE_CONF"]["STATS"]["showMotifs"] ? 141 : 95;

$pdf->writeHTML($content, true, false, false, false, '');
$pdf->SetXY(20, $tablePos);
$shipSats = false;
if($GLOBALS["BO_CONF"]["AGENCE"]["SIEGE"] && $GLOBALS["BO_CONF"]["AGENCE"]["SIEGE"]["CHOICES"]){
    foreach ($GLOBALS["BO_CONF"]["AGENCE"]["SIEGE"]["CHOICES"] as $choice) {
        if($choice == 'shipping')
            $shipSats = true;
    }
}
if($shipSats){
    //$pdf->ColoredTable(5, 0);
    //$pdf->SetXY(20, $tablePos);
}

$pdf->ColoredTable(1,0);

if(!$GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] || $TYPE_AGENCE == 1 || $TYPE_AGENCE == 3){
	$pdf->ColoredTable(0,0);
}
if($GLOBALS["PILE_CONF"]["CANCEL_CLIENT"]){
	$pdf->ColoredTable(1, 1);
	if(!$GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] || $TYPE_AGENCE == 1 || $TYPE_AGENCE == 3){
		$pdf->ColoredTable(0, 1);
	}
}
$pdf->ColoredTable(5, 0);
$pdf->Ln();

//Close and output PDF document
//$pdf->Output('/data/IFP10/Donnees/APA/APA/docs/IFP10_APA/cadif/pdf/rapport'.str_replace(' ','-',$_GET['agence']).'_'.date('d-m-Y').'.pdf', 'D');//IFD
ob_end_clean();
$pdf->Output(date('Y_m_d')."_".str_replace(' ','_',$AGENCE).".pdf", "D");//IFD
?>