<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('gr_pdf_column_exists')) {
    function gr_pdf_column_exists(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];
        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) {
            return $cache[$key];
        }

        try {
            $stmt = $pdo->prepare("\n                SELECT COUNT(*)\n                FROM INFORMATION_SCHEMA.COLUMNS\n                WHERE TABLE_SCHEMA = DATABASE()\n                  AND TABLE_NAME = :table_name\n                  AND COLUMN_NAME = :column_name\n            ");
            $stmt->execute([
                ':table_name'  => $table,
                ':column_name' => $column,
            ]);
            $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$key] = false;
        }

        return $cache[$key];
    }
}

if (!function_exists('gr_pdf_format_date')) {
    function gr_pdf_format_date($value): string
    {
        if (!$value) return '';
        $ts = strtotime((string)$value);
        return $ts ? date('d M Y', $ts) : (string)$value;
    }
}

if (!function_exists('gr_pdf_clean')) {
    function gr_pdf_clean($value): string
    {
        return trim((string)$value);
    }
}

if (!function_exists('gr_pdf_value')) {
    function gr_pdf_value($value, string $fallback = ''): string
    {
        $value = trim((string)$value);
        return $value !== '' ? $value : $fallback;
    }
}

if (!function_exists('gr_pdf_money')) {
    function gr_pdf_money($amount): string
    {
        return number_format((float)$amount, 2, '.', ',');
    }
}

$orderId = (int)($_GET['order_id'] ?? $_GET['id'] ?? 0);
if ($orderId <= 0) {
    die('Missing booking/order ID.');
}

/* Optional registration + indemnity storage columns on orders. Safe best-effort additions. */
$optionalOrderColumns = [
    'registration_no'          => "ALTER TABLE orders ADD COLUMN registration_no VARCHAR(50) NULL",
    'guest_id_number'          => "ALTER TABLE orders ADD COLUMN guest_id_number VARCHAR(100) NULL",
    'guest_passport_no'        => "ALTER TABLE orders ADD COLUMN guest_passport_no VARCHAR(100) NULL",
    'guest_nationality'        => "ALTER TABLE orders ADD COLUMN guest_nationality VARCHAR(100) NULL",
    'guest_phone'              => "ALTER TABLE orders ADD COLUMN guest_phone VARCHAR(100) NULL",
    'guest_email'              => "ALTER TABLE orders ADD COLUMN guest_email VARCHAR(150) NULL",
    'guest_address'            => "ALTER TABLE orders ADD COLUMN guest_address TEXT NULL",
    'vehicle_reg_no'           => "ALTER TABLE orders ADD COLUMN vehicle_reg_no VARCHAR(100) NULL",
    'arrival_time'             => "ALTER TABLE orders ADD COLUMN arrival_time VARCHAR(20) NULL",
    'departure_time'           => "ALTER TABLE orders ADD COLUMN departure_time VARCHAR(20) NULL",
    'special_requests'         => "ALTER TABLE orders ADD COLUMN special_requests TEXT NULL",
    'registration_notes'       => "ALTER TABLE orders ADD COLUMN registration_notes TEXT NULL",
    'guest_signature_name'     => "ALTER TABLE orders ADD COLUMN guest_signature_name VARCHAR(150) NULL",
    'guest1_signature_name'    => "ALTER TABLE orders ADD COLUMN guest1_signature_name VARCHAR(150) NULL",
    'guest2_signature_name'    => "ALTER TABLE orders ADD COLUMN guest2_signature_name VARCHAR(150) NULL",
    'indemnity_accepted'       => "ALTER TABLE orders ADD COLUMN indemnity_accepted TINYINT(1) NOT NULL DEFAULT 0",
    'indemnity_signed_at'      => "ALTER TABLE orders ADD COLUMN indemnity_signed_at DATETIME NULL",
    'registration_signed_at'   => "ALTER TABLE orders ADD COLUMN registration_signed_at DATETIME NULL",
];

foreach ($optionalOrderColumns as $column => $ddl) {
    if (!gr_pdf_column_exists($pdo, 'orders', $column)) {
        try { $pdo->exec($ddl); } catch (Throwable $e) {}
    }
}

/* TCPDF loader */
$tcpdfLoaded = false;
$tcpdfPaths = [
    __DIR__ . '/../../vendor/autoload.php',
    __DIR__ . '/../../tcpdf/tcpdf.php',
    __DIR__ . '/../../includes/tcpdf/tcpdf.php',
    __DIR__ . '/../../../tcpdf/tcpdf.php',
    $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php',
    $_SERVER['DOCUMENT_ROOT'] . '/tcpdf/tcpdf.php',
];

foreach ($tcpdfPaths as $path) {
    if ($path && file_exists($path)) {
        require_once $path;
        $tcpdfLoaded = true;
        break;
    }
}

if (!$tcpdfLoaded || !class_exists('TCPDF')) {
    die('TCPDF not found. Please install TCPDF or check the path.');
}

$guestPhoneExpr = "''";
if (gr_pdf_column_exists($pdo, 'guests', 'phone')) $guestPhoneExpr = 'g.phone';
elseif (gr_pdf_column_exists($pdo, 'guests', 'mobile')) $guestPhoneExpr = 'g.mobile';
elseif (gr_pdf_column_exists($pdo, 'guests', 'telephone')) $guestPhoneExpr = 'g.telephone';

$guestEmailExpr = gr_pdf_column_exists($pdo, 'guests', 'email') ? 'g.email' : "''";

$stmt = $pdo->prepare("\n    SELECT\n        o.*,\n        p.name AS property_name,\n        p.code AS property_code,\n        g.firstname,\n        g.lastname,\n        {$guestPhoneExpr} AS guest_phone_master,\n        {$guestEmailExpr} AS guest_email_master,\n        CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) AS agent_name\n    FROM orders o\n    LEFT JOIN properties p ON p.id = o.property_id\n    LEFT JOIN guests g ON g.id = o.guest_id\n    LEFT JOIN agents a ON a.id = o.agent_id\n    WHERE o.id = :id\n    LIMIT 1\n");
$stmt->execute([':id' => $orderId]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    die('Booking not found.');
}

$stmt = $pdo->prepare("\n    SELECT\n        rmg.*,\n        r.room_no,\n        rt.title AS room_type\n    FROM order_rooming rmg\n    LEFT JOIN rooms r ON r.id = rmg.room_id\n    LEFT JOIN room_types rt ON rt.id = rmg.room_type_id\n    WHERE rmg.order_id = :id\n    ORDER BY COALESCE(r.room_no, ''), rmg.id ASC\n");
$stmt->execute([':id' => $orderId]);
$rooms = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$guestName = trim((string)($order['firstname'] ?? '') . ' ' . (string)($order['lastname'] ?? ''));
if ($guestName === '') $guestName = 'Guest';

$registrationNo = gr_pdf_value($order['registration_no'] ?? '', 'REG-' . str_pad((string)$orderId, 6, '0', STR_PAD_LEFT));
$propertyName = gr_pdf_value($order['property_name'] ?? '', 'Pioneers Lodge');
$propertyCode = gr_pdf_clean($order['property_code'] ?? '');
$propertyLabel = $propertyName . ($propertyCode !== '' ? ' (' . $propertyCode . ')' : '');
$bookingNo = gr_pdf_value($order['order_no'] ?? '', '#' . $orderId);
$agentName = gr_pdf_value(trim((string)($order['agent_name'] ?? '')), 'Direct');
$guestPhone = gr_pdf_value($order['guest_phone'] ?? '', gr_pdf_clean($order['guest_phone_master'] ?? ''));
$guestEmail = gr_pdf_value($order['guest_email'] ?? '', gr_pdf_clean($order['guest_email_master'] ?? ''));
$guestSignatureName = gr_pdf_value($order['guest1_signature_name'] ?? '', gr_pdf_value($order['guest_signature_name'] ?? '', $guestName));
$guest2SignatureName = gr_pdf_clean($order['guest2_signature_name'] ?? '');

$roomNumbers = [];
$roomTypes = [];
foreach ($rooms as $room) {
    $roomNo = gr_pdf_clean($room['room_no'] ?? '');
    if ($roomNo !== '') $roomNumbers[] = $roomNo;
    $roomType = gr_pdf_clean($room['room_type'] ?? '');
    if ($roomType !== '') $roomTypes[] = $roomType;
}
$roomNumberText = $roomNumbers ? implode(', ', array_unique($roomNumbers)) : gr_pdf_clean($order['room_id'] ?? '');
$roomTypeText = $roomTypes ? implode(', ', array_unique($roomTypes)) : '';

class GuestRegistrationPDF extends TCPDF
{
    public string $propertyName = 'Pioneers Lodge';
    public string $bookingNo = '';
    public string $registrationNo = '';

    public function Header()
    {
        $this->SetY(8);
        $logoCandidates = [
            __DIR__ . '/../../assets/img/pioneers-logo.png',
            __DIR__ . '/../../assets/pioneers-logo.png',
            __DIR__ . '/../../images/pioneers-logo.png',
            __DIR__ . '/../../uploads/pioneers-logo.png',
            __DIR__ . '/../../assets/img/logo.png',
            __DIR__ . '/../../images/logo.png',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/assets/img/pioneers-logo.png',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/assets/img/logo.png',
        ];

        $logo = '';
        foreach ($logoCandidates as $candidate) {
            if ($candidate && file_exists($candidate)) {
                $logo = $candidate;
                break;
            }
        }

        if ($logo !== '') {
            $this->Image($logo, 12, 8, 42, 0, '', '', '', false, 300);
        } else {
            $this->SetFont('helvetica', 'B', 20);
            $this->SetTextColor(82, 56, 47);
            $this->Cell(70, 8, strtoupper($this->propertyName), 0, 0, 'L');
        }

        $this->SetTextColor(40, 40, 40);
        $this->SetFont('helvetica', 'B', 12);
        $this->SetXY(112, 8);
        $this->Cell(86, 6, 'GUEST REGISTRATION & INDEMNITY', 0, 1, 'R');
        $this->SetFont('helvetica', '', 8);
        $this->SetX(112);
        $this->Cell(86, 5, 'Booking: ' . $this->bookingNo . ' | Reg: ' . $this->registrationNo, 0, 1, 'R');
        $this->SetDrawColor(210, 210, 210);
        $this->Line(12, 25, 198, 25);
    }

    public function Footer()
    {
        $this->SetY(-12);
        $this->SetFont('helvetica', '', 7);
        $this->SetTextColor(120, 120, 120);
        $this->Cell(0, 5, 'Generated: ' . date('Y-m-d H:i') . ' | Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, 0, 'C');
    }
}

$pdf = new GuestRegistrationPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->propertyName = $propertyName;
$pdf->bookingNo = $bookingNo;
$pdf->registrationNo = $registrationNo;
$pdf->SetCreator('Rooms PMS');
$pdf->SetAuthor($propertyName);
$pdf->SetTitle('Guest Registration - ' . $bookingNo);
$pdf->SetSubject('Guest Registration and Disclaimer Indemnity');
$pdf->SetMargins(12, 31, 12);
$pdf->SetHeaderMargin(6);
$pdf->SetFooterMargin(8);
$pdf->SetAutoPageBreak(true, 15);
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 9);
$pdf->SetTextColor(30, 30, 30);

$font = 'helvetica';
$greyFill = [245, 247, 250];
$darkFill = [82, 82, 82];
$lineGrey = [210, 216, 224];

$esc = function ($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
};

$drawBand = function (string $title) use ($pdf, $font, $darkFill) {
    $pdf->SetFillColor($darkFill[0], $darkFill[1], $darkFill[2]);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFont($font, 'B', 9);
    $pdf->Cell(0, 7, '  ' . $title, 0, 1, 'L', true);
    $pdf->SetTextColor(30, 30, 30);
    $pdf->Ln(2);
};

$field = function (string $label, string $value, float $w, float $h = 8) use ($pdf, $font, $esc, $greyFill, $lineGrey) {
    $x = $pdf->GetX();
    $y = $pdf->GetY();
    $pdf->SetDrawColor($lineGrey[0], $lineGrey[1], $lineGrey[2]);
    $pdf->SetFillColor($greyFill[0], $greyFill[1], $greyFill[2]);
    $pdf->Rect($x, $y, $w, $h, 'DF');
    $pdf->SetXY($x + 2, $y + 1.2);
    $pdf->SetFont($font, 'B', 6.8);
    $pdf->SetTextColor(105, 115, 130);
    $pdf->Cell($w - 4, 3, strtoupper($label), 0, 2, 'L');
    $pdf->SetFont($font, '', 8.2);
    $pdf->SetTextColor(25, 25, 25);
    $pdf->MultiCell($w - 4, 3.5, $esc($value), 0, 'L', false, 0);
    $pdf->SetXY($x + $w + 2, $y);
};

$signatureLine = function (string $label, string $name = '') use ($pdf, $font, $esc) {
    $x = $pdf->GetX();
    $y = $pdf->GetY();
    $w = 86;
    $pdf->SetFont($font, 'B', 7.5);
    $pdf->SetTextColor(40, 40, 40);
    $pdf->Cell($w, 4, $label, 0, 2, 'L');
    $pdf->SetDrawColor(40, 40, 40);
    $pdf->Line($x + 28, $y + 12, $x + $w, $y + 12);
    $pdf->SetFont($font, '', 7.5);
    $pdf->SetXY($x, $y + 14);
    $pdf->Cell($w, 4, 'Print Name: ' . $esc($name), 0, 2, 'L');
    $pdf->Cell($w, 4, 'Date: ___________________________', 0, 0, 'L');
};

/* PAGE 1 - Registration */
$drawBand('BOOKING DETAILS');
$field('Date', date('d M Y'), 45);
$field('Registration No', $registrationNo, 45);
$field('Booking No', $bookingNo, 45);
$field('Room Number(s)', $roomNumberText, 45);
$pdf->Ln(10);
$field('Arrival Date', gr_pdf_format_date($order['check_in'] ?? ''), 58);
$field('Departure Date', gr_pdf_format_date($order['check_out'] ?? ''), 58);
$field('Arrival Time', gr_pdf_clean($order['arrival_time'] ?? ''), 32);
$field('Departure Time', gr_pdf_clean($order['departure_time'] ?? ''), 32);
$pdf->Ln(10);
$field('Property', $propertyLabel, 88);
$field('Agent / Bill To', $agentName, 88);
$pdf->Ln(10);
$field('Room Type(s)', $roomTypeText, 88);
$field('Vehicle Registration', gr_pdf_clean($order['vehicle_reg_no'] ?? ''), 88);
$pdf->Ln(12);

$drawBand('GUEST 1');
$field('Full Name', $guestName, 88);
$field('Passport / ID Number', gr_pdf_value($order['guest_passport_no'] ?? '', gr_pdf_clean($order['guest_id_number'] ?? '')), 88);
$pdf->Ln(10);
$field('Nationality', gr_pdf_clean($order['guest_nationality'] ?? ''), 58);
$field('Contact #', $guestPhone, 58);
$field('Email Address', $guestEmail, 58);
$pdf->Ln(10);
$field('Address', gr_pdf_clean($order['guest_address'] ?? ''), 178, 14);
$pdf->Ln(17);

$drawBand('GUEST 2');
$field('Full Name', '', 88);
$field('Passport #', '', 88);
$pdf->Ln(10);
$field('Nationality', '', 58);
$field('Contact #', '', 58);
$field('Email Address', '', 58);
$pdf->Ln(10);
$field('Address', '', 178, 14);
$pdf->Ln(17);

$drawBand('ADDITIONAL GUESTS / ROOMING');
if (!$rooms) {
    $pdf->SetFont($font, '', 8);
    $pdf->Cell(0, 6, 'No rooming lines found.', 0, 1, 'L');
} else {
    $pdf->SetFillColor(240, 242, 245);
    $pdf->SetTextColor(60, 60, 60);
    $pdf->SetFont($font, 'B', 7.2);
    $pdf->Cell(26, 6, 'ROOM', 1, 0, 'L', true);
    $pdf->Cell(58, 6, 'ROOM TYPE', 1, 0, 'L', true);
    $pdf->Cell(24, 6, 'ADULTS', 1, 0, 'C', true);
    $pdf->Cell(24, 6, 'CHILDREN', 1, 0, 'C', true);
    $pdf->Cell(23, 6, 'CHECK-IN', 1, 0, 'C', true);
    $pdf->Cell(23, 6, 'CHECK-OUT', 1, 1, 'C', true);
    $pdf->SetFont($font, '', 7.2);
    $pdf->SetTextColor(30, 30, 30);
    foreach ($rooms as $room) {
        $pdf->Cell(26, 6, $esc(gr_pdf_value($room['room_no'] ?? '', gr_pdf_clean($room['room_id'] ?? ''))), 1, 0, 'L');
        $pdf->Cell(58, 6, $esc(gr_pdf_clean($room['room_type'] ?? '')), 1, 0, 'L');
        $pdf->Cell(24, 6, (string)(int)($room['adults'] ?? 0), 1, 0, 'C');
        $pdf->Cell(24, 6, (string)(int)($room['children'] ?? 0), 1, 0, 'C');
        $pdf->Cell(23, 6, $esc(gr_pdf_format_date($room['check_in'] ?? ($order['check_in'] ?? ''))), 1, 0, 'C');
        $pdf->Cell(23, 6, $esc(gr_pdf_format_date($room['check_out'] ?? ($order['check_out'] ?? ''))), 1, 1, 'C');
    }
}

$pdf->Ln(4);
$field('Special Requests', gr_pdf_clean($order['special_requests'] ?? ''), 178, 14);
$pdf->Ln(17);
$field('Registration Notes', gr_pdf_clean($order['registration_notes'] ?? ''), 178, 14);
$pdf->Ln(18);

$pdf->SetFillColor(255, 252, 235);
$pdf->SetDrawColor(235, 206, 120);
$pdf->SetFont($font, '', 7.8);
$pdf->MultiCell(0, 8, 'I / We confirm that the guest details above are true and correct and form part of the Disclaimer & Indemnity signed below.', 1, 'L', true, 1);
$pdf->Ln(4);
$signatureLine('Guest 1 Signature:', $guestSignatureName);
$pdf->SetXY(108, $pdf->GetY() - 22);
$signatureLine('Guest 2 Signature:', $guest2SignatureName);

/* PAGE 2 - Indemnity */
$pdf->AddPage();
$drawBand('PIONEERS LODGE (PRIVATE) TRADING AS PIONEERS LODGE - DISCLAIMER & INDEMNITY');

$terms = [
    ['1.', 'Introduction', true],
    ['1.1', 'Pioneers Lodge (PVT) Ltd, Registration Number 241/2019 ("the Company") operates Pioneers Lodge ("the Lodge") and conducts the activities described herein for guests.', false],
    ['1.2', 'The guest and members of the guest party (including any minor children), whose names and particulars appear on the registration form, will be accommodated at the Lodge and will utilize the facilities and grounds of the Lodge, and may book activities from the Lodge activities desk, subject to the terms and conditions set out herein.', false],
    ['2.', 'Disclaimer and Indemnity', true],
    ['2.1', 'The Company and its shareholders, directors, employees and representatives (collectively referred to as "the Indemnified Parties"), are not liable for any loss or damage to any property of the Guest/s or injury to or death of the Guest/s, howsoever arising, even if such loss, damage, injury or death has been occasioned by the negligence (including gross negligence) of one or more of the Indemnified Parties.', false],
    ['2.2', 'The Guest/s partakes in the Activities entirely at the Guest/s own risk.', false],
    ['2.3', 'The Guest/s accordingly waive all claims of any nature whatsoever which the Guest/s or his/her deceased estate ("Estate") may have against the Indemnified Parties, arising from the death of or injury or the loss of or damage to any Guest property, even if such death or injury or loss or damage has been occasioned by negligence (including gross negligence) of the Indemnified Parties. The Guest/s hereby indemnifies and holds harmless each of the Indemnified Parties against all loss or damage arising from any claim which may be brought against any one of them by any of the Guest/s dependants, in respect of any such death, injury, loss or damage.', false],
    ['2.4', 'The Guest/s acknowledges that participation in the Activities will expose the Guest/s to various risks and dangers inherent in or directly or indirectly associated with the Activities.', false],
    ['2.5', 'The Guest/s further acknowledges that:', false],
    ['2.5.1', 'The Guest/s is obliged to exercise his/her own independent judgement in participating in the Activities and evaluating the Risks.', false],
    ['2.5.2', 'It is not possible for the Indemnified Parties to give any representation or warranty, whether expressed or implied, that the Risks will not materialise, even when the Activities are undertaken with the supervision of a trained guide/s or in accordance with the Company guidelines.', false],
    ['2.5.3', 'In the event of any accident or injury, the Indemnified Parties:', false],
    ['2.5.3.1', 'shall provide the immediate first aid treatment of the Guest/s and the evacuation/transfer of the Guest/s to the nearest available medical care center/doctor, which medical care center/doctor may be remote and during evacuation, proper medical assistance may be limited or non-existent;', false],
    ['2.5.3.2', 'may (in their sole discretion) meet with some of the medical treatment/transfers/accommodation costs of the Guest/s occasioned by the accident or injury, which payment/s shall be a voluntary gesture in good faith without any admission of liability on part of the Indemnified Parties and without prejudice to any of the Indemnified Parties rights in terms hereof, or otherwise in law.', false],
    ['2.5.4', 'This disclaimer and indemnity will be binding on the Guest Estate.', false],
    ['2.5.5', 'If any term or provision of this agreement is found to be illegal or unenforceable then such term shall be severable and the remaining terms and provisions hereof shall be and remain binding and of full force and effect.', false],
];

$pdf->SetFont($font, '', 7.3);
$pdf->SetTextColor(25, 25, 25);
foreach ($terms as $term) {
    [$num, $text, $heading] = $term;
    $pdf->SetFont($font, $heading ? 'B' : '', $heading ? 7.5 : 7.1);
    $pdf->MultiCell(13, 4.4, $esc($num), 0, 'L', false, 0);
    $pdf->MultiCell(165, 4.4, $esc($text), 0, 'L', false, 1);
    if ($heading) $pdf->Ln(0.7);
}

$pdf->Ln(1.5);
$pdf->SetFont($font, 'B', 7.5);
$pdf->MultiCell(0, 5, 'The Guest/s warrants that the Guest/s is in a sufficiently good physical and mental condition to take part in the Activities.', 0, 'L', false, 1);

$pdf->Ln(4);
$pdf->SetFillColor(245, 247, 250);
$pdf->SetDrawColor(210, 216, 224);
$pdf->SetFont($font, 'B', 8);
$pdf->MultiCell(0, 6, 'ACKNOWLEDGEMENT AND SIGNATURES', 1, 'L', true, 1);
$pdf->SetFont($font, '', 7.5);
$pdf->MultiCell(0, 8, 'By signing below, the Guest/s confirm that they have read, understood and accepted the Disclaimer & Indemnity above for themselves and, where applicable, for members of their party including minors.', 'LRB', 'L', false, 1);
$pdf->Ln(5);

$y = $pdf->GetY();
$signatureLine('Guest 1 Signature:', $guestSignatureName);
$pdf->SetXY(108, $y);
$signatureLine('Guest 2 Signature:', $guest2SignatureName);
$pdf->Ln(27);
$signatureLine('Front Desk Representative:', '');
$pdf->SetXY(108, $pdf->GetY() - 22);
$signatureLine('Manager / Witness:', '');

$pdf->Ln(6);
$pdf->SetFont($font, '', 7);
$pdf->SetTextColor(100, 100, 100);
$pdf->MultiCell(0, 5, 'This document combines the guest registration particulars with the Pioneers Lodge disclaimer and indemnity wording for signature at check-in.', 0, 'C', false, 1);

$filename = 'Guest_Registration_Indemnity_' . preg_replace('/[^A-Za-z0-9_-]+/', '_', $bookingNo) . '.pdf';
$pdf->Output($filename, 'I');
exit;
