<?php

namespace Paheko;

require_once __DIR__ . '/_inc.php';
$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);
$users = new Users\Users;

f(['id' => 'required|numeric']);
$id = (int) qg('id');
$sign_tag = UserTemplate\Functions::signature();

// Vérification que le document existe
if (!$f = $facture->get($id))
{
	throw new UserException("Ce document n'existe pas.");
}

$moyen_paiement = $facture->getMoyenPaiement($f->moyen_paiement);

// Récupération infos membre
try
{
	if ($f->receveur_membre)
	{
		$c = $users->get($f->receveur_id);
		// l'identité du membre peut être redéfinie dans la configuration des membres
		$name_fields = \Paheko\Users\DynamicFields::getNameFields();
		array_walk($name_fields, function(&$elem) use ($c) {
			$elem = $c->$elem ?? '** ABSENT **';
		});
		$c->nom = implode(" ", $name_fields);

		// adresse, code postal et ville peuvent être redéfini(e)s dans la configuration du plugin
		$adresse_client = $plugin->getConfig('adresse_client');
		if ($adresse_client != null && $c->$adresse_client != null) { $c->adresse = $c->$adresse_client; }
		$code_postal_client = $plugin->getConfig('code_postal_client');
		if ($code_postal_client != null && $c->$code_postal_client != null) { $c->code_postal = $c->$code_postal_client; }
		$ville_client = $plugin->getConfig('ville_client');
		if ($ville_client != null && $c->$ville_client != null) { $c->ville = $c->$ville_client; }

		foreach(['ville','code_postal','adresse'] as $v)
		{
			if($c->$v == '')
			{
				$c->$v = '[À RENSEIGNER DANS LA FICHE MEMBRE]';
			}
		}
	}
	else
	{
		$c = $client->get($f->receveur_id);
	}
}
catch(UserException $e)
{
	$form->addError($e);
}

// Formatage dates
$emission = $f->date_emission->format('d/m/Y');
if (isset($f->date_echeance))
{
	$echeance = $f->date_echeance->format('d/m/Y');
}


// -- Création du PDF

// Génération factures, devis
switch ($f->type_facture)
{
	case FACT:
	$doc = 'Facture n° '. $f->numero;
    $txtemis = $doc . " - Émise le " . $emission;
    $txtdest = "Adressée à :";
	break;
	case DEVIS:
	$doc = 'Devis n° '. $f->numero;
    $txtemis = $doc . " - Émis le " . $emission;
    $txtdest = "Adressé à :";
	break;
}

// utiliser l'adresse configurée dans le plugin sinon celle de l'asso sinon rien !
if ($plugin->getConfig('rue_asso') != null &&
    $plugin->getConfig('cp_asso') != null &&
    $plugin->getConfig('ville_asso') != null)
{
    $adresse =
        (($plugin->getConfig('numero_rue_asso') != null) ? $plugin->getConfig('numero_rue_asso') . " " : "") .
        $plugin->getConfig('rue_asso') . "<br>" .
        $plugin->getConfig('cp_asso') . " " .
        $plugin->getConfig('ville_asso');
}
else if ($config->get('org_address') != null)
{
    $adresse = str_replace("\n", '<br>', $config->get('org_address'));
}
else {
    $adresse = "";
}

$logo='';
if ($plugin->getConfig('logo')) {
	$logo = '<img id="logo" src="' . $config->fileURL('logo') . '" />';
}
$asso =
	// 'Émis par :<br><br>'.
	'<b>'.$config->get('org_name')."</b><br>".
	$adresse ."<br>".
	(($t = $plugin->getConfig('rna_asso'))?"RNA : $t<br>":'').
    (($t = $plugin->getConfig('siret_asso'))?"SIRET : " . implode(' ', str_split($t, 3)) . "<br>":'').
	(($t = $config->get('email_asso'))?"Email : $t<br>":'').
	(($t = $config->get('site_asso'))?"Site web : $t<br>":'');

$receveur =
	$txtdest.'<br>'.
	'<b>'.$c->nom.'</b><br>'.
	$c->adresse."<br>".
	$c->code_postal.' '.$c->ville."<br>".
    (($t = $c->siret)?"SIREN/SIRET : " . implode(' ', str_split($t, 3)) . "<br>":'').
	(($t = $c->email)?"Email : $t<br>":'').
	(($t = $c->telephone)?"Tel : $t<br>":'');

$total = Utils::money_format($f->total, ',', ' ');

// Devis et facture
{
	$echeance = ($f->type_facture?'Échéance de paiement':'Échéance du devis')." : ".$echeance;
	$reglee = !$f->reglee?'Cette facture est en attente de règlement.':'Cette facture a été réglée.';
	$footer = str_replace("\n", '<br>', $plugin->getConfig('footer') ?? '[Pied de page à configurer]');
	$ttc = $plugin->getConfig('ttc') ? 'TTC':'HT';

	// Génération du contenu de la facture
	ob_start();
	echo <<<EOF
<div class="h2">
    <span>Contenu</span> - $doc
</div>
<hr>

<table class="contenu">
    <thead>
	<tr>
	    <th>
		Désignations
	    </th>
	    <th>
		Prix
	    </th>
	</tr>
    </thead>
    <tbody>
EOF;

	$i = 1;
	foreach($f->contenu as $k=>$v)
	{
		echo '<tr><td>';
		echo str_replace("\n", '<br>', $v['designation']);
		echo '</td><td>';
		echo Utils::money_format($v['prix'], ',', ' ') .' €';
		echo '</td></tr>';
		$i++;
	}

	echo <<<EOF
    </tbody>
    <tfoot>
	<tr>
	<td><b>Total</b><br>Net à payer</td>
	<td><b>$total €</b><br>({$ttc})</td>
	</tr>
    </tfoot>
</table>
<footer>
    <div class="h2"><span>Détails</span></div>
    <hr>

    $echeance <br>
    $reglee
    Moyen de paiement : $moyen_paiement

    <p>
	$footer
    </p>
</footer>
EOF;

	$content = ob_get_clean();

}

//-- Layout du document

ob_start();
echo <<<EOF
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>{$doc}_{$emission}</title>
		<style>
			@page {
				size: A4 portrait;
				margin: 0;
			}

			body {
				padding: 4mm;
				font-family: Helvetica, Arial, sans;
				font-size: 10pt;
				background: white;
			}

			.titre {
				text-align: center;
				font-size: 8pt;
				margin-bottom: 6mm;
				margin-top: 0mm;
			}
			.h2 {
				margin: 20px 20px 0px 20px;
			}
			.h2 span {
				font-weight: bold;
				font-size: 14pt;
			}
			hr {
				margin: 5px 0px 15px 0px;
				border: none;
				border-top: 1px solid;
			}
			.adressage {
				font-size: 11pt;
				margin: auto;
			}
			.adressage td {
				width: 40%;
				vertical-align: top;
			}
			.adressage td#logo {
				width: 20%;
				vertical-align: top;
			}
			.adressage img#logo {
				height : 3cm;
			}

			.contenuTexte {
				padding: 0 6mm;
			}

			.contenu {
				width: 100%;
			}

			.contenu td, .contenu th {
				vertical-align: top;
				padding: 8px 10px;
				margin : 0px;
				border-collapse: collapse;
			}

			.contenu tr th, .contenu tr td {
				text-align: right;
				width: 16%;
			}
			.contenu tr td:nth-child(1), .contenu tr th:nth-child(1) {
				text-align: left;
				width: 84%;
			}

			.contenu thead tr, .contenu tfoot tr {
				background-color: #CCE;
				border: 10px solid black;
			}
			.contenu tbody tr:nth-child(even) {
				background-color: #DDF !important;
			}
			.contenu tfoot {
				display: table-row-group;
			}

			footer {
				bottom: 0;
				margin: 14mm 0;
				width: inherit;
				font-size: 9pt;
			}
		</style>
	</head>
	<body>
		<p class="titre">
		$txtemis
		</p>

		<table class="adressage">
			<tr>
				<td id="logo">$logo</td>
				<td>$asso</td>
				<td>$receveur</td>
			</tr>
		</table>
		<br>
		$content
	</body>
</html>
EOF;

$html = ob_get_clean();


if(qg('d') !== null)
{
	$filename = 'Print';
	if (preg_match('!<title>(.*)</title>!U', $html, $match)) {
		$filename = trim($match[1]);
	}

	header('Content-type: application/pdf');
	header(sprintf('Content-Disposition: attachment; filename="%s.pdf"', Utils::safeFileName($filename)));
	Utils::streamPDF($html);
}
else
{
	echo $html;
}