<?php
/* -------------------------------------------------------------------------- */
/*                                CONFIGURATION                               */
/* -------------------------------------------------------------------------- */
date_default_timezone_set("Australia/Hobart");

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

require_once 'connection.php';
include_once "dompdf/vendor/autoload.php";

use Dompdf\Dompdf;
use Dompdf\Options;

if (session_status() !== PHP_SESSION_ACTIVE) session_start();
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$csrf = $_SESSION['csrf'];

#$enquiry_date = date("l dS M 'y");
$drg = $_GET['drg'] ?? '';

if (!empty($_GET['drg'])) {
    include "table.php";
}

/* New: toggle PDF mode */
$asPdf = isset($_GET['pdf']);

/* If we are about to generate a PDF, start buffering the HTML now */
if ($asPdf) {
    ob_start();
}
?>
<!doctype html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= htmlspecialchars($drg) ?> - Manilla Folder Label</title>
        <link rel="shortcut icon" href="images/blueprint.ico" type="image/x-icon">
        <!-- normal view keeps external CSS -->
        <?php if (!$asPdf): ?>
        <link href="css/bootstrap.css" rel="stylesheet">
        <link href="css/blueprint.css" rel="stylesheet">
        <link href="css/print.css" rel="stylesheet" media="print">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
        <?php else: ?>
        <style>
            <?php
            // Inline local CSS so Dompdf reads it from disk
            foreach (['css/bootstrap.css', 'css/blueprint.css', 'css/print.css'] as $file) {
                $path = __DIR__ . '/' . $file;
                if (is_readable($path)) {
                    echo "/* $file */\n" . file_get_contents($path) . "\n";
                }
            }
            ?>

            /* PDF-only fallbacks for Bootstrap bits Dompdf struggles with */            
			.container-fluid { width: 100%; padding: 0 12px; color: #000; }
            .row { display: block; margin: 0; }
            .col-md-12 { width: 100%; padding: 0; }
            .fw-bold { font-weight: 700; }
            .small { font-size: 0.875rem; }
			.mb-0 {margin-bottom:0cm;line-height:0.9rem;}
            h3 {font-size: 1.75rem;}
			.h4 {font-size: 1.5rem;}
            @page { size: 320mm 243mm; margin: 0.08cm 0.25cm 0.25cm 0.25cm; }
        </style>
        <?php endif; ?>
    </head>

    <body style="background-color:#fff !important;">
        <?php if (!$asPdf): ?>
        <nav class="navbar bg-brown-dark brown-light border-bottom border-body d-print-none" data-bs-theme="dark">
            <div class="container-fluid">
                <a class="navbar-brand brown-light" href="dashboard.php">
                    <img src="images/blueprint-logo-light.png" alt="Logo" width="30" height="24" class="d-inline-block align-text-top">
                    Modulos Design
                </a>
                <div class="ms-auto d-flex gap-2">
                    <a href="dashboard.php" class="btn btn-sm btn-outline-light"><i class="bi bi-grid-fill"></i> Dashboard</a>
                    <?php if (!empty($drg)): ?><a href="client-brief.php?drg=<?= (int)$drg ?>" class="btn btn-sm btn-outline-light"><i class="bi bi-person-fill"></i> Client Brief</a><?php endif; ?>
                    <a class="btn btn-sm btn-outline-light" href="?drg=<?= urlencode($drg) ?>&pdf=1"><i class="bi bi-file-earmark-arrow-down"></i> Download PDF</a>
                </div>
            </div>
        </nav>
        <?php endif; ?>

        <div class="container-fluid">
            <div class="row ms-3 mx-auto p-0 plaque">
                <div class="plate pt-0 px-0">
        			<div class="col-md-12 mb-5">
                        <p><span class="fw-bold"><?= htmlspecialchars($drg) ?></span> - <?= htmlspecialchars($site_address ?? '') ?></p>
                    </div>
                    <div class="col-md-12 mb-0">
                        <h3><span class="fw-bold"><?= htmlspecialchars($drg) ?></span> - <?= htmlspecialchars($joint_name ?? '') ?></h3>
                    </div>
                    <div class="col-md-12 ms-5 mt-3 mb-0 small">
                        <p class="mb-0 fw-bold">CLIENT:</p>
                        <p class="mb-0"><?= htmlspecialchars(($firstname ?? '') . ' ' . ($lastname ?? '')) ?></p>
                        <p class="mb-0"><?= htmlspecialchars($joint_name ?? '') ?></p>
                        <p class="mb-0"><b>MOB:</b> <?= htmlspecialchars($client_mobile ?? '') ?></p>
                        <p class="mb-0"><b>EMAIL:</b> <?= htmlspecialchars($client_email ?? '') ?></p><br>
                        <p class="mb-0 fw-bold">SITE DETAILS:</p>
                        <p class="mb-0"><?= htmlspecialchars($site_address ?? '') ?></p>
                        <p class="mb-0"><b>TITLE:</b> <?= htmlspecialchars($title_id ?? '') ?> <b>PID:</b> <?= htmlspecialchars($property_id ?? '') ?></p>
                        <p class="mb-0"><b>Planning Zone:</b> <?= htmlspecialchars($planning_zones ?? '') ?></p>
                        <p class="h4 mt-3 mb-0"><b>Date:</b> <?= htmlspecialchars(date('M Y',strtotime($enquiry_date)) ?? date("M Y")) ?></p>
                    </div>
                </div>
            </div>
        </div>

    </body>
</html>
<?php
    /* If PDF requested, capture the HTML and stream a PDF */
    if ($asPdf) {
        $html = ob_get_clean();

        $options = new Options();
        $options->set('isRemoteEnabled', true);   // allow CDN CSS and images
        $options->set('isHtml5ParserEnabled', true);
        $options->setChroot(__DIR__);

        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html, 'UTF-8');

        // Custom paper size in points. 1 mm = 2.83465 pt
        $MM = 2.83465;
        $widthPt  = 320 * $MM;
        $heightPt = 239 * $MM;
        $dompdf->setPaper([0, 0, $widthPt, $heightPt], 'landscape');

        $dompdf->render();

        // Nice filename fallback if pieces are missing
        $file = trim(($drg ?? 'label')) . ' - Manilla Folder Label.pdf';

        // true => force download. set to false to open in browser
        $dompdf->stream($file, ['Attachment' => true]);
        exit;
    }
?>