<?php
	include '../autoload.php';

	if(!isset($_SESSION['language']))
		$_SESSION['language']="FR";
	
	error_log ( "###############################################################" );
	error_log ( "### Generate Audit PDF ###" );
	
	$audit_id=-1;
	if(isset($_REQUEST['audit_id']))
	{
		$audit_id=$_REQUEST['audit_id'];
	}
	
	$annexes=array();
	$annexes_inv=array();
	$annexescpt=0;
	
	if($audit_id==-1)
		exit();
	
	
	require_once $_SERVER['DOCUMENT_ROOT']. '/mpdf82/vendor/autoload.php';

	error_log ( " Doc root : ".$_SERVER['DOCUMENT_ROOT']);

	$strCookie = 'eoQUAL=' . $_COOKIE['eoQUAL'] . '; path=/';
	$useragent = $_SERVER['HTTP_USER_AGENT'];
	
	
	$audit_title="";

	$conn = get_dbconnection();
	$today="";
	$sql="select title,to_char(now(),'DD/MM/YYYY')  from audit where id=".$audit_id;
	$query=pg_query($conn,$sql);
	if($query=pg_query($conn,$sql))
	{
		if($row=pg_fetch_row($query))
		{
			$audit_title=$row[0];
			$today=$row[1];
		}
	}
	
	//get list
	$sql="select quaad_point.id,istitle,description,level2||coalesce(nullif('.'||level3,'.-1'),'')||coalesce(nullif('.'||level4,'.-1'),'')||coalesce(nullif('-'||inlevelorder,'-0'),''),description_summary from quaad_point, quaad_description where quaad_point.id = quaad_description.id_quaadpoint  and language='FR' and quaadversion=(select type from audit where id=".$audit_id.") order by level1,level2,level3,level4,level5,inlevelorder";
	
	
	$mpdf = new \Mpdf\Mpdf();
	$mpdf->SetCompression(true);
	$mpdf->allow_charset_conversion=true;
	$mpdf->charset_in='UTF-8';
	
	$htmlheader="<table><tr><td>Coucou</td></tr></table>";
	$htmlheader = '<htmlpageheader name="firstpage" style="display:none">
        '.$htmlheader.'
      </htmlpageheader>
      <htmlpageheader name="otherpages" style="display:none">
      </htmlpageheader>';

	error_log ( " Write header..." );
    $mpdf->WriteHTML($htmlheader);
$htmlfooter="<hr size=\"6\">
<table width=\"100%\" style=\" vertical-align: bottom; font-family: arial; font-size: 11pt;\">
	<tbody>
		
		<tr>
			<td width=\"90%\" style=\"font-size: 11pt; vertical-align: top; color: #000000; line-height: 110%;\" align=\"left\"><b>".$audit_title."</b>&nbsp;&nbsp;&nbsp;Document généré par eoQUAL</td>
			<td width=\"10%\" style=\"font-size: 11pt; vertical-align: top; color: #000000; line-height: 110%;\" align=\"right\">{PAGENO}/{nbpg}</td>
	
		</tr>
	</tbody>
</table>";
    $htmlfooter = '<htmlpagefooter name="firstpagef" style="display:none">
      
      </htmlpagefooter>
      <htmlpagefooter name="otherpagesf" style="display:none">
	  '.$htmlfooter.'
      </htmlpagefooter>';
	error_log ( " Write footer..." );
    $mpdf->WriteHTML($htmlfooter);

    //$mpdf->WriteHTML('<sethtmlpagefooter name="firstpagef" value="on"/>');
	

		$pagegarde 	= file_get_contents ('../../../Config/pagegarde.html',FILE_USE_INCLUDE_PATH);
		$keys				= array("___DOC_TITLE___","___MAIN_TITLE___","___DATE_TODAY___");
		$values 		= array($audit_title,$audit_title,$today);
		$pagegarde	= str_replace($keys,$values,$pagegarde);
		
		error_log ( " Write page garde..." );
		
		$mpdf->WriteHTML($pagegarde);
		$i = 0;
		$mpdf->WriteHTML('<sethtmlpagefooter name="otherpagesf" value="on"/>');

		echo ( "### Process audit<br>" );
		if ( $query=pg_query($conn,$sql) )
		{
			while($row=pg_fetch_row($query))
			{
				$datahtml="";
				$qp_id=$row[0];
				$istitle=$row[1];
				$qp_nr=$row[3];
				$qp_desc=$row[2];
				$qp_summary=$row[4];
			
				if($istitle=="t") 
					continue;
			
				$mpdf->Bookmark($qp_nr."  ".$qp_summary);
				$datahtml.="<table style='width: 100%;' cellspacing='0' cellpadding='5' border='0'>";
				$datahtml.="<tr><td style='background-color: #ffcc99;'><b>".$qp_nr."</b><br></td>";
				$datahtml.="   <td colspan='2' style='color: #000000; padding-top: 15px; padding-bottom: 10px;background-color: #ffeedd;'>";
				$datahtml.=$qp_desc."</td></tr></tbody></table><br><br>";
			
				$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
				$arr = explode("?", $actual_link, 2);
				$current_url = $arr[0];
				error_log ( " current_url : ".$current_url );
				// $url=str_replace("generate_audit_pdf.php","dbconnector/bquaadril/checkrules.php",$current_url);
				$url=str_replace("html/generate_audit_pdf.php","database/bquaadril/checkrules.php",$current_url);
				error_log ( " url : ".$url );
	
				session_write_close();
				$ch = curl_init($url);

				$params= array(
					'id' => $qp_id,
					'audit_id' => $audit_id
				);
	
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				//curl_setopt($ch, CURLOPT_HEADER, 1);

				curl_setopt($ch,CURLOPT_USERAGENT, $useragent);
				curl_setopt($ch, CURLOPT_COOKIE, $strCookie );

				$resultt = curl_exec($ch);
				curl_close($ch);

				session_start();

			
				$xml = new SimpleXMLElement($resultt);

				if($xml)
				{
					$expected = $xml->xpath('//expected')[0];
					$exp_nbrdocs = $expected->attributes()->nbrdocs;
					$exp_proc = $expected->attributes()->procedure;
				
					$result_proc= $xml->xpath('//procedure');
					$doc_id=-1;
					$fname="";
					$proc_id=-1;
					foreach ($result_proc as $node)
					{
						$attrs=$node->attributes();
						foreach($attrs as $attr => $val_attr)
						{
							if($attr=="docid")
								$doc_id = $val_attr;
							if($attr=="fname")
								$fname=$val_attr;
							if($attr=="procid")
								$proc_id=$val_attr;
						}
						break;
					}
					$annexe_nbr=-1;
					if($doc_id !=-1)
					{
						if(!isset($annexes["".$doc_id]))
						{
							$annexescpt++;
							$annexes["".$doc_id]=$annexescpt;
							$annexes_inv["".$annexescpt]=$doc_id;
						}
						$annexe_nbr=$annexes["".$doc_id];
					}
				
					$datahtml.= "<div style=\"flex: 1; background-color: white; width: 100%; overflow-y:auto;\">";
					$datahtml.="<table style=\"background-color: white; width: 100%;\">";
					$datahtml.= "<tr style=\"background-color: white;\">";
					$datahtml.="<td  style=\"background-color: white; padding-top: 20px; padding-bottom: 8px; border-bottom: solid thin gray; color: #646464;\">";
					$datahtml.="<b>Procédure associée</b>";
					$datahtml.="</td>";
					$datahtml.="</tr>";
				
					if($doc_id!=-1)
					{
						$datahtml.="<tr><td style='font-size:large;'><br><a href=\"#Annexe ".$annexe_nbr."\"><b><u>Annexe ".$annexe_nbr." :</u></b></a>".$fname."</td></tr>";
					}
					else
					{
						$datahtml.="<tr><td style='font-size:large;color:red'><br><b><u>Aucune procédure associée</u></b></tr>";
					}
					$datahtml.="</table></div><br>";
				
				
					$entities = $xml->xpath('//entity');
					$entities_cpt=0;
					foreach ($entities as $entity)
					{
						$name=$entity->attributes()->name;
						if($name)
						{
							if($entities_cpt==0)
							{
								$datahtml.="<div  style=\"background-color: white; padding-top: 20px; padding-bottom: 8px; border-bottom: solid thin gray; color: #646464;\">";
								$datahtml.="<b>Liste</b>";
								$datahtml.="</div><br>";
							}
							$datahtml.="<table><tr><td colspan='2' style='color: darkblue;font-weight:bold'>".$name."</td></tr>";
						
							$entities_cpt++;
						}
						$documents = $entity->xpath('.//document');
						$document_cpt=0;

						$nbrdocuments=count($documents);
						foreach($documents as $document)
						{
							$doc_id=-1;
							$force_doc_id=-1;
							$fname="";
							$remark="";
							$attrs=$document->attributes();
							foreach($attrs as $attr => $val_attr)
							{
								if($attr=="docid")
										$doc_id = $val_attr;
								if($attr=="realfname")
										$fname=$val_attr;
								if($attr=="remark")
										$remark=$val_attr;
							}
							
						
							if($doc_id !=-1)
							{
								$document_cpt++;
								if(!isset($annexes["".$doc_id]))
								{
									$annexescpt++;
									$annexes["".$doc_id]=$annexescpt;
									$annexes_inv["".$annexescpt]=$doc_id;
								}
							
								if(strlen($remark)>1) 
										$remark="<br><br>".$remark."<br>";
								$annexe_nbr=$annexes["".$doc_id];
								$datahtml.="<tr><td style='font-size:large;'><br><a href=\"#Annexe ".$annexe_nbr."\"><b><u>Annexe ".$annexe_nbr." :</u></b></a>".$fname.$remark;
								if(strlen($document)>1)
									$datahtml.="<br><br>".$document."<br>";
								$datahtml.="</td></tr>";
							}
						}
						$documents = $entity->xpath('.//documentmis');
						$documentmis_cpt=0;
						foreach($documents as $document)
						{
							$documentmis_cpt++;
							$remark="";
							$attrs=$document->attributes();
							$span_add="<br><span style='color:darkgreen'>Pas de document dans eoQUAL</span>";
						
							foreach($attrs as $attr => $val_attr)
							{
								if($attr=="remark")
									$remark = $val_attr;
								if($attr=="forcestatus")
								{
									if($val_attr=="f") 
									{
										$documentmis_cpt--;
										$span_add="";
									}
									
								}
							}
							if(strlen($remark)>1)
							{
								$datahtml.="<tr><td style='font-size:large;'>".$span_add;
								$datahtml.="<br>".$remark."<br>";
								$datahtml.="</td></tr>";
							}
						}
						$nbrmissing=($exp_nbrdocs - $document_cpt - $documentmis_cpt);
					
						if($nbrmissing > 0)
						{						
							$datahtml.="<tr><td style='font-size:large;'><br><span style='color:red'>".$nbrmissing." document(s) absent(s) dans eoQUAL</span>";
							$datahtml.="</td></tr>";
						}
						$datahtml.="</table><hr><br>";
					}
				
					$mpdf->WriteHTML($datahtml);
					$mpdf->WriteHTML('<pagebreak>');
									
					$i++;
			
					echo ( "+" );
					// flush();
				}
		}

		echo ( "<br>" );
		echo ( "### Process annexes<br>" );
		for($a = 1;$a<= $annexescpt;$a++)
		{
			echo ( "Annex ".$a." / ".$annexescpt."<br>" );

			$doc_id=$annexes_inv["".$a];
			$sqldoc = "select '".$GLOBALS["document_storage"].'/'."'||replace(folder||'/'||file,'\\','/'),extern_link from document where id=".$doc_id.";";

			if($querydoc=pg_query($conn,$sqldoc))
			{
				if($row=pg_fetch_row($querydoc))
				{
					
					$docufile = $row[0];
					
					if(!file_exists($docufile))
						continue;
					
					$pagecount;
					try{
						$pagecount = $mpdf->setSourceFile($docufile);
					}
					catch(Exception $e)
					{
						error_log ( "Need to use Ghostscript for : " .$docufile );

						$inputPDF = $docufile;
						echo ( "Process file : " .$inputPDF ."<br>" );
						// Path to the output PDF file (where the preprocessed PDF will be saved)
						//$outputPDFt = 'C:/XIMEO/output_t.pdf';
						$outputPDF = 'C:/XIMEO/output.pdf';
						
						// Command to run Ghostscript to preprocess the PDF
						//$command = "gswin64 -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=\"$outputPDF\" \"$inputPDF\"";
						
						// $command = "c:/Ximeo/qpdf/qpdf.exe --linearize --object-streams=disable --stream-data=uncompress \"$inputPDF\" \"$outputPDF\"";
						$command = "c:/Ximeo/qpdf/qpdf.exe --qdf --object-streams=disable " . escapeshellarg($inputPDF) . " " . escapeshellarg($outputPDF);
						error_log ( "command : " .$command );
						
						// Execute the Ghostscript command
						exec($command, $output, $returnCode);

					/*	$command = "gswin64 -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dDecodeAllStreams=true -dCompressStreams=false  -dCompressPages=false -sOutputFile=\"$outputPDF\" \"$outputPDFt\"";
						exec($command, $output, $returnCode);
*/
						
						// Check if Ghostscript command was successful
						if ($returnCode === 0) {
							echo "Preprocessing successful. Output saved as ".$outputPDF."<br>";
						} else {
							echo "Error during preprocessing. Check your PDF and Ghostscript installation.";
						}

						try {
							$pagecount = $mpdf->setSourceFile($outputPDF);
							
						}
						catch(Exception $e)
						{
							echo "Error ( file : ".$docufile." ) !!!  ".$e->getMessage();
							echo nl2br(htmlspecialchars($e->getTraceAsString()));
						}
					}

					$mpdf->WriteHTML('<pagebreak>');
					$mpdf->SetAutoPageBreak(false); // Disable auto page break
					$mpdf->Bookmark("Annexe ".$a);$mpdf->WriteHTML("<a name='Annexe ".$a."'></a>");
					$mpdf->SetXY(0, 0); // Set position to top-left corner
					$mpdf->SetFont('Arial', 'B', 48); // Set font and size
					$mpdf->SetTextColor(0, 0, 0); // Set text color (black)
					$mpdf->SetXY(0, 0); // Set position to top-left corner
					$mpdf->Cell(210, 297, "Annexe ".$a, 0, 1, 'C'); // Centered text filling the page
					error_log ( " pagecount : " .$pagecount );			
					$mpdf->SetAutoPageBreak(true); // Disable auto page break
										
					for($i=1;$i<=$pagecount;$i++)
					{
						
						$import_page = $mpdf->importPage($i);
						$size = $mpdf->getTemplateSize($import_page);
						$orientation = $size['width'] > $size['height'] ? "L" : "P";
//						$mpdf->AddPageByArray(['orientation' => $orientation]);
						// Set the zoom factor
						$zoomFactor = 0.95; 
						
						// Calculate the horizontal offset to center the page
						$horizontalOffset = (1-$zoomFactor)*$size['width']/2;

						// Calculate the scaled width and height based on the zoom factor
						$newWidth = $size['width'] * $zoomFactor;
						$newHeight = $size['height'] * $zoomFactor;

						$mpdf->AddPageByArray(['orientation' => $orientation, 'size' => [$newWidth, $newHeight]]);
						$mpdf->useTemplate($import_page, $horizontalOffset, 0, $newWidth, $newHeight);

					//	$mpdf->useTemplate($import_page);                 
				   }	
				}
			}
		}
	}

	return $mpdf->Output();
	
?>