<?php
// bulk_guest_registration_tomorrow.php
// Put this file under: /rooms/modules/reservations/
// Daily Reports -> Bulk print tomorrow's Guest Registration Forms.
// NEW: Bulk Print now generates ONE combined PDF document with one registration form per rooming/booking,
// ordered by property, room number, guest, booking and rooming id.

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

$pageTitle = 'Bulk Guest Registration Forms';

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

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

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

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

        return $cache[$key];
    }
}

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

        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = :table_name
                  AND COLUMN_NAME = :column_name
            ");
            $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('bgr_first_existing_file')) {
    function bgr_first_existing_file(array $paths): string
    {
        foreach ($paths as $path) {
            if ($path && is_file($path)) return $path;
        }
        return '';
    }
}

if (!function_exists('bgr_guest_value')) {
    function bgr_guest_value(array $guest, array $keys, string $fallback = ''): string
    {
        foreach ($keys as $key) {
            if (isset($guest[$key]) && trim((string)$guest[$key]) !== '') {
                return trim((string)$guest[$key]);
            }
        }
        return $fallback;
    }
}

if (!function_exists('bgr_guest_full_name')) {
    function bgr_guest_full_name(array $guest, string $fallback = ''): string
    {
        $name = trim((string)($guest['first_name'] ?? '') . ' ' . (string)($guest['last_name'] ?? ''));
        if ($name !== '') return $name;
        $name = trim((string)($guest['firstname'] ?? '') . ' ' . (string)($guest['lastname'] ?? ''));
        if ($name !== '') return $name;
        $name = trim((string)($guest['guest_name'] ?? ''));
        if ($name !== '') return $name;
        return $fallback;
    }
}

if (!function_exists('bgr_line_value')) {
    function bgr_line_value(TCPDF $pdf, float $x, float $y, string $label, string $value, float $labelW, float $lineW, float $font = 8.0, bool $valueBold = false): void
    {
        $pdf->SetXY($x, $y);
        $pdf->SetFont('helvetica', 'B', $font);
        $pdf->Cell($labelW, 4, $label, 0, 0, 'L');

        $lineX = $x + $labelW;
        $lineY = $y + 3.2;
        $pdf->Line($lineX, $lineY, $lineX + $lineW, $lineY);

        if (trim($value) !== '') {
            $pdf->SetXY($lineX + 1, $y - 0.2);
            $pdf->SetFont('helvetica', $valueBold ? 'B' : '', $font);
            $pdf->Cell($lineW - 2, 4, $value, 0, 0, 'C');
        }
    }
}

if (!function_exists('bgr_guest_block')) {
    function bgr_guest_block(TCPDF $pdf, float $y, string $title, array $guest): void
    {
        $fullName    = bgr_guest_full_name($guest, '');
        $passport    = bgr_guest_value($guest, ['passport_no', 'passport_number', 'id_number']);
        $nationality = bgr_guest_value($guest, ['nationality']);
        $contact     = bgr_guest_value($guest, ['phone', 'contact_no', 'mobile']);
        $address     = bgr_guest_value($guest, ['address']);
        $email       = bgr_guest_value($guest, ['email']);

        $pdf->SetFont('helvetica', 'B', 8.2);
        $pdf->SetXY(8, $y);
        $pdf->Cell(30, 4, $title, 0, 1, 'L');
        $pdf->Line(8, $y + 4.2, 27, $y + 4.2);

        bgr_line_value($pdf, 8,   $y + 7,  'Full Name:',     strtoupper($fullName), 19, 72, 8.0, true);
        bgr_line_value($pdf, 101, $y + 7,  'Passport #:',    $passport,    21, 78, 8.0);
        bgr_line_value($pdf, 8,   $y + 14, 'Nationality:',   $nationality, 22, 69, 8.0);
        bgr_line_value($pdf, 101, $y + 14, 'Contact #:',     $contact,     20, 79, 8.0);
        bgr_line_value($pdf, 8,   $y + 21, 'Address:',       $address,     15, 177, 8.0);
        bgr_line_value($pdf, 8,   $y + 28, 'Email address:', $email,       26, 166, 8.0);
    }
}

if (!function_exists('bgr_fetch_arrivals')) {
    function bgr_fetch_arrivals(PDO $pdo, int $propertyId, string $printDate): array
    {
        if (!bgr_table_exists($pdo, 'orders') || !bgr_table_exists($pdo, 'order_rooming')) {
            throw new RuntimeException('Required booking/rooming tables were not found.');
        }

        $guestNameSql = "''";
        if (bgr_table_exists($pdo, 'guests') && bgr_column_exists($pdo, 'orders', 'guest_id')) {
            $guestNameSql = "(SELECT TRIM(CONCAT(COALESCE(g.firstname,''), ' ', COALESCE(g.lastname,''))) FROM guests g WHERE g.id = o.guest_id LIMIT 1)";
        }

        $actualRoomSql = bgr_table_exists($pdo, 'rooms') ? "COALESCE(rm.room_no, rmg.room_no)" : "rmg.room_no";
        $roomJoinSql = bgr_table_exists($pdo, 'rooms') ? "LEFT JOIN rooms rm ON rm.id = rmg.room_id" : "";

        $roomTypeSelectSql = "'' AS room_type_title";
        $roomTypeJoinSql = "";
        if (bgr_table_exists($pdo, 'room_types')) {
            $roomTypeIdSql = bgr_column_exists($pdo, 'order_rooming', 'room_type_id')
                ? "COALESCE(rmg.room_type_id, o.room_type_id)"
                : "o.room_type_id";
            $roomTypeSelectSql = "rt.title AS room_type_title";
            $roomTypeJoinSql = "LEFT JOIN room_types rt ON rt.id = ({$roomTypeIdSql})";
        }

        $checkedInExpr = bgr_column_exists($pdo, 'order_rooming', 'checked_in_status') ? "COALESCE(rmg.checked_in_status,0)" : "0";
        $checkedOutExpr = bgr_column_exists($pdo, 'order_rooming', 'checked_out_status') ? "COALESCE(rmg.checked_out_status,0)" : "0";

        $orderNoSql = bgr_column_exists($pdo, 'orders', 'order_no') ? "o.order_no" : "CAST(o.id AS CHAR)";
        $statusSql = bgr_column_exists($pdo, 'orders', 'status') ? "o.status" : "1";

        $propertySelectSql = "'' AS property_name, '' AS property_code";
        $propertyJoinSql = "";
        if (bgr_table_exists($pdo, 'properties') && bgr_column_exists($pdo, 'orders', 'property_id')) {
            $propertySelectSql = "p.name AS property_name, p.code AS property_code";
            $propertyJoinSql = "LEFT JOIN properties p ON p.id = o.property_id";
        }

        $params = [':check_in' => $printDate];

        $where = "
            WHERE rmg.check_in = :check_in
              AND {$checkedInExpr} = 0
              AND {$checkedOutExpr} = 0
        ";

        if (bgr_column_exists($pdo, 'orders', 'status')) {
            $where .= "
              AND LOWER(TRIM(CAST(o.status AS CHAR))) NOT IN ('0','cancelled','canceled','void','deleted','no_show','noshow','4','checked_out','checkout','completed')
            ";
        }

        if ($propertyId > 0 && bgr_column_exists($pdo, 'orders', 'property_id')) {
            $where .= " AND o.property_id = :property_id ";
            $params[':property_id'] = $propertyId;
        }

        $guestCountSql = "0";
        if (bgr_table_exists($pdo, 'order_rooming_guests')) {
            $linkCol = '';
            foreach (['rooming_id','order_rooming_id'] as $candidate) {
                if (bgr_column_exists($pdo, 'order_rooming_guests', $candidate)) {
                    $linkCol = $candidate;
                    break;
                }
            }
            if ($linkCol !== '') {
                $guestCountSql = "(SELECT COUNT(*) FROM order_rooming_guests org WHERE org.`{$linkCol}` = rmg.id)";
            }
        }

        $sql = "
            SELECT
                o.id AS order_id,
                {$orderNoSql} AS order_no,
                {$statusSql} AS status,
                {$guestNameSql} AS lead_guest_name,
                {$propertySelectSql},
                rmg.id AS rooming_id,
                rmg.check_in,
                rmg.check_out,
                {$actualRoomSql} AS room_no,
                {$roomTypeSelectSql},
                {$guestCountSql} AS guest_count
            FROM order_rooming rmg
            INNER JOIN orders o ON o.id = rmg.order_id
            {$roomJoinSql}
            {$roomTypeJoinSql}
            {$propertyJoinSql}
            {$where}
            ORDER BY property_name ASC, CAST({$actualRoomSql} AS UNSIGNED) ASC, {$actualRoomSql} ASC, lead_guest_name ASC, o.id ASC, rmg.id ASC
        ";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

if (!function_exists('bgr_fetch_registration_data')) {
    function bgr_fetch_registration_data(PDO $pdo, int $orderId, int $roomingId): array
    {
        $guestSelectExtra = [];
        foreach ([
            'id_type', 'id_number', 'passport_no', 'passport_number', 'nationality',
            'gender', 'date_of_birth', 'phone', 'contact_no', 'mobile', 'email',
            'address', 'signature_data', 'registration_notes',
            'bed_config', 'bed_configuration', 'room_config', 'room_configuration', 'bedding'
        ] as $col) {
            if (bgr_column_exists($pdo, 'order_rooming_guests', $col)) {
                $guestSelectExtra[] = 'org.' . $col;
            }
        }
        $guestExtraSql = $guestSelectExtra ? ', ' . implode(', ', $guestSelectExtra) : '';

        $stmt = $pdo->prepare("
            SELECT
                o.*,
                g.firstname AS lead_firstname,
                g.lastname AS lead_lastname,
                g.email AS lead_email,
                g.phone AS lead_phone,
                p.name AS property_name,
                p.code AS property_code,
                p.address AS property_address,
                p.phone AS property_phone,
                p.email AS property_email,
                rt.title AS booking_room_type,
                CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) AS agent_name
            FROM orders o
            LEFT JOIN guests g ON g.id = o.guest_id
            LEFT JOIN properties p ON p.id = o.property_id
            LEFT JOIN room_types rt ON rt.id = o.room_type_id
            LEFT JOIN agents a ON a.id = o.agent_id
            WHERE o.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$order) {
            throw new RuntimeException('Booking not found: ' . $orderId);
        }

        $params = [':order_id' => $orderId];
        $roomingFilter = '';
        if ($roomingId > 0) {
            $roomingFilter = ' AND rmg.id = :rooming_id ';
            $params[':rooming_id'] = $roomingId;
        }

        $stmt = $pdo->prepare("
            SELECT
                rmg.*,
                rm.room_no AS actual_room_no,
                rm.status AS room_status,
                rt.title AS room_type_title
            FROM order_rooming rmg
            LEFT JOIN rooms rm ON rm.id = rmg.room_id
            LEFT JOIN room_types rt ON rt.id = rmg.room_type_id
            WHERE rmg.order_id = :order_id
            $roomingFilter
            ORDER BY rmg.room_no ASC, rmg.id ASC
        ");
        $stmt->execute($params);
        $roomingRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!$roomingRows) {
            throw new RuntimeException('No room registration records found for booking: ' . $orderId);
        }

        $roomingIds = array_map(static fn($r) => (int)$r['id'], $roomingRows);
        $guestRows = [];

        /*
         * CRITICAL FIX:
         * A registration page is printed for ONE rooming record at a time.
         * Previously this used IN ($placeholders). That can pull guests from other
         * rooming rows in the same booking and make a 2-pax room show Guest 3.
         * We now force the guest query to the exact selected rooming id.
         */
        if (bgr_table_exists($pdo, 'order_rooming_guests') && $roomingId > 0) {
            $linkCol = bgr_column_exists($pdo, 'order_rooming_guests', 'rooming_id')
                ? 'rooming_id'
                : (bgr_column_exists($pdo, 'order_rooming_guests', 'order_rooming_id') ? 'order_rooming_id' : 'rooming_id');

            $stmt = $pdo->prepare("
                SELECT
                    org.id,
                    org.order_id,
                    org.`{$linkCol}` AS rooming_id,
                    org.first_name,
                    org.last_name,
                    org.is_primary,
                    org.checked_in_at,
                    org.checked_out_at
                    $guestExtraSql
                FROM order_rooming_guests org
                WHERE org.`{$linkCol}` = :rooming_id
                  AND (org.order_id IS NULL OR org.order_id = :guest_order_id)
                ORDER BY org.is_primary DESC, org.id ASC
            ");
            $stmt->execute([
                ':rooming_id' => $roomingId,
                ':guest_order_id' => $orderId,
            ]);
            $guestRows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        }

        /*
         * Safety limit:
         * If old/bad data has extra guest records attached to this rooming row,
         * only print the number of people configured on order_rooming.
         * For Room 5 with adults+children = 2, Guest 3 will not print.
         */
        $expectedGuests = 0;
        if (!empty($roomingRows[0])) {
            foreach (['adults', 'Adults', 'adult_count'] as $col) {
                if (isset($roomingRows[0][$col])) { $expectedGuests += (int)$roomingRows[0][$col]; break; }
            }
            foreach (['children', 'Children', 'child_count'] as $col) {
                if (isset($roomingRows[0][$col])) { $expectedGuests += (int)$roomingRows[0][$col]; break; }
            }
            if ($expectedGuests <= 0) {
                foreach (['pax', 'Pax', 'guests', 'guest_count'] as $col) {
                    if (isset($roomingRows[0][$col])) { $expectedGuests = (int)$roomingRows[0][$col]; break; }
                }
            }
        }
        if ($expectedGuests > 0 && count($guestRows) > $expectedGuests) {
            $guestRows = array_slice(array_values($guestRows), 0, $expectedGuests);
        }

        if (!$guestRows) {
            $guestRows[] = [
                'first_name' => (string)($order['lead_firstname'] ?? ''),
                'last_name'  => (string)($order['lead_lastname'] ?? ''),
                'email'      => (string)($order['lead_email'] ?? ''),
                'phone'      => (string)($order['lead_phone'] ?? ''),
                'is_primary' => 1,
            ];
        }

        $roomNos = [];
        $roomTypes = [];
        foreach ($roomingRows as $room) {
            $roomNo = trim((string)($room['actual_room_no'] ?? ''));
            if ($roomNo === '') $roomNo = trim((string)($room['room_no'] ?? ''));
            if ($roomNo !== '') $roomNos[] = $roomNo;

            $roomType = trim((string)($room['room_type_title'] ?? ''));
            if ($roomType !== '') $roomTypes[] = $roomType;
        }

        /*
         * Room Config on the registration card must show the Bed / Room
         * Configuration that was ENTERED during the preload of names (e.g.
         * "Twin", "Double", "King + Cot"), not just the room type name.
         * The rooming query selects rmg.*, so whichever column the preload
         * feature writes it to is already in the row - probe the likely
         * column names, on the rooming row first, then on the guest rows.
         * Falls back to the room type name only when no configuration was
         * captured, so cards never print blank.
         */
        $configCols = ['bed_config', 'bed_configuration', 'room_config', 'room_configuration', 'bedding_config', 'bedding', 'room_setup', 'configuration'];
        $roomConfigs = [];
        foreach ($roomingRows as $room) {
            foreach ($configCols as $cc) {
                if (isset($room[$cc]) && trim((string)$room[$cc]) !== '') {
                    $roomConfigs[] = trim((string)$room[$cc]);
                    break;
                }
            }
        }
        if (!$roomConfigs) {
            foreach ($guestRows as $gRow) {
                foreach ($configCols as $cc) {
                    if (isset($gRow[$cc]) && trim((string)$gRow[$cc]) !== '') {
                        $roomConfigs[] = trim((string)$gRow[$cc]);
                        break 2;
                    }
                }
            }
        }
        $roomConfigLabel = implode(', ', array_values(array_unique($roomConfigs)));
        if ($roomConfigLabel === '') {
            $roomConfigLabel = implode(', ', array_values(array_unique($roomTypes)));
        }

        return [
            'order' => $order,
            'rooming_rows' => $roomingRows,
            'guest_rows' => array_values($guestRows),
            'expected_guest_count' => $expectedGuests,
            'room_no_label' => implode(', ', array_values(array_unique($roomNos))),
            'room_type_label' => implode(', ', array_values(array_unique($roomTypes))),
            'room_config_label' => $roomConfigLabel,
            'check_in' => $roomingRows[0]['check_in'] ?? ($order['check_in'] ?? ''),
            'check_out' => $roomingRows[0]['check_out'] ?? ($order['check_out'] ?? ''),
        ];
    }
}

if (!function_exists('bgr_render_registration_page')) {
    function bgr_render_registration_page(TCPDF $pdf, array $data, string $logoPath = ''): void
    {
        $order = $data['order'];
        $guestRows = $data['guest_rows'];

        $expectedGuestCount = (int)($data['expected_guest_count'] ?? 0);
        if ($expectedGuestCount > 0 && count($guestRows) > $expectedGuestCount) {
            $guestRows = array_slice(array_values($guestRows), 0, $expectedGuestCount);
        }

        $guest1 = $guestRows[0] ?? [];
        $guest2 = $guestRows[1] ?? [];
        $additionalGuests = ($expectedGuestCount > 2 || count($guestRows) > 2) ? array_slice($guestRows, 2, 2) : [];

        $pdf->AddPage();
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetDrawColor(0, 0, 0);
        $pdf->SetLineWidth(0.18);

        if ($logoPath !== '') {
            try { $pdf->Image($logoPath, 8, 7, 48, 0, '', '', '', false, 300); } catch (Throwable $e) {}
        } else {
            $pdf->SetXY(8, 7);
            $pdf->SetFont('helvetica', 'B', 18);
            $pdf->Cell(56, 8, 'PIONEERS', 0, 1, 'L');
            $pdf->SetX(8);
            $pdf->SetFont('helvetica', 'I', 9);
            $pdf->Cell(56, 4, 'Victoria Falls', 0, 1, 'C');
        }

        bgr_line_value($pdf, 132, 7,  'Date:', date('d/m/Y'), 12, 55, 8.0);
        bgr_line_value($pdf, 132, 16, 'Room Number:', (string)$data['room_no_label'], 27, 40, 8.0);
        bgr_line_value($pdf, 132, 23, 'Room Config:', (string)($data['room_config_label'] ?? ($data['room_type_label'] ?? '')), 27, 40, 8.0);
        bgr_line_value($pdf, 8,   31, 'Arrival Date:', bgr_date($data['check_in'], 'd/m/Y'), 23, 50, 8.0);
        bgr_line_value($pdf, 107, 31, 'Departure Date:', bgr_date($data['check_out'], 'd/m/Y'), 29, 64, 8.0);

        bgr_guest_block($pdf, 40, 'Guest 1', $guest1);
        bgr_guest_block($pdf, 78, 'Guest 2', $guest2);

        $pdf->SetFont('helvetica', 'B', 8.2);
        $pdf->SetXY(8, 116);
        $pdf->Cell(40, 4, 'Additional Guests:', 0, 1, 'L');
        $pdf->Line(8, 120.2, 38, 120.2);

        $add1 = isset($additionalGuests[0]) ? bgr_guest_full_name($additionalGuests[0]) : '';
        $add2 = isset($additionalGuests[1]) ? bgr_guest_full_name($additionalGuests[1]) : '';
        bgr_line_value($pdf, 8,   124, 'Name:', $add1, 12, 78, 8.0);
        bgr_line_value($pdf, 101, 124, 'Name:', $add2, 12, 87, 8.0);

        $html = '
<style>
    h3{font-size:7.8px;text-align:center;text-decoration:underline;margin:0 0 6px 0;font-weight:bold;}
    table{font-size:6.4px;line-height:1.42;}
    td.no{width:8%;font-weight:bold;vertical-align:top;padding-top:2px;padding-bottom:2px;}
    td.txt{width:92%;vertical-align:top;padding-top:2px;padding-bottom:2px;}
    .section{font-weight:bold;text-decoration:underline;}
    p{font-size:6.4px;line-height:1.42;margin:4px 0 0 0;}
</style>
<h3>Pioneers Lodge (Private) trading as Pioneers Lodge - DISCLAIMER &amp; INDEMNITY</h3>
<table cellpadding="0.7" cellspacing="0">
<tr><td class="no">1.</td><td class="txt section">Introduction</td></tr>
<tr><td class="no">1.1</td><td class="txt">Pioneers Lodge (PVT) Ltd, Registration Number 241/2019 (&quot;the Company&quot;) operates the Pioneers Lodge (&quot;the Lodge&quot;) and conducts the activities described herein for guests.</td></tr>
<tr><td class="no">1.2</td><td class="txt">The guest and members of the guest&apos;s party (including any minor children), whose names and particulars appears both 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.</td></tr>
<tr><td class="no">2.</td><td class="txt section">Disclaimer and Indemnity</td></tr>
<tr><td class="no">2.1</td><td class="txt">The Company and its shareholders, directors, employees and representatives (collectively referred to as &quot;the Indemnified Parties&quot;), 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.</td></tr>
<tr><td class="no">2.2</td><td class="txt">The Guest/s partakes in the Activities entirely at the Guest/s&apos;s own risk.</td></tr>
<tr><td class="no">2.3</td><td class="txt">The Guest/s accordingly waive all claims of any nature whatsoever which the Guest/s or his/her deceased estate (&quot;Estate&quot;) may have against the Indemnified Parties, arising from the death of or injury or the loss of or damage to any Guest&apos;s 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&apos; dependants, in respect of any such death, injury, loss or damage.</td></tr>
<tr><td class="no">2.4</td><td class="txt">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.</td></tr>
<tr><td class="no">2.5</td><td class="txt">The Guest/s further acknowledges that:</td></tr>
<tr><td class="no">2.5.1</td><td class="txt">The Guest/s is obliged to exercise his/her own independent judgement in participating in the Activities and evaluating the Risks.</td></tr>
<tr><td class="no">2.5.2</td><td class="txt">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.</td></tr>
<tr><td class="no">2.5.3</td><td class="txt">In the event of any accident or injury, the Indemnified Parties:</td></tr>
<tr><td class="no">2.5.3.1</td><td class="txt">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;</td></tr>
<tr><td class="no">2.5.3.2</td><td class="txt">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&apos; rights in terms hereof, or otherwise in law.</td></tr>
<tr><td class="no">2.5.4</td><td class="txt">This disclaimer and indemnity will be binding on the Guest&apos;s Estate.</td></tr>
<tr><td class="no">2.5.5</td><td class="txt">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.</td></tr>
</table>
<p>The Guest/s warrants that the Guest/s is in a sufficiently good physical and mental condition to take part in the Activities</p>';

        $pdf->writeHTMLCell(196, 0, 7, 134, $html, 0, 1, false, true, 'L', true);

        $signatureY = $pdf->GetY() + 4;
        $pdf->SetFont('helvetica', 'B', 6.8);
        bgr_line_value($pdf, 8,   $signatureY, 'Guest 1 Signature:', '', 27, 60, 6.8);
        bgr_line_value($pdf, 106, $signatureY, 'Guest 2 Signature:', '', 27, 60, 6.8);
    }
}

$properties = [];
try {
    if (bgr_table_exists($pdo, 'properties')) {
        $properties = $pdo->query("
            SELECT id, name, code
            FROM properties
            WHERE COALESCE(is_active,1) = 1
            ORDER BY name ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $properties = [];
}

$tomorrow = date('Y-m-d', strtotime('+1 day'));
$printDate = trim((string)($_GET['date'] ?? $tomorrow));
if (!strtotime($printDate)) $printDate = $tomorrow;
$printDate = date('Y-m-d', strtotime($printDate));

$propertyId = (int)($_GET['property_id'] ?? 0);
if ($propertyId <= 0 && count($properties) === 1) {
    $propertyId = (int)$properties[0]['id'];
}

$errors = [];
$rows = [];

try {
    $rows = bgr_fetch_arrivals($pdo, $propertyId, $printDate);
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

if (isset($_GET['combined_pdf']) && (int)$_GET['combined_pdf'] === 1) {
    try {
        if (!$rows) {
            throw new RuntimeException('No unchecked-in arrivals found for this date.');
        }

        $tcpdfPaths = [
            __DIR__ . '/../../vendor/tecnickcom/tcpdf/tcpdf.php',
            __DIR__ . '/../../../vendor/tecnickcom/tcpdf/tcpdf.php',
            __DIR__ . '/../../vendor/autoload.php',
            __DIR__ . '/../../../vendor/autoload.php',
            __DIR__ . '/../../tcpdf/tcpdf.php',
            __DIR__ . '/../../../tcpdf/tcpdf.php',
            __DIR__ . '/../../includes/tcpdf/tcpdf.php',
            __DIR__ . '/../../../includes/tcpdf/tcpdf.php',
            $_SERVER['DOCUMENT_ROOT'] . '/tcpdf/tcpdf.php',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/tcpdf/tcpdf.php',
        ];

        $tcpdfFile = bgr_first_existing_file($tcpdfPaths);
        if ($tcpdfFile === '') {
            throw new RuntimeException('TCPDF not found. Please install TCPDF or check the path.');
        }
        require_once $tcpdfFile;

        class BulkGuestRegistrationPdf extends TCPDF
        {
            public function Header() {}
            public function Footer() {}
        }

        $pdf = new BulkGuestRegistrationPdf('P', 'mm', 'A4', true, 'UTF-8', false);
        $pdf->SetCreator('Rooms PMS');
        $pdf->SetAuthor('Pioneers Lodge');
        $pdf->SetTitle('Bulk Guest Registration Forms - ' . $printDate);
        $pdf->SetSubject('Bulk Guest Registration Forms');
        $pdf->SetMargins(6, 6, 6);
        $pdf->SetAutoPageBreak(false, 0);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

        $logoPath = bgr_first_existing_file([
            __DIR__ . '/../../assets/img/pioneers-logo.png',
            __DIR__ . '/../../assets/images/pioneers-logo.png',
            __DIR__ . '/../../assets/pioneers-logo.png',
            __DIR__ . '/../../assets/img/company-logo.png',
            __DIR__ . '/../../assets/images/logo.png',
            __DIR__ . '/../../assets/logo.png',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/assets/img/pioneers-logo.png',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/assets/images/pioneers-logo.png',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/assets/img/logo.png',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/assets/images/logo.png',
            $_SERVER['DOCUMENT_ROOT'] . '/rooms/assets/logo.png',
        ]);

        foreach ($rows as $r) {
            $data = bgr_fetch_registration_data($pdo, (int)$r['order_id'], (int)$r['rooming_id']);
            bgr_render_registration_page($pdf, $data, $logoPath);
        }

        $filename = 'bulk_guest_registration_' . date('Ymd', strtotime($printDate)) . '.pdf';
        while (ob_get_level() > 0) { @ob_end_clean(); }
        $pdf->Output($filename, 'I');
        exit;
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

/*
    Individual form file you already have.
    Used only for the Open / Print button per row.
*/
$formBase = 'guest_registration_pdf.php';

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band mb-3" style="padding:12px 16px!important;border-radius:16px;">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
            <div class="page-eyebrow text-white-50"><i class="bi bi-printer"></i> Daily Reports</div>
            <div class="hero-title" style="font-size:1.2rem;">Bulk Guest Registration Forms</div>
            <div class="hero-subtitle" style="font-size:.82rem;">Generate one combined PDF for all arriving guest registration forms.</div>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="front_office_daily_reports.php<?php echo $propertyId > 0 ? '?property_id='.(int)$propertyId : ''; ?>" class="btn btn-sm btn-outline-light">
                <i class="bi bi-arrow-left me-1"></i>Daily Reports
            </a>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <strong>Please fix:</strong>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo bgr_e($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card panel-card mb-3">
    <div class="card-body">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label">Check-in Date</label>
                <input type="date" name="date" class="form-control form-control-sm" value="<?php echo bgr_e($printDate); ?>">
            </div>

            <div class="col-md-4">
                <label class="form-label">Property</label>
                <select name="property_id" class="form-select form-select-sm">
                    <option value="0">All properties</option>
                    <?php foreach ($properties as $p): ?>
                        <option value="<?php echo (int)$p['id']; ?>" <?php echo $propertyId === (int)$p['id'] ? 'selected' : ''; ?>>
                            <?php echo bgr_e($p['name']); ?><?php echo !empty($p['code']) ? ' - '.bgr_e($p['code']) : ''; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-5 d-flex gap-2">
                <button class="btn btn-sm btn-primary">
                    <i class="bi bi-search me-1"></i>Load Forms
                </button>

                <a class="btn btn-sm btn-success <?php echo !$rows ? 'disabled' : ''; ?>"
                   href="bulk_guest_registration_tomorrow.php?<?php echo http_build_query(['date'=>$printDate,'property_id'=>$propertyId,'combined_pdf'=>1]); ?>"
                   target="_blank">
                    <i class="bi bi-file-earmark-pdf me-1"></i>Generate One PDF (<?php echo count($rows); ?>)
                </a>

                <a class="btn btn-sm btn-outline-secondary"
                   href="bulk_guest_registration_tomorrow.php?<?php echo http_build_query(['date'=>$tomorrow,'property_id'=>$propertyId]); ?>">
                    Tomorrow
                </a>
            </div>
        </form>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h5 class="mb-0">Arrivals for <?php echo bgr_e(bgr_date($printDate)); ?></h5>
            <small class="text-muted"><?php echo count($rows); ?> form<?php echo count($rows) === 1 ? '' : 's'; ?> will be generated in one PDF, ordered by property, room, guest and booking.</small>
        </div>
        <?php if ($rows): ?>
            <a class="btn btn-sm btn-success"
               href="bulk_guest_registration_tomorrow.php?<?php echo http_build_query(['date'=>$printDate,'property_id'=>$propertyId,'combined_pdf'=>1]); ?>"
               target="_blank">
                <i class="bi bi-file-earmark-pdf me-1"></i>Generate One PDF
            </a>
        <?php endif; ?>
    </div>

    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern table-striped align-middle mb-0">
                <thead>
                    <tr>
                        <th>Booking</th>
                        <th>Guest</th>
                        <th>Room</th>
                        <th>Property</th>
                        <th>Stay</th>
                        <th>Guests</th>
                        <th class="text-end">Single Form</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">No unchecked-in arrivals found for this date.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <?php
                        $url = $formBase . '?' . http_build_query([
                            'order_id' => (int)$r['order_id'],
                            'rooming_id' => (int)$r['rooming_id'],
                        ]);
                        ?>
                        <tr>
                            <td>
                                <strong><?php echo bgr_e($r['order_no'] ?: ('#'.$r['order_id'])); ?></strong>
                                <div class="small text-muted">ID <?php echo (int)$r['order_id']; ?></div>
                            </td>
                            <td><?php echo bgr_e($r['lead_guest_name'] ?: 'Guest'); ?></td>
                            <td>
                                <?php echo bgr_e($r['room_no'] ?: 'Unassigned'); ?>
                                <?php if (!empty($r['room_type_title'])): ?><div class="small text-muted"><?php echo bgr_e($r['room_type_title']); ?></div><?php endif; ?>
                            </td>
                            <td>
                                <?php echo bgr_e(trim((string)$r['property_name'])); ?>
                                <?php echo !empty($r['property_code']) ? '<div class="small text-muted">'.bgr_e($r['property_code']).'</div>' : ''; ?>
                            </td>
                            <td>
                                <small>
                                    <strong>In:</strong> <?php echo bgr_e(bgr_date($r['check_in'])); ?><br>
                                    <strong>Out:</strong> <?php echo bgr_e(bgr_date($r['check_out'])); ?>
                                </small>
                            </td>
                            <td><?php echo (int)$r['guest_count']; ?></td>
                            <td class="text-end">
                                <a href="<?php echo bgr_e($url); ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                    Open Single
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.table-modern th,
.table-modern td {
    font-size: .86rem;
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
