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

if (!function_exists('hkp_column_exists')) {
    function hkp_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("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('hkp_money')) {
    function hkp_money($amount): string { return number_format((float)$amount, 2); }
}

if (!function_exists('hkp_clean')) {
    function hkp_clean($value): string
    {
        $value = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
        $value = str_replace(["\r\n", "\r"], "\n", $value);
        $value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $value);
        return trim($value);
    }
}

if (!function_exists('hkp_room_status_meta')) {
    function hkp_room_status_meta(string $occupancyStatus, string $housekeepingStatus): array
    {
        $occupancyStatus = strtolower(trim($occupancyStatus));
        $housekeepingStatus = strtolower(trim($housekeepingStatus));

        if (in_array($housekeepingStatus, ['out_of_order', 'ooo', 'maintenance', 'blocked'], true)) return ['label' => 'Out of Order', 'key' => 'ooo'];
        if ($occupancyStatus === 'arrival') return ['label' => 'Arrival Today', 'key' => 'arrival'];
        if ($occupancyStatus === 'departure') return ['label' => $housekeepingStatus === 'clean' ? 'Departure / Clean' : 'Departure Today', 'key' => 'departure'];
        if ($occupancyStatus === 'occupied') return ['label' => 'Occupied', 'key' => 'occupied'];
        if ($occupancyStatus === 'vacant') {
            if (in_array($housekeepingStatus, ['clean', 'inspected', 'available'], true)) return ['label' => 'Vacant Clean', 'key' => 'vacant_clean'];
            if ($housekeepingStatus === 'dirty') return ['label' => 'Vacant Dirty', 'key' => 'vacant_dirty'];
            return ['label' => 'Vacant Clean', 'key' => 'vacant_clean'];
        }
        return ['label' => 'Unknown', 'key' => 'unknown'];
    }
}

function hkp_load_tcpdf(): void
{
    $candidates = [
        __DIR__ . '/../../vendor/autoload.php',
        __DIR__ . '/../../../vendor/autoload.php',
        __DIR__ . '/../../includes/tcpdf/tcpdf.php',
        __DIR__ . '/../../../tcpdf/tcpdf.php',
        __DIR__ . '/../../lib/tcpdf/tcpdf.php',
        __DIR__ . '/../../tcpdf/tcpdf.php',
    ];

    foreach ($candidates as $path) {
        if (file_exists($path)) {
            require_once $path;
            if (class_exists('TCPDF')) return;
        }
    }

    if (!class_exists('TCPDF')) {
        throw new RuntimeException('TCPDF library not found. Please install TCPDF or place tcpdf.php under /rooms/includes/tcpdf/tcpdf.php.');
    }
}

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

$viewDate = trim((string)($_GET['view_date'] ?? date('Y-m-d')));
$propertyId = (int)($_GET['property_id'] ?? 0);
$search = trim((string)($_GET['q'] ?? ''));
$filterStatus = trim((string)($_GET['filter_status'] ?? ''));

if (strtotime($viewDate) === false) {
    $viewDate = date('Y-m-d');
} else {
    $viewDate = date('Y-m-d', strtotime($viewDate));
}

$properties = [];
$propertyLabel = 'All Properties';
try {
    $stmt = $pdo->query("SELECT id, name, code FROM properties WHERE is_active = 1 ORDER BY name ASC");
    $properties = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($properties as $p) {
        if ((int)$p['id'] === $propertyId) {
            $propertyLabel = trim((string)$p['name']);
            if (!empty($p['code'])) $propertyLabel .= ' (' . $p['code'] . ')';
            break;
        }
    }
} catch (Throwable $e) {}


$arrivalsToday = [];
$departuresToday = [];
$arrivalOrderIdsSeen = [];
$departureOrderIdsSeen = [];

/*
   Match housekeeping board with Front Desk:
   - Arrivals come from orders where DATE(check_in) = view date
   - Departures come from orders where DATE(check_out) = view date
   This avoids missing bookings that are not yet linked to rooms.id.
*/
try {
    $sqlArrivals = "
        SELECT
            o.*,
            p.name AS property_name,
            p.code AS property_code,
            rmix.room_mix,
            g.firstname,
            g.lastname,
            CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) AS agent_name,
            (
                SELECT COUNT(*)
                FROM order_rooming rmg
                WHERE rmg.order_id = o.id
            ) AS room_slots_total,
            (
                SELECT COUNT(*)
                FROM order_rooming rmg
                WHERE rmg.order_id = o.id
                  AND COALESCE(rmg.checked_in_status,0) = 1
            ) AS room_slots_checked_in,
            (
                SELECT COUNT(*)
                FROM order_rooming rmg
                WHERE rmg.order_id = o.id
                  AND COALESCE(rmg.checked_out_status,0) = 1
            ) AS room_slots_checked_out,
            (
                SELECT GROUP_CONCAT(DISTINCT NULLIF(TRIM(CAST(rmg.room_no AS CHAR)), '') ORDER BY rmg.room_no SEPARATOR ', ')
                FROM order_rooming rmg
                WHERE rmg.order_id = o.id
            ) AS assigned_room_nos,
            (
                SELECT COALESCE(SUM(f.balance),0)
                FROM folios f
                WHERE f.order_id = o.id
            ) AS booking_balance
        FROM orders o
        LEFT JOIN properties p ON p.id = o.property_id
        LEFT JOIN guests g ON g.id = o.guest_id
        LEFT JOIN agents a ON a.id = o.agent_id
        LEFT JOIN (
            SELECT order_id,
                   GROUP_CONCAT(room_summary ORDER BY sort_title SEPARATOR ', ') AS room_mix
            FROM (
                SELECT
                    rmg.order_id,
                    COALESCE(rt.title, 'Room') AS sort_title,
                    CONCAT(COALESCE(rt.title, 'Room'), ' x ', COUNT(*)) AS room_summary
                FROM order_rooming rmg
                LEFT JOIN room_types rt ON rt.id = rmg.room_type_id
                GROUP BY rmg.order_id, rmg.room_type_id, rt.title
            ) mix
            GROUP BY order_id
        ) rmix ON rmix.order_id = o.id
        WHERE DATE(o.check_in) = :arrival_date
    ";
    $arrivalParams = [':arrival_date' => $viewDate];

    if ($propertyId > 0) {
        $sqlArrivals .= " AND o.property_id = :arrival_property_id ";
        $arrivalParams[':arrival_property_id'] = $propertyId;
    }

    if ($search !== '') {
        $sqlArrivals .= "
            AND (
                o.order_no LIKE :arrival_search
                OR CAST(o.id AS CHAR) LIKE :arrival_search
                OR g.firstname LIKE :arrival_search
                OR g.lastname LIKE :arrival_search
                OR CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) LIKE :arrival_search
                OR COALESCE(p.name,'') LIKE :arrival_search
                OR COALESCE(p.code,'') LIKE :arrival_search
            )
        ";
        $arrivalParams[':arrival_search'] = '%' . $search . '%';
    }

    $sqlArrivals .= " ORDER BY p.name ASC, o.check_in ASC, o.id DESC ";
    $stmt = $pdo->prepare($sqlArrivals);
    $stmt->execute($arrivalParams);
    $arrivalsToday = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // Keep PDF usable even if the arrivals query cannot run.
    $arrivalsToday = [];
}

try {
    $sqlDepartures = "
        SELECT
            o.*,
            p.name AS property_name,
            p.code AS property_code,
            g.firstname,
            g.lastname,
            CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) AS agent_name,
            (
                SELECT COUNT(*)
                FROM order_rooming rmg
                WHERE rmg.order_id = o.id
            ) AS room_slots_total,
            (
                SELECT COUNT(*)
                FROM order_rooming rmg
                WHERE rmg.order_id = o.id
                  AND COALESCE(rmg.checked_out_status,0) = 1
            ) AS room_slots_checked_out,
            (
                SELECT COUNT(*)
                FROM order_rooming rmg
                WHERE rmg.order_id = o.id
                  AND COALESCE(rmg.checked_in_status,0) = 1
            ) AS room_slots_checked_in,
            (
                SELECT GROUP_CONCAT(DISTINCT rroom.room_no ORDER BY rroom.room_no SEPARATOR ', ')
                FROM order_rooming rmg
                LEFT JOIN rooms rroom ON rroom.id = rmg.room_id
                WHERE rmg.order_id = o.id
            ) AS assigned_room_nos,
            (
                SELECT COALESCE(SUM(f.balance),0)
                FROM folios f
                WHERE f.order_id = o.id
            ) AS booking_balance,
            (
                SELECT GROUP_CONCAT(room_summary SEPARATOR ', ')
                FROM (
                    SELECT CONCAT(COALESCE(rt2.title,'Room'), ' x ', COUNT(*)) AS room_summary
                    FROM order_rooming rmg2
                    LEFT JOIN room_types rt2 ON rt2.id = rmg2.room_type_id
                    WHERE rmg2.order_id = o.id
                    GROUP BY rmg2.room_type_id, rt2.title
                    ORDER BY rt2.title
                ) rmixq
            ) AS room_mix
        FROM orders o
        LEFT JOIN properties p ON p.id = o.property_id
        LEFT JOIN guests g ON g.id = o.guest_id
        LEFT JOIN agents a ON a.id = o.agent_id
        WHERE DATE(o.check_out) = :departure_date
    ";
    $departureParams = [':departure_date' => $viewDate];

    if ($propertyId > 0) {
        $sqlDepartures .= " AND o.property_id = :departure_property_id ";
        $departureParams[':departure_property_id'] = $propertyId;
    }

    if ($search !== '') {
        $sqlDepartures .= "
            AND (
                o.order_no LIKE :departure_search
                OR CAST(o.id AS CHAR) LIKE :departure_search
                OR g.firstname LIKE :departure_search
                OR g.lastname LIKE :departure_search
                OR CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) LIKE :departure_search
                OR COALESCE(p.name,'') LIKE :departure_search
                OR COALESCE(p.code,'') LIKE :departure_search
            )
        ";
        $departureParams[':departure_search'] = '%' . $search . '%';
    }

    $sqlDepartures .= " ORDER BY p.name ASC, o.check_out ASC, o.id DESC ";
    $stmt = $pdo->prepare($sqlDepartures);
    $stmt->execute($departureParams);
    $departuresToday = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // Keep PDF usable even if the departures query cannot run.
    $departuresToday = [];
}


$hkHasRoomNameColumn = hkp_column_exists($pdo, 'rooms', 'room_name');
$hkHasNoteColumn = hkp_column_exists($pdo, 'rooms', 'housekeeping_note');
$hkHasNoteAtColumn = hkp_column_exists($pdo, 'rooms', 'housekeeping_note_updated_at');

$rooms = [];
$sqlRooms = "
    SELECT
        r.*,
        p.name AS property_name,
        p.code AS property_code,
        rt.title AS room_type
    FROM rooms r
    LEFT JOIN properties p ON p.id = r.property_id
    LEFT JOIN room_types rt ON rt.id = r.room_type_id
    WHERE 1=1
";
$params = [];
if ($propertyId > 0) {
    $sqlRooms .= " AND r.property_id = :property_id ";
    $params[':property_id'] = $propertyId;
}
if ($search !== '') {
    $like = '%' . $search . '%';
    $parts = [
        "r.room_no LIKE :search_room_no",
        "COALESCE(rt.title,'') LIKE :search_room_type",
        "COALESCE(p.name,'') LIKE :search_property_name",
        "COALESCE(p.code,'') LIKE :search_property_code",
    ];
    $params[':search_room_no'] = $like;
    $params[':search_room_type'] = $like;
    $params[':search_property_name'] = $like;
    $params[':search_property_code'] = $like;
    if ($hkHasRoomNameColumn) {
        $parts[] = "COALESCE(r.room_name,'') LIKE :search_room_name";
        $params[':search_room_name'] = $like;
    }
    $sqlRooms .= ' AND (' . implode(' OR ', $parts) . ') ';
}
$sqlRooms .= " ORDER BY p.name ASC, r.room_no ASC, r.id ASC ";
$stmt = $pdo->prepare($sqlRooms);
$stmt->execute($params);
$rooms = $stmt->fetchAll(PDO::FETCH_ASSOC);

$bookingMap = [];
if ($rooms) {
    $roomIds = array_map(fn($r) => (int)$r['id'], $rooms);
    $placeholders = implode(',', array_fill(0, count($roomIds), '?'));
    $sqlAssignments = "
        SELECT
            rmg.*,
            o.order_no,
            o.check_in,
            o.check_out,
            o.status AS booking_status,
            g.firstname,
            g.lastname,
            CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) AS agent_name,
            (SELECT COALESCE(SUM(f.balance),0) FROM folios f WHERE f.order_id = o.id) AS booking_balance
        FROM order_rooming rmg
        INNER JOIN orders o ON o.id = rmg.order_id
        LEFT JOIN guests g ON g.id = o.guest_id
        LEFT JOIN agents a ON a.id = o.agent_id
        WHERE rmg.room_id IN ($placeholders)
          AND DATE(o.check_in) <= ?
          AND DATE(o.check_out) >= ?
        ORDER BY o.check_in ASC, o.id DESC
    ";
    $stmt = $pdo->prepare($sqlAssignments);
    $bind = $roomIds;
    $bind[] = $viewDate;
    $bind[] = $viewDate;
    $stmt->execute($bind);
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $ar) {
        $rid = (int)($ar['room_id'] ?? 0);
        $bookingMap[$rid][] = $ar;
    }
}

$sections = [
    'vacant_clean' => ['title' => 'CLEAN / READY ROOMS', 'rows' => []],
    'vacant_dirty' => ['title' => 'DIRTY ROOMS', 'rows' => []],
    'occupied' => ['title' => 'OCCUPIED ROOMS', 'rows' => []],
    'arrival' => ['title' => 'ARRIVALS TODAY', 'rows' => []],
    'departure' => ['title' => 'DEPARTURES TODAY', 'rows' => []],
    'ooo' => ['title' => 'OUT OF ORDER ROOMS', 'rows' => []],
];

foreach ($rooms as $room) {
    $roomId = (int)$room['id'];
    $assignment = $bookingMap[$roomId][0] ?? null;
    $rawHk = strtolower(trim((string)($room['housekeeping_status'] ?? $room['status'] ?? '')));
    if ($rawHk === '') $rawHk = 'clean';

    $occupancyStatus = 'vacant';
    if ($assignment) {
        $checkIn = substr((string)($assignment['check_in'] ?? ''), 0, 10);
        $checkOut = substr((string)($assignment['check_out'] ?? ''), 0, 10);
        if ($checkIn === $viewDate) {
            $occupancyStatus = 'arrival';
            if (!empty($assignment['order_id'])) $arrivalOrderIdsSeen[(int)$assignment['order_id']] = true;
        } elseif ($checkOut === $viewDate) {
            $occupancyStatus = 'departure';
            if (!empty($assignment['order_id'])) $departureOrderIdsSeen[(int)$assignment['order_id']] = true;
        } else {
            $occupancyStatus = 'occupied';
        }
    }

    $meta = hkp_room_status_meta($occupancyStatus, $rawHk);
    $key = $meta['key'];

    if ($filterStatus !== '') {
        if ($filterStatus !== $key) continue;
    }

    $property = trim((string)($room['property_name'] ?? ''));
    if (!empty($room['property_code'])) $property .= ($property !== '' ? ' (' . $room['property_code'] . ')' : $room['property_code']);

    $guest = '';
    $booking = '';
    $stay = '';
    $balance = '';
    if ($assignment) {
        $guest = trim((string)($assignment['firstname'] ?? '') . ' ' . (string)($assignment['lastname'] ?? ''));
        if ($guest === '') $guest = 'Guest';
        $booking = trim((string)($assignment['order_no'] ?? '')) ?: ('#' . (int)($assignment['order_id'] ?? 0));
        $stay = substr((string)($assignment['check_in'] ?? ''), 0, 10) . ' to ' . substr((string)($assignment['check_out'] ?? ''), 0, 10);
        $balance = hkp_money($assignment['booking_balance'] ?? 0);
    }

    $note = $hkHasNoteColumn ? hkp_clean($room['housekeeping_note'] ?? '') : '';
    $noteAt = $hkHasNoteAtColumn ? hkp_clean($room['housekeeping_note_updated_at'] ?? '') : '';
    if ($note !== '' && $noteAt !== '') $note .= ' (' . $noteAt . ')';

    if (!isset($sections[$key])) $sections[$key] = ['title' => strtoupper($meta['label']), 'rows' => []];
    $sections[$key]['rows'][] = [
        'room_no' => hkp_clean($room['room_no'] ?? ''),
        'room_type' => hkp_clean($room['room_type'] ?? ''),
        'property' => hkp_clean($property),
        'status' => hkp_clean($meta['label']),
        'hk_status' => hkp_clean(ucwords(str_replace('_', ' ', $rawHk))),
        'booking' => hkp_clean($booking),
        'guest' => hkp_clean($guest),
        'stay' => hkp_clean($stay),
        'balance' => hkp_clean($balance),
        'note' => hkp_clean($note),
    ];
}


/*
   Add front-desk arrivals/departures that were not visible through room-card matching.
   This keeps the PDF totals aligned with arrivals_today.php and departures_today.php.
*/
foreach ($arrivalsToday as $arrival) {
    $orderId = (int)($arrival['id'] ?? 0);
    if ($orderId <= 0 || isset($arrivalOrderIdsSeen[$orderId])) {
        continue;
    }

    $property = trim((string)($arrival['property_name'] ?? ''));
    if (!empty($arrival['property_code'])) {
        $property .= ($property !== '' ? ' (' . $arrival['property_code'] . ')' : $arrival['property_code']);
    }

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

    $roomLabel = trim((string)($arrival['assigned_room_nos'] ?? ''));
    if ($roomLabel === '') $roomLabel = 'Unassigned';

    $sections['arrival']['rows'][] = [
        'room_no' => hkp_clean($roomLabel),
        'room_type' => hkp_clean($arrival['room_mix'] ?? 'Arrival not linked to room card'),
        'property' => hkp_clean($property !== '' ? $property : 'Not set'),
        'status' => 'Arrival Today',
        'hk_status' => 'Arrival',
        'booking' => hkp_clean($arrival['order_no'] ?? ('#' . $orderId)),
        'guest' => hkp_clean($guest),
        'stay' => hkp_clean(substr((string)($arrival['check_in'] ?? ''), 0, 10) . ' to ' . substr((string)($arrival['check_out'] ?? ''), 0, 10)),
        'balance' => hkp_money($arrival['booking_balance'] ?? 0),
        'note' => hkp_clean('Front Desk arrival; not linked to a physical room card'),
    ];
}

foreach ($departuresToday as $departure) {
    $orderId = (int)($departure['id'] ?? 0);
    if ($orderId <= 0 || isset($departureOrderIdsSeen[$orderId])) {
        continue;
    }

    $property = trim((string)($departure['property_name'] ?? ''));
    if (!empty($departure['property_code'])) {
        $property .= ($property !== '' ? ' (' . $departure['property_code'] . ')' : $departure['property_code']);
    }

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

    $roomLabel = trim((string)($departure['assigned_room_nos'] ?? ''));
    if ($roomLabel === '') $roomLabel = 'Unassigned';

    $checkedOut = (int)($departure['room_slots_checked_out'] ?? 0);
    $totalSlots = (int)($departure['room_slots_total'] ?? 0);
    $checkoutText = 'Check-out ' . $checkedOut . '/' . $totalSlots . ' rooms';

    $sections['departure']['rows'][] = [
        'room_no' => hkp_clean($roomLabel),
        'room_type' => hkp_clean($departure['room_mix'] ?? 'Departure not linked to room card'),
        'property' => hkp_clean($property !== '' ? $property : 'Not set'),
        'status' => 'Departure Today',
        'hk_status' => 'Departure',
        'booking' => hkp_clean($departure['order_no'] ?? ('#' . $orderId)),
        'guest' => hkp_clean($guest),
        'stay' => hkp_clean(substr((string)($departure['check_in'] ?? ''), 0, 10) . ' to ' . substr((string)($departure['check_out'] ?? ''), 0, 10)),
        'balance' => hkp_money($departure['booking_balance'] ?? 0),
        'note' => hkp_clean($checkoutText . '; Front Desk departure'),
    ];
}

hkp_load_tcpdf();

class HousekeepingTCPDF extends TCPDF
{
    public string $reportTitle = 'Housekeeping Report';
    public string $reportSubTitle = '';

    public function Header()
    {
        $this->SetFillColor(79, 89, 102);
        $this->Rect(0, 0, $this->getPageWidth(), 23, 'F');

        // Proforma-style subtle lower band
        $this->SetFillColor(226, 230, 235);
        $this->Rect(0, 23, $this->getPageWidth(), 2, 'F');

        $this->SetTextColor(255, 255, 255);
        $this->SetFont('helvetica', 'B', 14);
        $this->SetXY(10, 6);
        $this->Cell(180, 6, $this->reportTitle, 0, 0, 'L');

        $this->SetFont('helvetica', '', 8);
        $this->SetXY(10, 14);
        $this->Cell(180, 5, $this->reportSubTitle, 0, 0, 'L');

        $this->SetFont('helvetica', 'B', 8);
        $this->SetXY(210, 8);
        $this->Cell(75, 5, 'Generated: ' . date('Y-m-d H:i'), 0, 0, 'R');

        $this->SetTextColor(0, 0, 0);
    }

    public function Footer()
    {
        $this->SetY(-12);
        $this->SetFont('helvetica', '', 7);
        $this->SetTextColor(120, 120, 120);
        $this->Cell(0, 6, 'Page ' . $this->getAliasNumPage() . ' of ' . $this->getAliasNbPages(), 0, 0, 'C');
    }
}

$sectionColors = [
    // Proforma grey palette
    'vacant_clean' => '#5f6b7a',
    'vacant_dirty' => '#7b8794',
    'occupied' => '#4b5563',
    'arrival' => '#6b7280',
    'departure' => '#9ca3af',
    'ooo' => '#374151',
];

/*
   IMPORTANT:
   Total Rooms must mean physical rooms in the property, not operational rows.
   The arrival/departure sections may include virtual Front Desk booking rows for
   bookings not linked to a physical room card. Summing all section rows double-counts
   rooms and can show 57 when the property only has 50 rooms.
*/
$totalPhysicalRooms = count($rooms);

$totalOperationalRows = 0;
foreach ($sections as $s) {
    $totalOperationalRows += count($s['rows']);
}

$pdf = new HousekeepingTCPDF('L', PDF_UNIT, 'A4', true, 'UTF-8', false);
$pdf->SetCreator('RoomZ PMS');
$pdf->SetAuthor('RoomZ PMS');
$pdf->SetTitle('Housekeeping Report - ' . $viewDate);
$pdf->reportTitle = 'HOUSEKEEPING REPORT';
$pdf->reportSubTitle = 'Date: ' . $viewDate . ' | Property: ' . $propertyLabel . ($filterStatus !== '' ? ' | Filter: ' . $filterStatus : '');
$pdf->SetMargins(8, 29, 8);
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(8);
$pdf->SetAutoPageBreak(true, 13);
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->SetFont('helvetica', '', 8);
$pdf->AddPage();

$summaryHtml = '
<style>
    .summary-table { border-collapse: collapse; width: 100%; }
    .summary-table td { border: 1px solid #cfd5dc; background-color: #f1f3f5; font-size: 8px; font-weight: bold; text-align: center; padding: 6px; }
    .section-title { color:#ffffff; font-size:10px; font-weight:bold; padding:7px; }
    .hk-table { border-collapse: collapse; width: 100%; }
    .hk-table th { background-color:#dfe3e8; color:#111827; border:1px solid #cfd5dc; font-size:7px; font-weight:bold; padding:5px; }
    .hk-table td { border:1px solid #d7dce2; font-size:7px; padding:5px; vertical-align:top; }
    .empty { border:1px solid #d7dce2; color:#777777; font-size:8px; font-style:italic; text-align:center; padding:8px; }
</style>
<table class="summary-table">
<tr>
<td>Physical Rooms<br><span style="font-size:12px;">' . number_format($totalPhysicalRooms) . '</span></td>';

foreach ($sections as $key => $section) {
    if ($filterStatus !== '' && $key !== $filterStatus) continue;
    $summaryHtml .= '<td>' . hkp_pdf_escape(str_replace([' ROOMS', ' TODAY', ' / READY'], '', $section['title'])) . '<br><span style="font-size:12px;">' . number_format(count($section['rows'])) . '</span></td>';
}
$summaryHtml .= '</tr></table><br>';
$pdf->writeHTML($summaryHtml, true, false, true, false, '');

foreach ($sections as $key => $section) {
    if ($filterStatus !== '' && $key !== $filterStatus) continue;

    $color = $sectionColors[$key] ?? '#4b5563';
    $rows = $section['rows'];

    $html = '
    <table cellpadding="0" cellspacing="0" style="width:100%; border-collapse:collapse;">
        <tr>
            <td style="background-color:' . $color . '; color:#ffffff; font-weight:bold; font-size:10px; padding:7px;">
                ' . hkp_pdf_escape($section['title']) . ' (' . count($rows) . ')
            </td>
        </tr>
    </table>';

    if (!$rows) {
        $html .= '<div class="empty">No rooms in this category.</div><br>';
        $pdf->writeHTML($html, true, false, true, false, '');
        continue;
    }

    $html .= '
    <table class="hk-table" cellpadding="4">
        <thead>
            <tr>
                <th width="7%">Room</th>
                <th width="12%">Room Type</th>
                <th width="14%">Property</th>
                <th width="11%">Booking</th>
                <th width="15%">Guest</th>
                <th width="15%">Stay</th>
                <th width="8%" align="right">Balance</th>
                <th width="18%">Notes / HK Status</th>
            </tr>
        </thead>
        <tbody>';

    foreach ($rows as $row) {
        $note = trim(($row['hk_status'] ?? '') . (($row['note'] ?? '') !== '' ? ' - ' . $row['note'] : ''));
        $html .= '
            <tr>
                <td width="7%"><strong>' . hkp_pdf_escape($row['room_no'] ?: 'Room') . '</strong></td>
                <td width="12%">' . hkp_pdf_escape($row['room_type']) . '</td>
                <td width="14%">' . hkp_pdf_escape($row['property']) . '</td>
                <td width="11%">' . hkp_pdf_escape($row['booking']) . '</td>
                <td width="15%">' . hkp_pdf_escape($row['guest']) . '</td>
                <td width="15%">' . hkp_pdf_escape($row['stay']) . '</td>
                <td width="8%" align="right">' . hkp_pdf_escape($row['balance']) . '</td>
                <td width="18%">' . hkp_pdf_escape($note) . '</td>
            </tr>';
    }

    $html .= '</tbody></table><br>';
    $pdf->writeHTML($html, true, false, true, false, '');
}

$pdf->Output('housekeeping_report_' . $viewDate . '.pdf', 'I');
exit;
