<?php
error_reporting(E_ALL);
set_time_limit(300);          // Allow up to 5 minutes for large datasets
ini_set('memory_limit', '512M'); // Enough memory for 76+ images
ob_start();                   // Buffer all output so stray warnings don't corrupt PDF
require_once 'tcpdf/tcpdf.php';

class MYPDF extends TCPDF {
public function Footer() {
    	$this->SetY(-15);
    	// Use the same font as body content
    	$this->SetFont('helvetica', 'I', 8);
    	// Left side: company name or blank
    	$this->Cell(0, 10, 'Page ' . $this->getAliasNumPage() . ' of ' . $this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
    }
}


$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
 
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(true);
header('Access-Control-Allow-Origin: *');


if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}

$fontname = TCPDF_FONTS::addTTFfont('font/Spectral-Regular.ttf', 'TrueTypeUnicode', '', 32);
$fontname1 = TCPDF_FONTS::addTTFfont('font/Spectral-Medium.ttf', 'TrueTypeUnicode', '', 32);	


$fontname2 = TCPDF_FONTS::addTTFfont('font/Lato-Black.ttf', 'TrueTypeUnicode', '', 32);
$fontname3 = TCPDF_FONTS::addTTFfont('font/Lato-BlackItalic.ttf', 'TrueTypeUnicode', '', 32);	
$fontname4 = TCPDF_FONTS::addTTFfont('font/Lato-Bold.ttf', 'TrueTypeUnicode', '', 32);
$fontname5 = TCPDF_FONTS::addTTFfont('font/Lato-BoldItalic.ttf', 'TrueTypeUnicode', '', 32);	

$fontname6 = TCPDF_FONTS::addTTFfont('font/Lato-Italic.ttf', 'TrueTypeUnicode', '', 32);
$fontname7 = TCPDF_FONTS::addTTFfont('font/Lato-Light.ttf', 'TrueTypeUnicode', '', 32);	
$fontname8 = TCPDF_FONTS::addTTFfont('font/Lato-LightItalic.ttf', 'TrueTypeUnicode', '', 32);
$fontname9 = TCPDF_FONTS::addTTFfont('font/Lato-Regular.ttf', 'TrueTypeUnicode', '', 32);	 
$fontname10 = TCPDF_FONTS::addTTFfont('font/Spectral-Italic.ttf', 'TrueTypeUnicode', '', 32);	

$pdf->SetMargins(5, 5, 5, 5);
// $pdf->SetFooterMargin(50);

$pdf->AddFont($fontname, '', 10, '', false); 
$pdf->AddFont($fontname1, '', 10, '', false);
$pdf->AddFont($fontname2, '', 10, '', false); 
$pdf->AddFont($fontname3, '', 10, '', false);
$pdf->AddFont($fontname4, '', 10, '', false); 
$pdf->AddFont($fontname5, '', 10, '', false);
$pdf->AddFont($fontname6, '', 10, '', false); 
$pdf->AddFont($fontname7, '', 10, '', false);
$pdf->AddFont($fontname8, '', 10, '', false); 
$pdf->AddFont($fontname9, '', 10, '', false);
$pdf->AddFont($fontname10, '', 10, '', false); 

$i = 0;

$pdf->AddPage();

if (isset($_POST['title']) ) {

$title = $_POST["title"];
$title1 = json_decode($title);
if ($title1 === null) {
    // JSON decode failed — bad input
    http_response_code(400);
    exit('Invalid JSON in title parameter');
}
$html = '';

// Ensure images directory exists
if (!is_dir('images')) {
    mkdir('images', 0755, true);
}


$pageCount = 0;
$isHeader = true;
$isLessvalue = true;

// Count total individual items (each outer element is a pair of up to 2 items)
$arrLen = 0;
foreach ($title1 as $arr) {
    $arrLen += count($arr);
}
// Total pages needed = ceil(items / 12)
// e.g. 22 items → ceil(22/12)=2 pages, 76 items → ceil(76/12)=7 pages
// Using intval() was wrong: intval(22/12)=1 → no new page ever added for 22 items!
$total = ceil($arrLen / 12);


$header = ' 
	<table style="  width:100%; " cellpadding="0" cellspacing="0">
			<tbody>
				<tr>
					<td>
						<table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0">
							<tbody> 
								<tr>
									<td width="100%" style="width:100%;">
										<table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0">
											<tbody> 
												<tr>
													<td  width="40%" style="width: 40%;" valign="middle">
														<a target="_blank" href="#" style="text-decoration:none;">
													 		<img src="./images/Logo_color.png"  width="200" height="28" >
													 	</a> 	
													</td>
													<td width="60%" style="width: 60%; font-size:20px;font-weight:900;font-family:Lato-Black;" cellpadding="0" cellspacing="0" valign="middle" >
														 Accessories
													</td>
												</tr>
											</tbody>
										</table>
									</td>
								</tr>  
								<tr>
									<td width="100%" style="line-height:10px;height:10px;">
									</td>
								</tr> 
								<tr>
									<td width="100%" style="width:100%;" >
										<table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0">
											<tbody> 
												<tr>
													<td width="100%" style="width: 100%;" >
														<table width="100%" style="width: 100%;" cellpadding="5" cellspacing="0">
															<tbody> ';

$footer = '</tbody>
	</table>
	</td>
	</tr>
	</tbody>
	</table>
	</td>
	</tr> 
	</tbody>
	</table>

	</td>
	</tr>
	</tbody>
	</table>
'; 

foreach ($title1 as $arr) {

		$html .= '<tr>';
foreach ($arr as $ary) {
	$file_name = basename($ary->img);
	$url = $ary->img;
	$local_path = 'images/' . $file_name;
	// Download remote image safely using file_get_contents (works without allow_url_fopen issues)
	if (!file_exists($local_path)) {
		$img_data = @file_get_contents($url);
		if ($img_data !== false) {
			file_put_contents($local_path, $img_data);
		} else {
			// Use a placeholder if download fails
			$file_name = 'No%20Image.png';
			$local_path = 'images/' . $file_name;
		}
	}
	$i += 1;

	$html .= '<td width="50%" style="width:50%;">
<table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0">
	<tbody> 
		<tr>
			<td width="100%"  height="110px" style="width: 100%; height:110px;border-top:1px solid #777; border-left:1px solid #777; border-right:1px solid #777; border-bottom:1px solid #777;" valign="top">
				<table width="100%" style="width: 100%;" cellpadding="5" cellspacing="0">
					<tbody> 
						<tr> 
							<td width="100%" style="width:100%;">
								 <table width="100%" style="width: 100%;" cellspacing="0">
									<tbody> 
										<tr> 
											<td width="80px" style="width:80px;">
												<img src="images/'.$file_name.'" width="75" height="75" style="width:75px;height:75px;">
											</td>
											<td width="180px" style="width:180px;border-left:1px solid #777;padding-left:20px; ">
												<table width="100%" style="width: 100%;" cellspacing="0">
													<tbody> 
														<tr> 
															<td width="100%" style="width: 100%;font-family:Lato-Black;font-size:9px;" >
																'.$ary->title.'
															</td>
														</tr>
														<tr>
															<td width="100%" style="line-height:5px;height:5px;">
															</td>
														</tr> 
														<tr> 
															<td width="100%" style="width: 100%;font-family:Lato;font-size:8px;color: #a6192e;" >
																 '.$ary->tag.' 
															</td>
														</tr>
														<tr>
															<td width="100%" style="line-height:5px;height:5px;">
															</td>
														</tr> 
														<tr> 
															<td width="100%" style="width: 100%;font-family:Lato;font-size:7px; color: #000; " >
																<ul style="margin: 0px; padding: 0px;">
																	'.$ary->desc1.'
																</ul>
															</td>
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
									</tbody>
								</table>
							</td> 
						</tr>
					</tbody>
				</table>
			</td>
		</tr>
	</tbody>
</table>	
</td>';

}
		$html .= '</tr>';

		if($i == 12){
			$pageCount += 1;
			// CRITICAL: disable auto page break BEFORE writeHTML.
			// If left enabled, TCPDF breaks mid-<tr>, injecting the footer inside a card
			// and splitting the image from its title/description.
			$pdf->SetAutoPageBreak(false, 0);
			if($isHeader){
				$pdf->writeHTML($header.$html.$footer, true, false, true, false, '');
				$isHeader = false;
			}else{
				$pdf->writeHTML('<table style="  width:100%; " cellpadding="0" cellspacing="0"> <tbody> <tr> <td> <table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0"> <tbody><tr> <td width="100%" style="line-height:10px;height:10px;"> </td> </tr> <tr> <td width="100%" style="width:100%;" > <table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0"> <tbody> <tr> <td width="100%" style="width: 100%;" > <table width="100%" style="width: 100%;" cellpadding="5" cellspacing="0"> <tbody>'.$html.$footer
				, true, false, true, false, '');
			}
			// Restore auto page break after the block is fully written
			$pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM);
			
				$pdf->lastPage();
				if($pageCount < $total){
					$pdf->addPage();					
				}
				
				$i = 0;
				$html = '';
		}
		
		
}
// Render any remaining items that didn't fill a complete page of 12
if($i > 0 && $isLessvalue){
	// Same guard: disable auto page break so TCPDF can't break inside the final block
	$pdf->SetAutoPageBreak(false, 0);
	if($isHeader){
		$pdf->writeHTML($header.$html.$footer, true, false, true, false, '');
		$isHeader = false;
		$isLessvalue = false;
	}else{
		$pdf->writeHTML('<table style="  width:100%; " cellpadding="0" cellspacing="0"> <tbody> <tr> <td> <table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0"> <tbody><tr> <td width="100%" style="line-height:10px;height:10px;"> </td> </tr> <tr> <td width="100%" style="width:100%;" > <table width="100%" style="width: 100%;" cellpadding="0" cellspacing="0"> <tbody> <tr> <td width="100%" style="width: 100%;" > <table width="100%" style="width: 100%;" cellpadding="5" cellspacing="0"> <tbody>'.$html.$footer
		, true, false, true, false, '');
		$isLessvalue = false;
	}
	$pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM);

}

ob_end_clean();
 
$pdf->Output('htmlout.pdf', 'I');
}

?>