<?php
session_start();
include("config.php");
require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf();

ob_start();
$back = $bdd->query("SELECT * FROM documents WHERE id='".$_GET['id']."'");
$facture = $back->fetch();
if($facture['type'] != "bre"){
	$_GET['valeur'] = "1";
}
$back = $bdd->query("SELECT * FROM companies WHERE id='".$facture['company']."'");
$company = $back->fetch();
$req = $bdd->prepare("UPDATE printoptions SET signature='".$_GET['signature']."',header='".$_GET['header']."',ice='".$_GET['ice']."',valeur='".$_GET['valeur']."',label='".$_GET['label']."',d1='".$_GET['d1']."',d2='".$_GET['d2']."',d3='".$_GET['d3']."',d4='".$_GET['d4']."',d5='".$_GET['d5']."',d6='".$_GET['d6']."'");
$req->execute();
?>
<!DOCTYPE html>
<html lang="zxx">
	<head>
		<meta charset="utf-8">
		<style>
			@page {
				<?php
				if(isset($_GET['header'])){
					if($_GET['header'] == "1"){
						?>
				margin:180px 25px 280px 25px;
						<?php
					}
					elseif($_GET['header'] == "0"){
						?>
				margin:180px 25px 280px 25px;
						<?php						
					}
				}
				else{
					?>
				margin:180px 25px 280px 25px;
					<?php					
				}
				?>
				header: html_MyCustomHeader;
				footer: html_MyCustomFooter;
			}
		</style>
	</head>
	<body>
		<div style="padding:20px;font-family:'Arial';">
			<htmlpageheader name="MyCustomHeader">
				<table style="width:100%;font-family:'Arial';">
					<tr>
						<td style="width:50%;padding:0px 15px;">
							<?php
							if(isset($_GET['header'])){
								if($_GET['header'] == "1"){
									?>
							<img src="uploads/<?php echo $company['logo1'];?>" style="max-height:90px;max-width:160px;" />
									<?php
								}
							}
							else{
								?>
							<img src="uploads/<?php echo $company['logo1'];?>" style="max-height:90px;max-width:160px;" />
								<?php					
							}
							?>
						</td>
					</tr>
				</table>
			</htmlpageheader>
			<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:30px;font-family:'Arial';">
				<tr>
					<?php
					$back = $bdd->query("SELECT * FROM suppliers WHERE id='".$facture['supplier']."'");
					$supplier = $back->fetch();
					?>
					<td style="width:100%;padding:0px;text-align:right;">
						<p style="font-weight:bold;margin-top:0px;padding-top:0px;"><?php echo $_GET['title'];?>: <?php echo $facture['code'];?></p>
						<p style="font-size:12px;">Date création: <?php echo date("d/m/Y",$facture['dateadd']);?></p>
						<p style="font-size:12px;"><?php echo ($supplier['codefo']!=""?"Code Fournisseur: ".$supplier['codefo']:"Réf Fournisseur: ".$supplier['code']);?></p>
					</td>
				</tr>
			</table>
			<table style="width:100%;margin-top:-20px;font-family:'Arial';">
				<tr>
					<td><p style="margin-top:0px;padding-top:0px;font-size:12px;">Émetteur</p></td>
					<td></td>
					<td><p style="font-size:12px;">Adressé à</p></td>
				</tr>
				<tr>
					<td style="width:50%;padding:10px;background:#EEEEEE;">
						<p style="font-weight:bold;"><?php echo $company['rs'];?></p>
						<p style="font-size:12px;"><?php echo $company['address'];?></p>
						<p style="font-size:12px;"><b>Tél.: </b><?php echo $company['phone'];?></p>
						<?php
						if($company['email'] != ""){
						?>
						<p style="font-size:12px;"><b>Email: </b><?php echo $company['email'];?></p>
						<?php
						}
						if($company['website'] != ""){
						?>
						<p style="font-size:12px;"><b>Siteweb: </b>: <?php echo $company['website'];?></p>
						<?php
						}
						?>
					</td>
					<td style="width:1%;"></td>
					<td style="width:49%;padding:10px;border:1px solid #000000;">
						<p style="font-weight:bold;"><?php echo $supplier['title']!=""?$supplier['title']:"Fournisseur anonyme";?></p>
						<?php
						if($supplier['address'] != ""){
						?>
						<p style="font-size:12px;"><b>Adresse: </b><?php echo $supplier['address']?></p>
						<?php
						}
						if($supplier['respphone'] != ""){
						?>
						<p style="font-size:12px;"><b>Tél: </b><?php echo $supplier['respphone']?></p>
						<?php
						}
						if($supplier['respemail'] != ""){
						?>
						<p style="font-size:12px;"><b>Email: </b><?php echo $supplier['respemail']?></p>
						<?php
						}
						if($supplier['respfax'] != ""){
						?>
						<p style="font-size:12px;"><b>Fax: </b><?php echo $supplier['respfax']?></p>
						<?php
						}
						?>
					</td>
				</tr>
			</table>
			<?php
			if($facture['abovetable'] != ""){
			?>
			<div style="margin-top:10px;">
				<?php echo "<p style='margin-bottom:5px;'><b>Note: </b></p>".str_replace('<p','<p style="margin:0px;padding:0px;"',$facture['abovetable']);?>
			</div>
			<?php
			}
			$h = 0;
			$price = 0;
			$maindiscount = 0;			
			$existdiscount = 0;
			?>
			<table style="margin-top:10px;border-collapse:collapse;width:100%;font-size:12px;font-family:'Arial';text-align:center;">
				<?php
				$discounttype = "";
				$products = explode("||",$facture['title']);
				$abovenotes = explode("||",$facture['abovenote']);
				$belownotes = explode("||",$facture['belownote']);
				$units = explode("||",$facture['unit']);
				$qtys = explode("||",$facture['qty']);
				$uprices = explode("||",$facture['uprice']);
				$tvas = explode("||",$facture['ptva']);
				$tprices = explode("||",$facture['tprice']);
				$discounts = explode("||",$facture['discount']);
				for($i=0;$i<count($discounts);$i++){
					if($discounts[$i] > 0){
						$existdiscount = 1;
						$discounttype = $facture['discounttype'];
					}					
				}
				?>
				<thead>
					<tr>
						<?php
						if($_GET['d1'] == "1"){
						?>
						<th style="width:50%;padding:10px;border:1px solid #000000;">Désignation</th>
						<?php
						}
						if($_GET['d2'] == "1"){
						?>
						<th style="padding:10px;border:1px solid #000000;">Qté</th>
						<?php
						}
						if($_GET['valeur'] == "1"){
							if($_GET['d3'] == "1"){
							?>
						<th style="padding:10px;border:1px solid #000000;white-space:nowrap;">P.U. HT</th>
							<?php
							}
							if($existdiscount == 1){
								if($_GET['d4'] == "1"){
								?>
						<th style="padding:10px;border:1px solid #000000;white-space:nowrap;">Remise HT</th>
								<?php
								}
							}
							if($_GET['d5'] == "1"){
							?>
						<th style="padding:10px;border:1px solid #000000;">TVA</th>
							<?php
							}
							if($_GET['d6'] == "1"){
							?>
						<th style="padding:10px;border:1px solid #000000;white-space:nowrap;">Total HT</th>
							<?php
							}
						}
						?>
					</tr>
				</thead>
				<?php
				$tvarate = [];
				$tvavalue = [];
				for($i=0;$i<count($products);$i++){
					?>
				<tr>
					<?php
					if($_GET['d1'] == "1"){
					?>
					<td style="height:20px;padding:10px 4px;border-top:1px solid #000000;border-right:1px solid #000000;border-left:1px solid #000000;border-bottom:1px solid #000000;text-align:left;">
						<?php echo $products[$i];?>
					</td>
					<?php
					}
					if($_GET['d2'] == "1"){
					?>
					<td style="padding:10px 4px;border-top:1px solid #000000;border-left:1px solid #000000;border-right:1px solid #000000;border-bottom:1px solid #000000;text-align:right;white-space:nowrap;"><?php echo $qtys[$i]." ".$command['unit'];?></td>
					<?php
					}
					if($_GET['valeur'] == "1"){
						if($_GET['d3'] == "1"){
						?>
					<td style="padding:10px 4px;border-top:1px solid #000000;border-left:1px solid #000000;border-right:1px solid #000000;border-bottom:1px solid #000000;text-align:right;white-space:nowrap;"><?php echo number_format((float)$uprices[$i],2,'.',' ');?></td>
						<?php
						}
						if($existdiscount == 1){
							if($_GET['d4'] == "1"){
						?>
					<td style="padding:10px 4px;border-top:1px solid #000000;border-left:1px solid #000000;border-right:1px solid #000000;border-bottom:1px solid #000000;text-align:right;white-space:nowrap;"><?php echo $discounts[$i]>0?($discounts[$i].($discounttype=="%"?$discounttype:"")):"";?></td>
						<?php
							}
						}
						if($_GET['d5'] == "1"){
						?>
					<td style="padding:10px 4px;border-top:1px solid #000000;border-left:1px solid #000000;border-right:1px solid #000000;border-bottom:1px solid #000000;text-align:right;white-space:nowrap;"><?php echo $tvas[$i];?>%</td>
						<?php
						}
						if($_GET['d6'] == "1"){
						?>
					<td style="padding:10px 4px;border-top:1px solid #000000;border-left:1px solid #000000;border-right:1px solid #000000;border-bottom:1px solid #000000;text-align:right;white-space:nowrap;"><?php echo number_format((float)$tprices[$i],2,'.',' ');?></td>
						<?php
						}
					}
					?>
				</tr>						
					<?php
					$tprice = number_format((float)$tprices[$i],2,'.','');
					$tvarate[] = $tvas[$i];
					$tvavalue[] = (number_format((float)($tprice * ($tvas[$i]/100)),2,".",""));
					$maindiscount += number_format((float)($discounttype=="%"?(($uprices[$i] * $qtys[$i]) * ($discounts[$i] / 100)):$discounts[$i]), 2, '.', '');
					$price += number_format((float)($tprices[$i]), 2, '.', '');
				}
				?>
			</table>
			<div style="width:351px;margin-top:10px;float:left;">
				<?php
				if($facture['modepayment'] != "" OR $facture['conditions'] != ""){
					if($facture['modepayment'] != ""){
						echo "<p style='margin-bottom:5px;'><b>Mode paiement: </b></p>".str_replace('<p','<p style="margin:0px;padding:0px;"',$facture['modepayment']);
					}
					if($facture['conditions'] != ""){
						echo "<p style='margin-bottom:5px;'><b>Conditions: </b></p>".str_replace('<p','<p style="margin:0px;padding:0px;"',$facture['conditions']);
					}
				}
				else{
					echo "&nbsp;";
				}
				?>				
			</div>
			<?php
			if($_GET['valeur'] == "1"){
			?>
			<div style="width:351px;float:left;">
				<table style="width:100%;border-collapse:collapse;font-family:'Arial';font-size:12px;font-weight:bold;">
					<?php
					if($maindiscount > 0){
						?>
					<tr>
						<td style="padding:5px;font-weight:normal;height:22px;">Remise globale HT</td>
						<td style="padding:5px;font-weight:normal;text-align:right;"><?php echo number_format((float)($maindiscount), 2, '.', ' ');?></td>
					</tr>
						<?php
					}				
					?>
					<tr>
						<td style="width:15%;padding:5px;height:22px;">Total HT <?php echo $maindiscount > 0?"après remise":"";?></td>
						<td style="width:15%;padding:5px;text-align:right;"><?php echo number_format((float)($price), 2, '.', ' ');?></td>					
					</tr>
					<?php
					$tval = 0;
					$uniquetvarate = array_unique($tvarate);
					sort($uniquetvarate);
					foreach($uniquetvarate AS $value){
						$val = 0;
						for($j=0;$j<count($tvarate);$j++){
							if($tvarate[$j] == $value){
								$val += $tvavalue[$j];
								$tval += $tvavalue[$j];
							}
						}
						?>
					<tr>
						<td style="padding:5px;height:22px;">TVA <?php echo $value;?>%</td>
						<td style="padding:5px;text-align:right;"><?php echo number_format((float)$val, 2, '.', ' ');?></td>
					</tr>
						<?php
					}
					?>
					<tr style="background:#EEEEEE;">
						<td style="padding:5px;height:22px;" valign="top">Total TTC</td>
						<td style="padding:5px;text-align:right;" valign="top"><?php echo number_format((float)($price + $tval), 2, '.', ' ');?></td>
					</tr>
					<tr>
						<td colspan="2" valign="top" align="right" style="padding-top:5px;height:22px;">
							<p style="font-weight:normal;">Montants exprimés en <?php echo $settings['currency']?></p>
						</td>
					</tr>
					<tr>
						<td colspan="2" valign="top" align="right" style="padding-top:5px;">
							<p style="white-space:nowrap;"># <?php echo chifre_en_lettre(number_format((float)($price + $tval), 2, '.', ''),$settings['currency']);?> #</p>
						</td>
					</tr>
				</table>				
			</div>
			<?php
			}
			if($facture['picture'] != ""){
			?>
			<div>
				<img src="uploads/<?php echo $facture['picture'];?>" style="max-width:100%;max-height:110%;" />
			</div>
			<?php
			}
			?>
		</div>
		<htmlpagefooter name="MyCustomFooter">
			<div class="footer">
				<p style="margin:10px;text-align:center;font-family:arial;font-size:12px;text-decoration:underline;"><?php echo $_GET['label'];?></p>
				<?php
				if(isset($_GET['signature'])){
					if($_GET['signature'] == "1" AND $company['signature'] !== ""){
					?>
				<p style="padding:0px 0px 30px 0px;text-align:center;"><img src="uploads/<?php echo $company['signature'];?>" style="display:block;height:100px;margin:10px auto;" /></p>
					<?php
					}
					else{
					?>
				<p style="padding:0px 50px 30px 0px;text-align:right;"><img src="images/fakesignature.png" style="display:block;height:100px;margin:10px auto;" /></p>
					<?php					
					}
				}
				if(isset($_GET['header'])){
					if($_GET['header'] == "1"){
						?>
						<p style='padding:5px 0px 0px 0px;font-family:arial;font-size:9px;text-align:center;border-top:1px solid #000000;'><b>Siège social: </b><?php echo $company['rs'];?> - <?php echo $company['address'];?><br />
						<?php
						if($company['phone'] != ""){
							?>
						<b>Téléphone: </b><?php echo $company['phone'];?> 
							<?php
						}
						if($company['email'] != ""){
							?>
						- <b>E-mail: </b><?php echo $company['email'];?>
							<?php
						}
						if($company['website'] != ""){
							?>
						- <b>Siteweb: </b><?php echo $company['website'];?>
							<?php
						}
						?>
						<br />
						<?php
						if($company['capital'] != ""){
							?>
						<b>Capital de </b><?php echo $company['capital'];?> 
							<?php
						}
						if($company['rc'] != ""){
							?>
						- <b>R.C.: </b><?php echo $company['rc'];?> 
							<?php
						}
						if($company['patente'] != ""){
							?>
						- <b>Patente: </b><?php echo $company['patente'];?>
							<?php
						}
						?>
						<br />
						<?php
						if($company['iff'] != ""){
							?>
						<b>I.F.: </b><?php echo $company['iff'];?> 
							<?php
						}
						if($company['cnss'] != ""){
							?>
						- <b>C.N.S.S.: </b><?php echo $company['cnss'];?> 
							<?php
						}
						if($company['ice'] != ""){
							?>
						- <b>ICE: </b><?php echo $company['ice'];?>
							<?php
						}
						?>
						<br /><b>Page: {PAGENO}/{nbpg}</b></p>
						<?php
					}
					else{
						?>
				<p style="padding:0px 50px 30px 0px;text-align:right;"><img src="images/fakesignature2.png" style="display:block;height:45px;margin:0px auto;" /></p>
						<?php
					}
				}
				else{
					?>
					<p style='padding:5px 0px 0px 0px;font-family:arial;font-size:9px;text-align:center;border-top:1px solid #000000;'><b>Siège social: </b><?php echo $company['rs'];?> - <?php echo $company['address'];?><br />
					<?php
					if($company['phone'] != ""){
						?>
					<b>Téléphone: </b><?php echo $company['phone'];?> 
						<?php
					}
					if($company['email'] != ""){
						?>
					- <b>E-mail: </b><?php echo $company['email'];?>
						<?php
					}
					if($company['website'] != ""){
						?>
					- <b>Siteweb: </b><?php echo $company['website'];?>
						<?php
					}
					?>
					<br />
					<?php
					if($company['capital'] != ""){
						?>
					<b>Capital de </b><?php echo $company['capital'];?> 
						<?php
					}
					if($company['rc'] != ""){
						?>
					- <b>R.C.: </b><?php echo $company['rc'];?> 
						<?php
					}
					if($company['patente'] != ""){
						?>
					- <b>Patente: </b><?php echo $company['patente'];?>
						<?php
					}
					?>
					<br />
					<?php
					if($company['iff'] != ""){
						?>
					<b>I.F.: </b><?php echo $company['iff'];?> 
						<?php
					}
					if($company['cnss'] != ""){
						?>
					- <b>C.N.S.S.: </b><?php echo $company['cnss'];?> 
						<?php
					}
					if($company['ice'] != ""){
						?>
					- <b>ICE: </b><?php echo $company['ice'];?>
						<?php
					}
					?>
					<br /><b>Page: {PAGENO}/{nbpg}</b></p>
					<?php
				}
				?>
			</div>
		</htmlpagefooter>
	</body>
</html>
<?php
$css = "
ul {
  list-style-type: disc !important;
  margin-left: 20px !important;
  padding-left: 20px !important;
}

ol {
  list-style-type: decimal !important;
  margin-left: 20px !important;
  padding-left: 20px !important;
}

li {
  display: list-item !important;
  margin-bottom: 5px;
}
";

$content = ob_get_clean();
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf->WriteHTML(wrapListsInTables($content));
$mpdf->WriteHTML($css, \Mpdf\HTMLParserMode::HEADER_CSS);
$mpdf->Output($facture['code'].'.pdf','D');


/**
 * Wrap all <ul> or <ol> elements that are inside tables
 * into a 2-column structure:
 *   <table><tr>
 *      <td style="width:25px;"></td>
 *      <td> ... list ... </td>
 *   </tr></table>
 *
 * @param string $html The input HTML.
 * @param int $widthPx The width in pixels for the left spacer column (default: 25).
 * @return string Modified HTML ready for mPDF.
 */
function wrapListsInTables(string $html, int $widthPx = 25): string
{
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML(
        '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' . $html . '</body></html>',
        LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
    );

    $xpath = new DOMXPath($doc);

    // Find all ul and ol inside tables
    $lists = $xpath->query('//table//ul | //table//ol');

    foreach ($lists as $list) {
        $parent = $list->parentNode;
        if (!$parent) continue;

        // Build the new table wrapper
        $wrapperTable = $doc->createElement('table');
        $tr = $doc->createElement('tr');

        $td1 = $doc->createElement('td');
        $td1->setAttribute('style', "width:{$widthPx}px;");

        $td2 = $doc->createElement('td');

        // Move the list into td2
        $td2->appendChild($list->cloneNode(true));

        $tr->appendChild($td1);
        $tr->appendChild($td2);
        $wrapperTable->appendChild($tr);

        // Replace the old list with the new table
        $parent->replaceChild($wrapperTable, $list);
    }

    $body = $doc->getElementsByTagName('body')->item(0);
    $result = '';
    foreach ($body->childNodes as $child) {
        $result .= $doc->saveHTML($child);
    }

    libxml_clear_errors();
    return $result;
}
