<?php
/**
 * Ausweis generator
 */

//Set default timezone
date_default_timezone_set('Europe/Paris');

//XXX: Append FPDF paths and qrlib to include_path
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '/usr/share/php/fpdf' . PATH_SEPARATOR . '/usr/share/php/fpdf/font' . PATH_SEPARATOR . '../vendor/phpqrcode');

//XXX: Set font path
define('FPDF_FONTPATH', '../vendor/font');

//Load FPDF
require 'fpdf.php';

//Require qrcode
//XXX: need php-gd
require 'qrlib.php';

//Set reasons
$reasons = ['travail', 'achats', 'sante', 'famille', 'handicap', 'sport_animaux', 'convocation', 'missions', 'enfants'];

//Display form 
if (
	empty($_REQUEST['type']) ||
	empty($_REQUEST['lastname']) ||
	empty($_REQUEST['firstname']) ||
	empty($_REQUEST['birthdate']) ||
	empty($_REQUEST['birthplace']) ||
	empty($_REQUEST['address']) ||
	empty($_REQUEST['zipcode']) ||
	empty($_REQUEST['city']) ||
	empty($_REQUEST['function']) ||
	empty($_REQUEST['location']) ||
	empty($_REQUEST['date']) ||
	empty($_REQUEST['time'])
) {
	//Set time
	//XXX: round it to previous 5 minute
	$time = floor(strtotime('now')/300)*300;

	//Set selected
	$selected = null;

	//Set selected
	if (empty($_REQUEST['type'])) {
		if (!empty($_SERVER['SCRIPT_URL'])) {
			if ($_SERVER['SCRIPT_URL'] == '/bnp') {
				$selected = 'bnp';
			} elseif ($_SERVER['SCRIPT_URL'] == '/poltrone') {
				$selected = 'poltrone';
			} elseif ($_SERVER['SCRIPT_URL'] == '/convoc') {
				$selected = 'convocation';
			} elseif ($_SERVER['SCRIPT_URL'] == '/achat') {
				$selected = 'achats';
			} elseif ($_SERVER['SCRIPT_URL'] == '/sport') {
				$selected = 'sport_animaux';
			} elseif ($_SERVER['SCRIPT_URL'] == '/travail') {
				$selected = 'travail';
			}
		}
	} else {
		if ($_REQUEST['type'] == 'bnp' || $_REQUEST['type'] == 'poltrone' || in_array($_REQUEST['type'], $reasons)) {
			$selected = $_REQUEST['type'];
		}
	}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
	<title>Ausweis generator</title>
	<style>
		p {
			color: red;
			font-weight: bold;
		}
		div,
		section {
			margin: 1rem auto;
			text-align: center;
		}
		div div {
			display: flex;
			justify-content: space-between;
			margin: 0 auto;
			width: 25rem;
		}
		span {
			color: #ccc;
			font-style: italic;
		}
		input,
		select {
			border: .1rem solid black;
			border-radius: .2rem;
			box-sizing: border-box;
			width: 12rem;
		}
		input:invalid,
		select:invalid {
			border-color: #c33333;
			background-color: #f9c3c3;
			color: #c33333;
		}
		input:valid,
		select:valid {
			background-color: #c3f9c3;
			border-color: #33c333;
			color: #33c333;
		}
		input[type="date"] {
			width: 9rem;
		}
		input[type="time"] {
			width: 6rem;
		}
		input[type="submit"] {
			background-color: #efefef;
			border-color: black;
			color: black;
			margin: 0 .5rem;
		}
		input[type="submit"]:first-child,
		input[type="submit"]:last-child {
			margin: 0;
		}
	</style>
</head>
<body>
	<section>
		<h1>Generateur d'attestation</h1>
		<p>Tous les champs sont obligatoires, format de date jj/mm/aaaa, format horaire hh:mm</p>
		<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>" method="post" autocomplete="on">
			<div>
				<div>
					<label for="type">Type</label>
					<select id="type" name="type" required="required">
						<optgroup label="Professional">
							<option value="bnp"<?php echo empty($selected)||$selected=='bnp'?' selected="selected"':''; ?>>Bnp</option>
							<option value="poltrone"<?php echo !empty($selected)&&$selected=='poltrone'?' selected="selected"':''; ?>>Poltrone</option>
						</optgroup>
						<optgroup label="Personnal">
							<option value="travail"<?php echo !empty($selected)&&$selected=='travail'?' selected="selected"':''; ?>>Travail</option>
							<option value="achats"<?php echo !empty($selected)&&$selected=='achats'?' selected="selected"':''; ?>>Achat</option>
							<option value="sante"<?php echo !empty($selected)&&$selected=='sante'?' selected="selected"':''; ?>>Sante</option>
							<option value="famille"<?php echo !empty($selected)&&$selected=='famille'?' selected="selected"':''; ?>>Famille</option>
							<option value="handicap"<?php echo !empty($selected)&&$selected=='handicap'?' selected="selected"':''; ?>>Handicap</option>
							<option value="sport_animaux"<?php echo !empty($selected)&&$selected=='sport_animaux'?' selected="selected"':''; ?>>Sport</option>
							<option value="convocation"<?php echo !empty($selected)&&$selected=='convocation'?' selected="selected"':''; ?>>Convocation</option>
							<option value="missions"<?php echo !empty($selected)&&$selected=='missions'?' selected="selected"':''; ?>>Mission</option>
							<option value="enfants"<?php echo !empty($selected)&&$selected=='enfants'?' selected="selected"':''; ?>>Enfant</option>
						</optgroup>
					</select>
				</div>
			</div>
			<div>
				<div>
					<label for="firstname">Prénom</label>
					<input type="text" id="firstname" name="firstname" value="<?php echo htmlspecialchars($_REQUEST['firstname']??''); ?>" autocomplete="given-name" required="required" />
				</div>
				<div>
					<span>Jean</span>
				</div>
			</div>
			<div>
				<div>
					<label for="lastname">Nom</label>
					<input type="text" id="lastname" name="lastname" value="<?php echo htmlspecialchars($_REQUEST['lastname']??''); ?>" autocomplete="family-name" required="required" />
				</div>
				<div>
					<span>Dupont</span>
				</div>
			</div>
			<div>
				<div>
					<label for="birthdate">Date de naissance</label>
					<input type="date" id="birthdate" name="birthdate" value="<?php echo htmlspecialchars($_REQUEST['birthdate']??''); ?>" autocomplete="bday" required="required" />
				</div>
				<div>
					<span>01/01/1970</span>
				</div>
			</div>
			<div>
				<div>
					<label for="birthplace">Lieu de naissance</label>
					<input type="text" id="birthplace" name="birthplace" value="<?php echo htmlspecialchars($_REQUEST['birthplace']??''); ?>" required="required" />
				</div>
				<div>
					<span>Lyon</span>
				</div>
			</div>
			<div>
				<div>
					<label for="address">Adresse</label>
					<input type="text" id="address" name="address" value="<?php echo htmlspecialchars($_REQUEST['address']??''); ?>" autocomplete="address-line1" required="required" />
				</div>
				<div>
					<span>10 rue Colbert</span>
				</div>
			</div>
			<div>
				<div>
					<label for="zipcode">Code postal</label>
					<input type="text" id="zipcode" name="zipcode" value="<?php echo htmlspecialchars($_REQUEST['zipcode']??''); ?>" autocomplete="postal-code" required="required" />
				</div>
				<div>
					<span>75002</span>
				</div>
			</div>
			<div>
				<div>
					<label for="city">Ville</label>
					<input type="text" id="city" name="city" value="<?php echo htmlspecialchars($_REQUEST['city']??''); ?>" autocomplete="address-level2" required="required" />
				</div>
				<div>
					<span>Paris</span>
				</div>
			</div>
			<div>
				<div>
					<label for="function">Fonction</label>
					<input type="text" id="function" name="function" value="<?php echo htmlspecialchars($_REQUEST['function']??'Technicien(e) d\'astreint(e)'); ?>" autocomplete="organization-title" required="required" />
				</div>
				<div>
					<span>Technicien(e) d'astreint(e)</span>
				</div>
			</div>
			<div>
				<div>
					<label for="location">Fait à</label>
					<input type="text" id="location" name="location" value="<?php echo htmlspecialchars($_REQUEST['location']??'Paris'); ?>" autocomplete="address-level2" required="required" />
				</div>
				<div>
					<span>Paris</span>
				</div>
			</div>
			<div>
				<div>
					<label for="date">Sortie</label>
					<input type="date" id="date" name="date" value="<?php echo htmlspecialchars($_REQUEST['date']??date('Y-m-d', $time)); ?>" required="required" />
					<label for="time">a</label>
					<?php /*<datalist id="timelist">
						<?php for($h = 0; $h < 24; $h++): for($m = 0; $m < 55; $m += 5): ?>
							<option value="<?php printf('%02d:%02d', $h, $m); ?>"<?php if ($_REQUEST['time']??date('H:i', $time) == sprintf('%02d:%02d', $h, $m)): ?> selected="selected"<?php endif; ?>>
						<?php endfor; endfor ?>
					</datalist> */ ?>
					<input type="time" id="time" name="time" value="<?php echo htmlspecialchars($_REQUEST['time']??date('H:i', $time)); ?>" step="300"<?php # list="timelist" ?> required="required" />
				</div>
			</div>
			<script>
	document.getElementById("time").onchange = function () {
		//Extract time array
		var time = document.getElementById("time").value.split(':');
		//Floor time minutes to closest value
		time[1] = (parseInt(time[1]/5)*5).toString().padStart(2, "0");
		//Set back value
		document.getElementById("time").value = time.join(':');
	}
			</script>
			<div>
				<div>
					<input type="submit" value="Afficher" />
					<input type="submit" name="download" value="Télécharger" />
					<input type="submit" name="download" value="iBug" />
				</div>
			</div>
		</form>
	</section>
</body>
</html>
<?php
	exit;
}

if (!empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] != 'GET' && !empty($_REQUEST['download']) && $_REQUEST['download'] == 'iBug') {
	header('Location: '.$_SERVER['REQUEST_URI'].'?'.http_build_query($_REQUEST));
	exit;
}

/**
 * Ausweis class
 */
class Ausweis {
	/**
	 * Fix date
	 */
	static function fixDate($date) {
		$return = preg_replace(
			[
				'%^([0-9]{4})-([0-9]{2})-([0-9]{2})$%',
				'%^([0-9]{2})/([0-9]{2})/([0-9]{4})$%',
				'%^([0-9]{2})/([0-9]{2})/([0-9]{2})$%',
				'%^([0-9]{2})([0-9]{2})([0-9]{4})$%',
				'%^([0-9]{2})([0-9]{2})([0-9]{2})$%'
			],
			[
				'\1-\2-\3',
				'\3-\2-\1',
				'20\3-\2-\1',
				'\3-\2-\1',
				'20\3-\2-\1'
			],
			$date
		);
		if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $return)) {
			die('Unable to fix date "'.$date.'" please use dd/mm/aaaa format');
		}
		return $return;
	}

	/**
	 * Fix time
	 */
	static function fixTime($time) {
		$return = preg_replace(
			[
				'%^([0-9]{2}):([0-9]{2})%',
				'%^([0-9]{2})h([0-9]{2})%',
				'%^([0-9]{2})([0-9]{2})%'
			],
			[
				'\1:\2',
				'\1:\2',
				'\1:\2'
			],
			$time
		);
		if (!preg_match('/^[0-9]{2}:[0-9]{2}$/', $return)) {
			die('Unable to fix time "'.$time.'" please use HH:ii format');
		}
		return $return;
	}

	/**
	 * Add ausweis attestation
	 */
	static function addAttestation($p, $reason, $firstname, $lastname, $birthdate, $birthplace, $address, $location, $date, $time) {
		//Set positions
		$pos = [];

		//Add page
		$p->AddPage();

		//Set label length
		$labelLength = 30;

		//Set line height
		$lineHeight = 7.9;

		//Set title height
		$titleHeight = 15;

		//Disable auto page break
		$p->SetAutoPageBreak(false, 0);

		//Set margins
		$p->SetMargins(23.8, 0);

		//Set y
		$p->SetY(12);

		//Set font
		$p->setFont('LiberationSerif', 'B', 17);

		//Addd title
		$p->Cell(0, 20, utf8_decode('ATTESTATION DE DÉPLACEMENT DÉROGATOIRE'), 0, 0, 'C');

		//Set y
		$p->SetY(28.5);

		//Set font
		$p->setFont('MicrosoftSansSerif', '', 10.5);

		//Add legal mention
		$p->Cell(0, 4, utf8_decode('En application du décret n°2020-1310 du 29 octobre 2020 prescrivant les mesures générales'), 0, 1, 'C');
		$p->Cell(0, 4, utf8_decode('nécessaires pour faire face à l\'épidémie de Covid19 dans le cadre de l\'état d\'urgence sanitaire'), 0, 1, 'C');

		//Set y
		$p->setY(40.25);

		//Add formal
		$p->Cell(0, 4, utf8_decode('Je soussigné(e),'), 0, 1, 'L');

		//Set y
		$p->setY(46.25);

		//Save name pos
		$posName = $p->getY();

		//Add employee
		$p->Cell(0, 8, utf8_decode('Mme/M. :'), 0, 1, 'L');

		//Save birth pos
		$posBirth = $p->getY();

		//Add birth
		$p->Cell(75, 8, utf8_decode('Né(e) le :'), 0, 0, 'L');
		$p->Cell(0, 8, utf8_decode('à :'), 0, 1, 'L');

		//Save address pos
		$posAddress = $p->getY();

		//Add address
		$p->Cell(0, 8, utf8_decode('Demeurant :'), 0, 1, 'L');

		//Set y
		$p->setY(71);

		//Add certification
		$p->Cell(0, 4.2, utf8_decode('certifie que mon déplacement est lié au motif suivant (cocher la case) autorisé par le décret'), 0, 1, 'L');
		$p->Cell(0, 4.2, utf8_decode('n°2020-1310 du 29 octobre 2020 prescrivant les mesures générales nécessaires pour faire face à'), 0, 1, 'L');
		$p->Cell(0, 4.2, utf8_decode('l\'épidémie de Covid19 dans le cadre de l\'état d\'urgence sanitaire¹ :'), 0, 1, 'L');

		//Jump line
		$p->Ln(3.5);

		//Set box size
		$boxSize = 5.85;

		//Save y
		$y = $p->getY();

		//Set margins
		$p->SetLeftMargin(37.5, 0);

		//Add travail
		$p->MultiCell(148, 4.25, utf8_decode('Déplacements entre le domicile et le lieu d\'exercice de l\'activité professionnelle ou un établissement d\'enseignement ou de formation, déplacements professionnels ne pouvant être différés², déplacements pour un concours ou un examen'), 0, 'J');

		//Save travail position
		$pos['travail'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add achats
		$p->MultiCell(148, 4.25, utf8_decode('Déplacements pour effectuer des achats de fournitures nécessaires à l\'activité professionnelle, des achats de première nécessité³ dans des établissements dont les activités demeurent autorisées, le retrait de commande et les livraisons à domicile'), 0, 'J');

		//Save achats position
		$pos['achats'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add sante
		$p->MultiCell(148, 4.25, utf8_decode('Consultations, examens et soins ne pouvant être ni assurés à distance et l\'achat de médicaments'), 0, 'J');

		//Save sante position
		$pos['sante'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add famille
		$p->MultiCell(148, 4.25, utf8_decode('Déplacements pour motif familial impérieux, pour l\'assistance aux personnes vulnérables et précaires ou la garde d\'enfants'), 0, 'J');

		//Save famille position
		$pos['famille'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add handicap
		$p->MultiCell(148, 4.25, utf8_decode('Déplacement des personnes en situation de handicap et leur accompagnant'), 0, 'J');

		//Save handicap position
		$pos['handicap'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add sport_animaux
		$p->MultiCell(148, 4.25, utf8_decode('Déplacements brefs, dans la limite d\'une heure quotidienne et dans un rayon maximal d\'un kilomètre autour du domicile, liés soit à l\'activité physique individuelle des personnes, à l\'exclusion de toute pratique sportive collective et de toute proximité avec d\'autres personnes, soit à la promenade avec les seules personnes regroupées dans un même domicile, soit aux besoins des animaux de compagnie'), 0, 'J');

		//Save sport_animaux position
		$pos['sport_animaux'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add convocation
		$p->MultiCell(148, 4.25, utf8_decode('Convocation judiciaire ou administrative et pour se rendre dans un service public'), 0, 'J');

		//Save convocation position
		$pos['convocation'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add missions
		$p->MultiCell(148, 4.25, utf8_decode('Participation à des missions d\'intérêt général sur demande de l\'autorité administrative'), 0, 'J');

		//Save missions position
		$pos['missions'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Jump line
		$p->Ln(6.5);

		//Save y
		$y = $p->getY();

		//Add enfants
		$p->MultiCell(148, 4.25, utf8_decode('Déplacement pour chercher les enfants à l\'école et à l\'occasion de leurs activités périscolaires'), 0, 'J');

		//Save enfants position
		$pos['enfants'] = $y + ($p->getY() - $y) / 2 - $boxSize / 2;

		//Set line width
		$p->SetLineWidth(0.5);

		//Add boxes
		foreach($pos as $k => $v) {
			$p->Rect(27.75, $v, 5.85, 5.85);
		}

		//Set margins
		$p->SetLeftMargin(23.9, 0);

		//Set y
		$p->SetY('-64.9', true);

		//Save location pos
		$posLocation = $p->getY();

		//Add creation location
		$p->Cell(0, 4, utf8_decode('Fait à :'), 0, 1, 'L');

		//Set y
		$p->SetY('-56.9', true);

		//Save date pos
		$posDate = $p->getY();

		//Add creation date
		$p->Cell(60.1, 4, utf8_decode('Le :'), 0, 0, 'L');
		$p->Cell(0, 4, utf8_decode('à :'), 0, 1, 'L');

		//Set y
		$p->SetY('-51', true);

		//Set font
		$p->setFont('MicrosoftSansSerif', '', 10);

		//Add creation mentions
		$p->Cell(0, 4, utf8_decode('(Date et heure de début de sortie à mentionner obligatoirement)'), 0, 1, 'L');

		//Set font
		$p->setFont('MicrosoftSansSerif', '', 10.5);

		//Set y
		$p->SetY('-45.3', true);

		//Add signature
		$p->Cell(12, 4, utf8_decode('Signature :'), 0, 0, 'L');
		$p->Ln($lineHeight);

		//Place footer
		$p->SetY('-33.25', true);

		//Set font
		$p->setFont('MicrosoftSansSerif', '', 8);

		//Add notice
		$p->Cell(12.5, 3.5, utf8_decode('¹'), 0, 0, 'C');
		$p->MultiCell(0, 3.5, utf8_decode('Les personnes souhaitant bénéficier de l\'une de ces exceptions doivent se munir s\'il y a lieu, lors de leurs'."\n".'déplacements hors de leur domicile, d\'un document leur permettant de justifier que le déplacement considéré entre'."\n".'dans le champ de l\'une de ces exceptions'), 0, 'L');
		$p->Ln(0);
		$p->Cell(12.5, 3.5, utf8_decode('²'), 0, 0, 'C');
		$p->MultiCell(0, 3.5, utf8_decode('A utiliser par les travailleurs non-salariés, lorsqu\'ils ne peuvent disposer d\'un justificatif de déplacement établi par leur'."\n".'employeur'), 0, 'L');
		$p->Ln(0);
		$p->Cell(12.5, 3.5, utf8_decode('³'), 0, 0, 'C');
		$p->MultiCell(0, 3.5, utf8_decode('Y compris les acquisitions à titre gratuit (distribution de denrées alimentaires...) et les déplacements liés à la'."\n".'perception de prestations sociales et au retrait d\'espèces'), 0, 'L');
		$p->Ln(0);

		//Set font
		$p->setFont('Helvetica', '', 11);

		//Set y
		$p->setXY(41, $posName);

		//Add name
		$p->Cell(0, 8, utf8_decode($firstname.' '.$lastname), 0, 0, 'L');

		//Set y
		$p->setXY(41, $posBirth);

		//Fix birthdate
		$birthdate = self::fixDate($birthdate);

		//Add birth
		$p->Cell(63, 8, utf8_decode(date('d/m/Y', strtotime($birthdate))), 0, 0, 'L');
		$p->Cell(0, 8, utf8_decode($birthplace), 0, 0, 'L');

		//Set y
		$p->setXY(46, $posAddress);

		//Add address
		$p->Cell(0, 7, utf8_decode($address), 0, 0, 'L');

		//Set xy
		$p->setXY(27.75, $pos[$reason]);

		//Set y
		$p->setXY(36, $posLocation);

		//Add location
		$p->Cell(0, 4, utf8_decode($location), 0, 0, 'L');

		//Set y
		$p->setXY(31, $posDate);

		//Fix date
		$date = self::fixDate($date);

		//Fix time
		$time = self::fixTime($time);

		//Add date
		$p->Cell(58, 4, utf8_decode(date('d/m/Y', strtotime($date))), 0, 0, 'L');
		$p->Cell(0, 4, utf8_decode($time), 0, 0, 'L');

		//Set xy
		$p->setXY(27.75, $pos[$reason]);

		//Set font
		$p->setFont('Helvetica', '', 16);

		//Add cross
		$p->Cell(0, 6.5, 'X', 0, 0, 'L');

		//Set delay
		$delay = rand(30, 60);

		//Set qrdata
		$qrData = [
			'Cree le: '.date('d/m/Y \a H\hi', strtotime('-'.$delay.' minutes', strtotime($date.' '.$time))),
			'Nom: '.$lastname,
			'Prenom: '.$firstname,
			'Naissance: '.date('d/m/Y', strtotime($birthdate)).' a '.$birthplace,
			'Adresse: '.$address,
			'Sortie: '.date('d/m/Y \a H:i', strtotime($date.' '.$time)),
			'Motifs: '.$reason
		];

		//Set qr text
		$qrText = implode(";\n ", $qrData);

		//Set qr file
		$qrFile = tmpfile();

		//Set qr path
		$qrPath = stream_get_meta_data($qrFile)['uri'];

		//Output in png
		#ob_start();
		QRcode::png($qrText, $qrPath, QR_ECLEVEL_M, 6, 4, false);
		#$qrPng = ob_get_contents();
		#ob_end_clean();

		//Add qrPng
		$p->Image($qrPath, 146, 221, 40, 40, 'PNG');

		//Add page
		//XXX: add the attestation de déplacement dérogatoire page
		$p->AddPage();

		//Add qrPng
		$p->Image($qrPath, 12.5, 12.5, 117, 0, 'PNG');
		$p->Ln();
	}

	/**
	 * Add ausweis quittance
	 */
	static function addQuittance($p, $firstname, $lastname, $address, $titleowner, $firstowner, $lastowner, $addressowner, $sign, $loyer, $charge) {
		//Add employer page
		$p->AddPage();

		//Set label length
		$labelLength = 80;

		//Set line height
		$lineHeight = 15;

		//Set margins
		$p->SetMargins(30, 0);

		//Disable auto page break
		$p->SetAutoPageBreak(false, 0);

		//Jump line
		$p->SetY($lineHeight);

		//Set font
		$p->setFont('Helvetica', 'B', 18);

		//Addd title
		$p->Cell(0, 20, utf8_decode('QUITTANCE DE LOYER'), 0, 0, 'C');

		//Jump line
		$p->Ln($titleHeight);

		//Set font
		$p->setFont('Times', '', 9);

		//Add legal mention
		$p->Cell(0, 5, utf8_decode('Quittance de loyer pour la période du '.date('01/m/Y', strtotime('-1 month')).' au '.date('d/m/Y', strtotime('-1 day', strtotime('first day of now')))), 0, 0, 'C');
		$p->Ln();

		//Jump line
		$p->Ln($lineHeight);

		//Set font
		$p->setFont('Times', 'BU', 10);

		//Add formal
		$p->Cell($labelLength, 5, utf8_decode('Bailleur :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode('Colocataire :'), 0, 0, 'L');

		//Jump line
		$p->Ln();

		//Set font
		$p->setFont('Times', '', 9);

		//Add names
		$p->Cell($labelLength, 5, utf8_decode($titleowner.' '.$firstowner.' '.$lastowner), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($firstname.' '.$lastname), 0, 0, 'L');
		$p->Ln();
		$p->Cell($labelLength, 5, utf8_decode($addressowner), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($address), 0, 0, 'L');

		//Add formal
		$p->Ln($lineHeight*1.5);

		//Add date
		$p->Cell(0, 5, utf8_decode('Angers le '.date('07/m/Y', strtotime('-1 month'))), 0, 0, 'R');

		//Jump line
		$p->Ln($lineHeight);

		//Set font
		$p->setFont('Times', 'BU', 10);

		//Add formal
		$p->Cell(0, 5, utf8_decode('Adresse de location :'), 0, 0, 'L');
		$p->Ln();

		//Set font
		$p->setFont('Times', 'B', 9);

		//Add address
		$p->Cell(0, 5, utf8_decode($address), 0, 0, 'L');

		//Add formal
		$p->Ln($lineHeight);

		//Set font
		$p->setFont('Times', '', 10);

		//Set total
		$total = $loyer + $charge;

		//Add mention
		$p->MultiCell(0, 5, utf8_decode('Je soussigné '.$titleowner.' '.$firstowner.' '.$lastowner.', usufruitier du logement situé au '.$address.', déclare avoir reçu de '.$firstname.' '.$lastname.', colocataire de ce logement, la somme de '.str_replace('.', ',', sprintf('%.2f', $total)).' euros correspondant au loyer et aux charges dus pour la période allant du '.date('01/m/Y', strtotime('-1 month')).' au '.date('d/m/Y', strtotime('-1 day', strtotime('first day of now'))).'. Cette somme correspond aux montants suivants :'), 0, 'J');

		//Add formal
		$p->Ln($lineHeight);

		//Add formal
		$p->Cell(0, 5, utf8_decode('Loyer hors charge :'), 0, 0, 'L');
		$p->Ln();

		//Set font
		$p->setFont('Times', '', 9);

		$p->Cell(0, 5, utf8_decode(str_replace('.', ',', sprintf('%.2f', $loyer)).' euros'), 0, 0, 'L');

		//Add formal
		$p->Ln($lineHeight);

		//Set font
		$p->setFont('Times', '', 10);

		//Add formal
		$p->Cell(0, 5, utf8_decode('Provision pour charges :'), 0, 0, 'L');
		$p->Ln();

		//Set font
		$p->setFont('Times', '', 9);

		$p->Cell(0, 5, utf8_decode(str_replace('.', ',', sprintf('%.2f', $charge)).' euros'), 0, 0, 'L');

		//Add formal
		$p->Ln($lineHeight);

		//Set font
		$p->setFont('Times', 'BU', 10);

		//Add formal
		$p->Cell(0, 5, utf8_decode('Somme totale reçue :'), 0, 0, 'L');
		$p->Ln();

		//Set font
		$p->setFont('Times', 'B', 9);

		$p->Cell(0, 5, utf8_decode(str_replace('.', ',', sprintf('%.2f', $total)).' euros'), 0, 0, 'L');

		//Add formal
		$p->Ln($lineHeight);

		//Set font
		$p->setFont('Times', '', 10);

		//Add formal
		$p->Cell(0, 5, utf8_decode('Date du paiement :'), 0, 0, 'L');
		$p->Ln();

		//Set font
		$p->setFont('Times', '', 9);
		$p->Cell(0, 5, utf8_decode(date('05/m/Y', strtotime('-1 month')).' par virement'), 0, 0, 'L');

		//Add formal
		$p->Ln($lineHeight);

		//Set Y
		$p->setY(-60);

		//Set font
		$p->setFont('Times', '', 10);

		//Add creation location
		$p->Cell(0, 5, utf8_decode('Fait à Angers le '.date('07/m/Y', strtotime('-1 month'))), 0, 0, 'L');
		$p->Ln();

		//Add signature
		$p->Cell(12, 5, utf8_decode('Signature :'), 0, 0, 'L');
		$p->Ln();

		//Add sign
		$p->Image($sign, 45, 245, 30, 0, 'PNG');

		//Set font
		$p->setFont('Times', '', 10);

		//Set Y
		$p->setY(-30);

		//Add legal
		$p->MultiCell(0, 5, utf8_decode('La présente quittance est valable sous réserve d\'encaissement des sommes indiquées et de tous droits ou instances en cours. Elle n\'est libératoire que pour la période indiquée et n\'implique pas présomption de paiement des échéances antérieures qui pourraient rester dues.'), 0, 'J');
	}

	/**
	 * Add ausweis employer
	 */
	static function addEmployer($p, $employerTitle, $employerFunction, $employerCompany, $employerCity, $logo, $stamp, $sign, $workplaces, $firstname, $lastname, $birthdate, $birthplace, $address, $function) {
		//Add conveyances
		$conveyances = [
			'Bicyclette',
			'Cyclomoteur',
			'Marche',
			'Transport en commun',
			'Voiture'
		];

		//Add employer page
		$p->AddPage();

		//Set label length
		$labelLength = 51.75;

		//Set line height
		$lineHeight = 7.5;

		//Set title height
		$titleHeight = 18.5;

		//Set margins
		$p->SetMargins(25, 0);

		//Disable auto page break
		$p->SetAutoPageBreak(false, 0);

		//Jump line
		#$p->Ln($titleHeight);
		$p->SetY($titleHeight);

		//Set font
		$p->setFont('TrebuchetMS', 'B', 16);

		//Addd title
		$p->Cell(0, 20, utf8_decode('JUSTIFICATIF DE DÉPLACEMENT PROFESSIONNEL'), 0, 0, 'C');

		//Jump line
		$p->Ln();

		//Set font
		$p->setFont('Times', '', 10);

		//Add legal mention
		$p->Cell(0, 5, utf8_decode('En application du décret n°2020-1310 du 29 octobre 2020 prescrivant les mesures générales nécessaires pour'), 0, 1, 'C');
		$p->Cell(0, 5, utf8_decode('faire face à l\'épidémie de Covid19 dans le cadre de l\'état d\'urgence sanitaire'), 0, 1, 'C');

		//Jump line
		$p->Ln($lineHeight);

		//Add formal
		$p->Cell(0, 5, utf8_decode('Je soussigné(e),'), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Add name
		$p->Cell($labelLength, 5, utf8_decode('Nom et prénom de l\'employeur :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($employerTitle), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Add functions
		$p->Cell($labelLength, 5, utf8_decode('Fonctions :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($employerFunction), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Add certification
		$p->MultiCell(0, 5, utf8_decode('Certifie que les déplacements de la personne ci-après, entre son domicile et le ou les lieux d\'exercice de son activité professionnelle ou à l\'occasion de l\'exercice de ses fonctions, ne peuvent être différés ou sont indispensables à l\'exercice d\'activités ne pouvant être organisées sous forme de télétravail :'), 0, 'J');

		//Jump line
		$p->Ln($lineHeight-5);

		//Add employee
		$p->Cell($labelLength, 5, utf8_decode('Nom :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($lastname), 0, 0, 'L');
		$p->Ln($lineHeight);
		$p->Cell($labelLength, 5, utf8_decode('Prénom :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($firstname), 0, 0, 'L');
		$p->Ln($lineHeight);
		$p->Cell($labelLength, 5, utf8_decode('Date de naissance :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($birthdate), 0, 0, 'L');
		$p->Ln($lineHeight);
		$p->Cell($labelLength, 5, utf8_decode('Lieu de naissance :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($birthplace), 0, 0, 'L');
		$p->Ln($lineHeight);
		$p->Cell($labelLength, 5, utf8_decode('Adresse du domicile :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($address), 0, 0, 'L');
		$p->Ln($lineHeight);
		$p->Cell($labelLength, 5, utf8_decode('Nature de l\'activité professionnelle :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($function), 0, 0, 'L');
		$p->Ln($lineHeight);

		//Add conveyances
		$p->Cell($labelLength, 5, utf8_decode('Moyens de déplacement :'), 0, 0, 'L');
		$p->Cell(0, 5, /*'        '.*/implode(', ', $conveyances), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Add validity
		$p->Cell($labelLength, 5, utf8_decode('Durée de validité :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode('6 mois'), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Add workplaces
		$p->Cell(0, 5, utf8_decode('Lieux d\'exercice de l\'activité professionnelle :'), 0, 0, 'L');
		foreach($workplaces as $siret => $location) {
			$p->Ln(4);
			#$p->cell($labelLength/1.5, 5, '        '.$siret.' :', 0, 0, 'l');
			$p->cell(0, 5, '        '.utf8_decode($location), 0, 0, 'l');
		}

		//Jump line
		#$p->Ln($lineHeight*2);

		//Place footer
		$p->SetY('-65', true);

		//Add employer name
		$p->Cell($labelLength, 5, utf8_decode('Nom et cachet de l\'employeur :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($employerCompany), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Add sign location
		$p->Cell($labelLength, 5, utf8_decode('Fait à :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode($employerCity), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Add sign date
		$p->Cell($labelLength, 5, utf8_decode('Le :'), 0, 0, 'L');
		$p->Cell(0, 5, utf8_decode('02 novembre 2020'), 0, 0, 'L');

		//Jump line
		$p->Ln($lineHeight);

		//Place footer
		$p->SetY('-40', true);

		//Set font
		$p->setFont('MicrosoftSansSerif', '', 7);

		//Add notice
		$p->Cell(0, 4, utf8_decode('Ce document, établi par l\'employeur, est suffisant pour justifier les déplacements professionnels d\'un salarié, qu\'il s\'agisse :'), 0, 0, 'L');
		$p->Ln($lineHeight/2);
		$p->Cell(0, 4, utf8_decode('- du trajet habituel entre le domicile et le lieu de travail du salarié ou des déplacements entre les différents lieux de travail lorsque la nature'), 0, 0, 'L');
		$p->Ln($lineHeight/2);
		$p->Cell(0, 4, utf8_decode('de ses fonctions l\'exige'), 0, 0, 'L');
		$p->Ln($lineHeight/2);
		$p->Cell(0, 4, utf8_decode('- des déplacements de nature professionnelle qui ne peuvent pas être différés, à la demande de l\'employeur.'), 0, 0, 'L');
		$p->Ln($lineHeight/2);
		$p->Cell(0, 4, utf8_decode('Il n\'est donc pas nécessaire que le salarié se munisse, en plus de ce justificatif, de l\'attestation de déplacement dérogatoire.'), 0, 0, 'L');
		$p->Ln($lineHeight/2);
		$p->Cell(0, 4, utf8_decode('Les travailleurs non-salariés, pour lesquels ce justificatif ne peut être établi, doivent en revanche se munir de l\'attestation de déplacement'), 0, 0, 'L');
		$p->Ln($lineHeight/2);
		$p->Cell(0, 4, utf8_decode('dérogatoire en cochant le premier motif de déplacement'), 0, 0, 'L');

		//Add pictures
		$p->Image($logo, 10, 8, 40, 0, 'PNG');
		$p->Image($stamp, 130, 210, 60, 0, 'PNG');
		$p->Image($sign, 110, 215, 25, 0, 'PNG');
	}
}

/**
 * Prefilled data
 */
$data = [];

/**
 * Bnp
 */
if ($_REQUEST['type'] == 'bnp') {
	//Set employer
	$data['employer'] = [
		'title' => 'Jean-Laurent Bonnafé',
		'function' => 'Administrateur Directeur Général de BNP Paribas',
		'company' => 'BNP PARIBAS',
		'address' => '16 Boulevard des Italiens 75009 Paris',
		'city' => 'Paris',
		'vat' => 'FR76662042449'
	];

	//Set workplaces
	$data['workplaces'] = [
		//TODO: add others...
		66204244932405 => '37 place du Marché St Honoré 75001 Paris',
		66204244932355 => '36b avenue de l\'Opéra 75002 Paris',
		66204244920376 => '67 rue de Bretagne 75003 Paris',
		66204244919998 => '48 rue des Archives 75004 Paris',
		66204244915558 => '50 boulevard de Saint Marcel 75005 Paris',
		66204244920368 => '1 rue de Medicis 75006 Paris',
		66204244941596 => '64 rue de Sèvres 75007 Paris',
		66204244943238 => '10 boulevard Malesherbes 75008 Paris',
		66204244900014 => '16 boulevard des Italiens 75009 Paris',
		66204244932454 => '150 rue du fbg Poissonniere 75010 Paris',
		66204244941539 => '41 rue Basfroi 75011 Paris',
		66204244943733 => '47 boulevard Diderot 75012 Paris',
		66204244920897 => '109 rue de Tolbiac 75013 Paris',
		66204244941265 => '160 boulevard Macdonald 75019 Paris',
		66204244925110 => '4 place Saint Fargeau 75020 Paris',
		00000000000000 => 'Toute l\'Île-de-France',
		99999999999999 => 'Toute la France'
	];

	//Set pictures
	$data['sign'] = '../picture/ausweis/bnp/sign.png';
	$data['stamp'] = '../picture/ausweis/bnp/stamp.png';
	$data['logo'] = '../picture/ausweis/bnp/logo.png';

	//Set reason
	$data['reason'] = 'travail';
/**
 * Poltronesofa
 */
} elseif ($_REQUEST['type'] == 'poltrone') {
	//Set employer
	$data['employer'] = [
		'title' => 'M Renzo Ricci',
		'function' => 'Président',
		'company' => 'POLTRONESOFA \'FRANCE',
		'address' => '6 Rue Jean Jaures 92800 Puteaux',
		'city' => 'Puteaux',
		'vat' => 'FR88422036905'
	];

	//Set workplaces
	$data['workplaces'] = [
		42203690500020 => 'Place du Marché St Honoré 75001 Paris',
		42203690500558 => '72 Boulevard de Sébastopol 75003 Paris',
		42203690500756 => 'Avenue de Fontainebleau 94320 Thiais',
		//42203690500749 => 'Cc Opensky Lot A03 78200 Buchelay',
		//42203690500681 => 'L\'oseraie 95520 Osny',
		42203690500533 => '1 rue de la Mare au Chanvre 91700 Sainte-Geneviève-des-Bois',
		42203690500483 => '23 rue Alexandre Chatrian 77410 Claye-Souilly',
		42203690500434 => 'Route Nationale 10 78210 Coignières',
		42203690500186 => 'Avenue Henri Barbusse 78340 Les Clayes-sous-Bois',
		42203690500152 => 'La Saussaie Beauclair 93110 Rosny-sous-Bois',
		42203690500095 => '234 Boulevard du Havre 95220 Pierrelaye',
		00000000000000 => 'Toute l\'Île-de-France',
		99999999999999 => 'Toute la France'
	];

	//Set pictures
	$data['sign'] = '../picture/ausweis/poltrone/sign.png';
	$data['stamp'] = '../picture/ausweis/poltrone/stamp.png';
	$data['logo'] = '../picture/ausweis/poltrone/logo.png';

	//Set reason
	$data['reason'] = 'travail';
/**
 * Sport
 */
} elseif ($_REQUEST['type'] == 'sport_animaux') {
	//Set reason
	$data['reason'] = 'sport_animaux';
	$data['sign'] = '../picture/ausweis/bnp/sign.png';
/**
 * Achats
 */
} elseif ($_REQUEST['type'] == 'achats') {
	//Set reason
	$data['reason'] = 'achats';
	$data['sign'] = '../picture/ausweis/bnp/sign.png';
/**
 * Others:
 * - travail: 578,
 * - achats: 533,
 * - sante: 477,
 * - famille: 435,
 * - handicap: 396,
 * - sport_animaux: 358,
 * - convocation: 295,
 * - missions: 255,
 * - enfants: 211,
 */
} elseif (in_array($_REQUEST['type'], $reasons)) {
	//Set reason
	$data['reason'] = $_REQUEST['type'];
/**
 * Unknown
 */
} else {
	die('TODO');
}

//Set filename
//XXX: was Ausweis_ now we use Travail_firstname_lastname.pdf
$fileName = ucfirst($data['reason']).'_'.preg_replace(['/[^a-zA-Z0-9]/', '/__+/'], ['_', '_'], $_REQUEST['firstname'].'_'.$_REQUEST['lastname']).'_'.date('Ymd_Hi', strtotime(Ausweis::fixDate($_REQUEST['date']).' '.Ausweis::fixTime($_REQUEST['time']))).'.pdf';

//Create pdf object
$p = new FPDF('P', 'mm', 'A4');

//Add marianne bold
#$p->AddFont('Marianne-Bold', '', 'marianne-bold.php');
#$p->AddFont('Marianne-Bold', 'B', 'marianne-bold.php');
#$p->AddFont('Marianne-Bold', 'BI', 'marianne-bold.php');
#$p->AddFont('Marianne-Bold', 'I', 'marianne-bold.php');

//Add mariane regular
#$p->AddFont('Marianne-Regular', '', 'marianne-regular.php');
#$p->AddFont('Marianne-Regular', 'B', 'marianne-regular.php');
#$p->AddFont('Marianne-Regular', 'BI', 'marianne-regular.php');
#$p->AddFont('Marianne-Regular', 'I', 'marianne-regular.php');

//Add trebuchet ms
$p->AddFont('TrebuchetMS', '', 'trebuc.php');
$p->AddFont('TrebuchetMS', 'B', 'trebucb.php');
$p->AddFont('TrebuchetMS', 'BI', 'trebucbi.php');
$p->AddFont('TrebuchetMS', 'I', 'trebuci.php');

//Add liberation serif
$p->AddFont('LiberationSerif', '', 'liberationserif.php');
$p->AddFont('LiberationSerif', 'B', 'liberationserifb.php');
$p->AddFont('LiberationSerif', 'BI', 'liberationserifbi.php');
$p->AddFont('LiberationSerif', 'I', 'liberationserifi.php');

//Add microsoft sans serif
$p->AddFont('MicrosoftSansSerif', '', 'micross.php');
$p->AddFont('MicrosoftSansSerif', 'B', 'micross.php');
$p->AddFont('MicrosoftSansSerif', 'BI', 'micross.php');
$p->AddFont('MicrosoftSansSerif', 'I', 'micross.php');

//Set creator
$p->SetTitle('Justificatif de déplacement professionnel', true);
$p->SetCreator($_SERVER['PHP_SELF'], true);
$p->SetAuthor('Französischer Kommandantur', true);
$p->SetSubject('Verkehrsausweis', true);

/**
 * Add attestation
 */
Ausweis::addAttestation(
	$p,
	$data['reason'],
	$_REQUEST['firstname'],
	$_REQUEST['lastname'],
	$_REQUEST['birthdate'],
	$_REQUEST['birthplace'],
	$_REQUEST['address'].' '.$_REQUEST['zipcode'].' '.$_REQUEST['city'],
	$_REQUEST['location'],
	$_REQUEST['date'],
	$_REQUEST['time']
);

/**
 * Employer attestation type
 */
//XXX: add the justificatif de déplacement professionnel page
if (!empty($data['employer'])) {
	/**
	 * Add employer attestation
	 */
	Ausweis::addEmployer(
		$p,
		$data['employer']['title'],
		$data['employer']['function'],
		$data['employer']['company'],
		$data['employer']['city'],
		$data['logo'],
		$data['stamp'],
		$data['sign'],
		$data['workplaces'],
		$_REQUEST['firstname'],
		$_REQUEST['lastname'],
		$_REQUEST['birthdate'],
		$_REQUEST['birthplace'],
		$_REQUEST['address'].' '.$_REQUEST['zipcode'].' '.$_REQUEST['city'],
		$_REQUEST['function']
	);
}

/**
 * Personnal sport and buy attestation type
 */
if ($data['reason'] == 'sport_animaux' || $data['reason'] == 'achats') {
	/**
	 * Add quittance attestation
	 */
	Ausweis::addQuittance(
		$p,
		$_REQUEST['firstname'],
		$_REQUEST['lastname'],
		$_REQUEST['address'].' '.$_REQUEST['zipcode'].' '.$_REQUEST['city'],
		'M.',
		'Jean',
		'Larivière',
		'6 chemin Bas des Plaines 49000 Angers',
		'../picture/ausweis/bnp/sign.png',
		705.55,
		125.00,
	);
}

//Close document
$p->Close();

//Send common headers
header('Content-Type: application/pdf');

//Send download headers
if (!empty($_REQUEST['download'])) {
	if ($_REQUEST['download'] == 'iBug') {
		header('Content-Type: application/octet-stream');
	}
	header('Content-Disposition: attachment; filename="'.rawurlencode($fileName).'"');
//Send display headers
} else {
	header('Content-Disposition: inline; filename="'.rawurlencode($fileName).'"');
}

//Send remaining headers
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');

//Save output
$output = $p->Output('S');

//Send content-length
header('Content-Length: '.strlen($output));

//Display the pdf
echo $output;
