<?php
require_once __DIR__ . '/vendor/autoload.php';

function fitImageWithinBox($imageWidth, $imageHeight, $boxLeft, $boxBottom, $boxRight, $boxTop) {
    $boxWidth = $boxRight - $boxLeft;
    $boxHeight = $boxTop - $boxBottom;

    $aspectRatio = $imageWidth / $imageHeight;
    $boxAspectRatio = $boxWidth / $boxHeight;

    if ($aspectRatio > $boxAspectRatio) {
        $newWidth = $boxWidth;
        $newHeight = $boxWidth / $aspectRatio;
        $newLeft = $boxLeft;
        $newBottom = $boxBottom + ($boxHeight - $newHeight) / 2;
        $newRight = $boxRight;
        $newTop = $boxTop - ($boxHeight - $newHeight) / 2;
    } else {
        $newWidth = $boxHeight * $aspectRatio;
        $newHeight = $boxHeight;
        $newLeft = $boxLeft + ($boxWidth - $newWidth) / 2;
        $newBottom = $boxBottom;
        $newRight = $boxLeft + $newWidth;
        $newTop = $boxTop;
    }

    return array($newLeft, $newBottom, $newRight, $newTop);
}

function pdfTextWidth($text, $font, $fontSize) {
    $width = 0;
    $chars = array_map('ord', str_split($text));
    $glyphs = $font->glyphNumbersForCharacters($chars);
    foreach ($glyphs as $glyph) {
        $width += $font->widthForGlyph($glyph);
    }
    return $width / $font->getUnitsPerEm() * $fontSize;
}

function wrapPdfText($text, $font, $fontSize, $maxWidth) {
    $words = explode(' ', $text);
    $lines = [];
    $line  = '';

    foreach ($words as $word) {
        $candidate = $line === '' ? $word : $line . ' ' . $word;
        if ($line !== '' && pdfTextWidth($candidate, $font, $fontSize) > $maxWidth) {
            $lines[] = $line;
            $line    = $word;
        } else {
            $line = $candidate;
        }
    }

    if ($line !== '') {
        $lines[] = $line;
    }

    return $lines;
}

function fitImageInBoundingBox($width, $height, $boundingBoxWidth, $boundingBoxHeight) {
    $aspectRatio = $width / $height;
    $boundingBoxAspectRatio = $boundingBoxWidth / $boundingBoxHeight;

    if ($aspectRatio > $boundingBoxAspectRatio) {
      $newWidth = $boundingBoxWidth;
      $newHeight = $newWidth / $aspectRatio;
    } else {
      $newHeight = $boundingBoxHeight;
      $newWidth = $newHeight * $aspectRatio;
    }

    return array($newWidth, $newHeight);
  }
// 792 x 612
// 744 x 468
try {
	$pdf = Zend_Pdf::load('project.pdf');

	// Set up the document.
	$string         = '';
	$name_details_y = 0;
	$page           = $pdf->pages[0];
	$template       = clone $pdf->pages[0]; // cloning the page (a must do)

	$refNumber  = $_SESSION['uuid'] ?? 'Unknown';
	$monthDir   = date('Y-m');
	$projectDir = UPLOAD_DIR . $monthDir;
	$fileSlug   = slugify($_SESSION['project_num'] ?? 'project') . '-' . date('Y-m-d');

	if (!is_dir($projectDir)) {
		mkdir($projectDir, 0755, true);
	}

	$oldPng = UPLOAD_DIR . $refNumber . '.png';
	$newPng = "{$projectDir}/{$fileSlug}.png";
	if (file_exists($oldPng)) {
		rename($oldPng, $newPng);
	}

	$pdfRelPath = "projects/{$monthDir}/{$fileSlug}"; // no extension

	// Set font
	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);

	// Set stage for main ramp image
	$image = Zend_Pdf_Image::imageWithPath($newPng);

    $imgWidth = $image->getPixelWidth();
    $imgHeight = $image->getPixelHeight();

	$imgWidthPts  = $imgWidth * 72 / 96;
	$imgHeightPts = $imgHeight * 72 / 96;

	$x1 = ($page->getWidth() - $imgWidthPts) / 2;
	$y1 = 120;

	// Draw image
	$page->drawImage($image, $x1, $y1, $x1 + $imgWidthPts, $y1 + $imgHeightPts);

	// Draw wrapped notes — box runs from x=590 to x=780, top at y=75, 10pt line height
	$notesFont     = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
	$notesFontSize = 7.8;
	$notesX        = 580;
	$notesY        = 80;
	$notesMaxWidth = 185;
	$notesLineHeight = 10;
	$page->setFont($notesFont, $notesFontSize);
	$notesLines = wrapPdfText($_SESSION['notes'] ?? '', $notesFont, $notesFontSize, $notesMaxWidth);
	foreach ($notesLines as $i => $notesLine) {
		$page->drawText($notesLine, $notesX, $notesY - ($i * $notesLineHeight));
	}
	$page->drawText($_SESSION['project_num'], 690, 44);
	$page->drawText($_SESSION['designed_by'], 545, 35);
	$page->drawText($_SESSION['email'], 600, $name_details_y -= 10);
	$page->drawText($refNumber, 677, 30); // Reference number
	$page->drawText(date('M d,Y'), 475, 35);

	// Draw in the module counts
	$x_value = 45;
	$y_value = 80;
	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD), 12);

	$num_diff_modules = 0;
	foreach ($_SESSION['mcount'] as $k => $v) {
		if ($v > 0) {
			$num_diff_modules += 1;
			if ($num_diff_modules > 3) {
				$num_diff_modules = 1;
				$x_value          += 50;
				$y_value          = 80;
			}
			$page->drawText($k . ': ' . $v, $x_value -= 0, $y_value -= 12);
		}
	}

	// Add in the slope ratio diagram
	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);

	if ($_SESSION['actual_slope'] >= 5 && $_SESSION['actual_slope'] <= 7.5) {
		$ramp_image = '1-6.jpg';
	} else if ($_SESSION['actual_slope'] >= 7.5 && $_SESSION['actual_slope'] <= 10.5) {
		$ramp_image = '1-9.jpg';
	} else if ($_SESSION['actual_slope'] >= 10.5 && $_SESSION['actual_slope'] <= 13.5) {
		$ramp_image = '1-12.jpg';
	} else if ($_SESSION['actual_slope'] >= 13.5 && $_SESSION['actual_slope'] <= 17.5) {
		$ramp_image = '1-15.jpg';
	} else if ($_SESSION['actual_slope'] >= 17.5 && $_SESSION['actual_slope'] <= 19.5) {
		$ramp_image = '1-18.jpg';
	} else {
		$ramp_image = false;
	}

	if ($ramp_image) {
		$path      = 'images/slopes/';
		$imagePath = $path . $ramp_image;
		$image     = Zend_Pdf_Image::imageWithPath($imagePath);

		$page->drawImage($image, 275, 30, 425, 74);
	} else {
		$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD), 14);
		$page->drawText('Sample Image Not Available', 235, 45);
	}

	// Add in the slope information
	$slope = $_SESSION['target_slope'];
	$rise  = $_SESSION['rise'];

	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);
	$page->drawText("1:" . $slope, 400, 85);
	$page->drawText($rise . '"', 270, 85);
	$page->drawText("1:" . $_SESSION['actual_slope'], 262, 72);

	// Create the pdf
	$_SESSION['pdf_filname'] = "{$fileSlug}.pdf";
	$pdf->save("{$pdfRelPath}.pdf");

    sendProjectEmails($_SESSION, __DIR__ . "/{$pdfRelPath}.pdf");
} catch (Zend_Pdf_Exception $e) {
	echo $e->getMessage();
}
?><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Your Ramp PDF - QRAMP Ramp Builder</title>

    <link rel="stylesheet" href="css/tachyons.css">
    <link rel="stylesheet" href="css/styles.css">

    <style>
		#the-canvas {
			aspect-ratio: 1.29/1;
		}
	</style>
</head>

<body class="tc">
<?php if (defined('DEBUG') && DEBUG) {
echo '<details><summary>Session Data</summary><pre>' . print_r($_SESSION, true) . '</pre></details>';
echo '<details><summary>Post Data</summary><pre>' . print_r($_POST, true) . '</pre></details>';
} ?>
    <header class="bb b--light-gray mb3 shadow-1">
        <div class="flex justify-between gh5 items-center lh-copy ph3">
            <a href="https://qramp.com" target="_blank" title="Visit the QRamp website">
                <img src="images/qramp-logo.png" alt="QRamp - Modular Access System" width="230" height="90">
            </a>
            <nav class="flex gv2 gh3 pa3 tc justify-between">
                <div class="flex gv2 gh3 f6">
                    <a href="/save.php">
                        <img src="images/toolbar/back.svg" alt="" width="50" height="50"><br>
                        Back to Project Details
                    </a>

                    <a href="https://qramp.com/find-a-dealer" title="Find a Dealer" target="_blank">
                        <img src="images/toolbar/search.png" alt="" width="50" height="50"><br>
                        Find a Dealer
                    </a>
                </div>
            </nav>
            <div class="tr nowrap">
                <span class="f6">For assistance please call</span><br>
                <a class="f3 fw5" href="tel:+18556977267">(855)-697-7267</a>
            </div>
        </div>
    </header>

	<?php if (!empty($_SESSION['is_dealer'])): ?>
	<p>Thank you for using our QRamp Builder tool. Our team will review your project and provide a detailed quote within 24 hours.</p>
	<?php else: ?>
	<p>Thank you for using our QRamp Builder tool. Check your in-box for an email with your next-step options.</p>
	<?php endif; ?>
	<p class="mb4">
		<a class="btn" href="<?= htmlspecialchars($pdfRelPath) ?>.pdf" download>⤵ Download PDF</a>
		<a class="btn" href="#print" onclick="printDiagram();">🖨 Print Diagram</a>
		<a class="btn" href="/index.php">Design Another Ramp</a>
	</p>

	<canvas class="db mv4 ml-auto mr-auto mw-100 h-auto b--light-gray ba shadow-1" id="the-canvas"></canvas>

	<script src="/js/pdf.js" type="module"></script>

	<script type="module">
		var url = '/<?php echo htmlspecialchars($pdfRelPath); ?>.pdf';

		// Loaded via <script> tag, create shortcut to access PDF.js exports.
		var {
			pdfjsLib
		} = globalThis;

		// The workerSrc property shall be specified.
		pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.js';

		// Asynchronous download of PDF
		var loadingTask = pdfjsLib.getDocument(url);
		loadingTask.promise.then(function(pdf) {
			var pageNumber = 1;
			pdf.getPage(pageNumber).then(function(page) {
				var scale = 1.5;
				var viewport = page.getViewport({
					scale: scale
				});

				// Prepare canvas using PDF page dimensions
				var canvas = document.getElementById('the-canvas');
				var context = canvas.getContext('2d');
				canvas.height = viewport.height;
				canvas.width = viewport.width;

				// Render PDF page into canvas context
				var renderContext = {
					canvasContext: context,
					viewport: viewport
				};
				var renderTask = page.render(renderContext);
			} );
		}, function(reason) {
			// PDF loading error
			console.error(reason);
		});
		</script>

		<script>
		function printDiagram() {
			let canvas = document.getElementById( 'the-canvas' ).toDataURL();
			let win    = window.open( '', '', 'width=800,height=600' ); ;
			let style  = `<style>
			@page {
				size: landscape;
				margin: 0;
			}
			@media print {
				html, body {
					height: 100%;
					margin: 0 !important;
					padding: 0 !important;
					overflow: hidden;
				}

				img {
					width: 100%;
					height: 100%;
					object-fit: contain;
				}
			</style>`;
			let html = `${style}<img src="${canvas}">`;

			win.document.write( html );
			win.document.close();
			win.focus();
			win.print();
			win.close();
		}
	</script>
</body>

</html>
