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

$pageTitle = 'Housekeeping Board';

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

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



if (!function_exists('hk_column_exists')) {
    function hk_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('room_status_meta')) {
    function 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', 'class' => 'dark'];
        }

        if ($occupancyStatus === 'arrival') {
            return ['label' => 'Arrival Today', 'class' => 'primary'];
        }

        if ($occupancyStatus === 'departure') {
            if ($housekeepingStatus === 'clean') {
                return ['label' => 'Departure / Clean', 'class' => 'info'];
            }
            return ['label' => 'Departure Today', 'class' => 'warning'];
        }

        if ($occupancyStatus === 'occupied') {
            return ['label' => 'Occupied', 'class' => 'danger'];
        }

        if ($occupancyStatus === 'vacant') {
            if ($housekeepingStatus === 'clean' || $housekeepingStatus === 'inspected' || $housekeepingStatus === 'available') {
                return ['label' => 'Vacant Clean', 'class' => 'success'];
            }
            if ($housekeepingStatus === 'dirty') {
                return ['label' => 'Vacant Dirty', 'class' => 'warning'];
            }
            return ['label' => 'Vacant', 'class' => 'secondary'];
        }

        return ['label' => 'Unknown', 'class' => 'secondary'];
    }
}

$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));
}

$errors = [];
$success = '';
$properties = [];
$rooms = [];
$rackRows = [];
$arrivalsToday = [];
$arrivalOrderIdsSeen = [];


/*
   Housekeeping notes are required for statuses that need accountability.
   The ALTERs are safe best-effort additions for older installations.
*/
$hkHasNoteColumn = hk_column_exists($pdo, 'rooms', 'housekeeping_note');
$hkHasNoteAtColumn = hk_column_exists($pdo, 'rooms', 'housekeeping_note_updated_at');
$hkHasNoteByColumn = hk_column_exists($pdo, 'rooms', 'housekeeping_note_by');
$hkHasRoomNameColumn = hk_column_exists($pdo, 'rooms', 'room_name');

if (!$hkHasNoteColumn) {
    try {
        $pdo->exec("ALTER TABLE rooms ADD COLUMN housekeeping_note TEXT NULL");
        $hkHasNoteColumn = true;
    } catch (Throwable $e) {}
}
if (!$hkHasNoteAtColumn) {
    try {
        $pdo->exec("ALTER TABLE rooms ADD COLUMN housekeeping_note_updated_at DATETIME NULL");
        $hkHasNoteAtColumn = true;
    } catch (Throwable $e) {}
}
if (!$hkHasNoteByColumn) {
    try {
        $pdo->exec("ALTER TABLE rooms ADD COLUMN housekeeping_note_by INT NULL");
        $hkHasNoteByColumn = true;
    } catch (Throwable $e) {}
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_room_status'])) {
    $roomId = (int)($_POST['room_id'] ?? 0);
    $newStatus = trim((string)($_POST['new_status'] ?? ''));
    $statusNote = trim((string)($_POST['status_note'] ?? ''));
    $noteRequiredStatuses = ['inspected', 'inspect', 'out_of_order', 'ooo', 'maintenance', 'blocked'];
    $redirectDate = trim((string)($_POST['view_date'] ?? date('Y-m-d')));
    $redirectPropertyId = (int)($_POST['property_id'] ?? 0);
    $redirectSearch = trim((string)($_POST['q'] ?? ''));
    $redirectFilter = trim((string)($_POST['filter_status'] ?? ''));

    if ($roomId <= 0) {
        $errors[] = 'Invalid room selected.';
    }
    if ($newStatus === '') {
        $errors[] = 'Invalid housekeeping status.';
    }
    if (in_array(strtolower($newStatus), $noteRequiredStatuses, true) && $statusNote === '') {
        $errors[] = 'Please enter notes before marking a room as inspected or out of order.';
    }

    if (!$errors) {
        try {
            $noteBy = 0;
            foreach (['user_id', 'userid', 'id', 'staffid'] as $sessionKey) {
                if (!empty($_SESSION[$sessionKey]) && (int)$_SESSION[$sessionKey] > 0) {
                    $noteBy = (int)$_SESSION[$sessionKey];
                    break;
                }
            }

            try {
                $setParts = ['housekeeping_status = :status'];
                $executeParams = [
                    ':status' => $newStatus,
                    ':id'     => $roomId,
                ];

                if ($hkHasNoteColumn) {
                    $setParts[] = 'housekeeping_note = :housekeeping_note';
                    $executeParams[':housekeeping_note'] = $statusNote !== '' ? $statusNote : null;
                }
                if ($hkHasNoteAtColumn) {
                    $setParts[] = 'housekeeping_note_updated_at = NOW()';
                }
                if ($hkHasNoteByColumn) {
                    $setParts[] = 'housekeeping_note_by = :housekeeping_note_by';
                    $executeParams[':housekeeping_note_by'] = $noteBy > 0 ? $noteBy : null;
                }

                $stmt = $pdo->prepare("UPDATE rooms SET " . implode(', ', $setParts) . " WHERE id = :id");
                $stmt->execute($executeParams);
            } catch (Throwable $e) {
                $setParts = ['status = :status'];
                $executeParams = [
                    ':status' => $newStatus,
                    ':id'     => $roomId,
                ];

                if ($hkHasNoteColumn) {
                    $setParts[] = 'housekeeping_note = :housekeeping_note';
                    $executeParams[':housekeeping_note'] = $statusNote !== '' ? $statusNote : null;
                }
                if ($hkHasNoteAtColumn) {
                    $setParts[] = 'housekeeping_note_updated_at = NOW()';
                }
                if ($hkHasNoteByColumn) {
                    $setParts[] = 'housekeeping_note_by = :housekeeping_note_by';
                    $executeParams[':housekeeping_note_by'] = $noteBy > 0 ? $noteBy : null;
                }

                $stmt = $pdo->prepare("UPDATE rooms SET " . implode(', ', $setParts) . " WHERE id = :id");
                $stmt->execute($executeParams);
            }

            $url = 'housekeeping_board.php?view_date=' . urlencode($redirectDate);
            if ($redirectPropertyId > 0) {
                $url .= '&property_id=' . $redirectPropertyId;
            }
            if ($redirectSearch !== '') {
                $url .= '&q=' . urlencode($redirectSearch);
            }
            if ($redirectFilter !== '') {
                $url .= '&filter_status=' . urlencode($redirectFilter);
            }
            $url .= '&saved=1';

            header('Location: ' . $url);
            exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Room housekeeping status and notes updated successfully.';
}

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

/*
   Load arrivals using the SAME source logic as arrivals_today.php:
   orders where DATE(o.check_in) = selected date.
   This is important because not every arrival is already perfectly linked
   to rooms.room_id on the housekeeping board.
*/
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,
                    rt.title AS sort_title,
                    CONCAT(rt.title, ' 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) {
    $errors[] = 'Could not load arrivals: ' . $e->getMessage();
}


try {
    $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 !== '') {
        $searchLike = '%' . $search . '%';
        $searchParts = [
            "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'] = $searchLike;
        $params[':search_room_type'] = $searchLike;
        $params[':search_property_name'] = $searchLike;
        $params[':search_property_code'] = $searchLike;

        if ($hkHasRoomNameColumn) {
            $searchParts[] = "COALESCE(r.room_name,'') LIKE :search_room_name";
            $params[':search_room_name'] = $searchLike;
        }
        if (hk_column_exists($pdo, 'rooms', 'view_type')) {
            $searchParts[] = "COALESCE(r.view_type,'') LIKE :search_view_type";
            $params[':search_view_type'] = $searchLike;
        }
        if (hk_column_exists($pdo, 'rooms', 'room_configuration_notes')) {
            $searchParts[] = "COALESCE(r.room_configuration_notes,'') LIKE :search_room_configuration_notes";
            $params[':search_room_configuration_notes'] = $searchLike;
        }
        if ($hkHasNoteColumn) {
            $searchParts[] = "COALESCE(r.housekeeping_note,'') LIKE :search_housekeeping_note";
            $params[':search_housekeeping_note'] = $searchLike;
        }

        $sqlRooms .= " AND (" . implode(" OR ", $searchParts) . ") ";
    }

    $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);
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
    $rooms = [];
}

$bookingMap = [];
if ($rooms) {
    try {
        $roomIds = array_map(function ($r) {
            return (int)$r['id'];
        }, $rooms);

        $placeholders = implode(',', array_fill(0, count($roomIds), '?'));

        $roomNos = [];
        foreach ($rooms as $r) {
            $rn = trim((string)($r['room_no'] ?? ''));
            if ($rn !== '') {
                $roomNos[$rn] = $rn;
            }
        }

        $roomNoPlaceholders = $roomNos ? implode(',', array_fill(0, count($roomNos), '?')) : '';
        $roomNoWhere = $roomNoPlaceholders !== '' ? " OR NULLIF(TRIM(CAST(rmg.room_no AS CHAR)), '') IN ($roomNoPlaceholders) " : '';

        /*
         * Important:
         * order_rooming.room_id is not always populated in older bookings.
         * Some rows only have order_rooming.room_no. If we only match by room_id,
         * arrivals/departures can show as zero even when bookings exist today.
         */
        $sqlAssignments = "
            SELECT
                rmg.*,
                COALESCE(NULLIF(rmg.room_id, 0), matched_room.id) AS matched_room_id,
                o.order_no,
                o.check_in,
                o.check_out,
                o.expected_arrival_time,
                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 rooms matched_room
                   ON NULLIF(TRIM(CAST(matched_room.room_no AS CHAR)), '') = NULLIF(TRIM(CAST(rmg.room_no AS CHAR)), '')
                  AND (matched_room.property_id = o.property_id OR o.property_id IS NULL OR o.property_id = 0)
            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)
                    OR matched_room.id IN ($placeholders)
                    $roomNoWhere
                  )
              AND DATE(o.check_in) <= ?
              AND DATE(o.check_out) >= ?
            ORDER BY o.check_in ASC, o.id DESC
        ";

        $stmt = $pdo->prepare($sqlAssignments);
        $bind = array_values($roomIds);
        $bind = array_merge($bind, array_values($roomIds));
        if ($roomNos) {
            $bind = array_merge($bind, array_values($roomNos));
        }
        $bind[] = $viewDate;
        $bind[] = $viewDate;
        $stmt->execute($bind);
        $assignmentRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($assignmentRows as $ar) {
            $rid = (int)($ar['matched_room_id'] ?? $ar['room_id'] ?? 0);
            if ($rid <= 0) {
                continue;
            }
            if (!isset($bookingMap[$rid])) {
                $bookingMap[$rid] = [];
            }
            $bookingMap[$rid][] = $ar;
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$totalVacantClean = 0;
$totalVacantDirty = 0;
$totalOccupied = 0;
$totalArrivals = 0;
$totalDepartures = 0;
$totalOOO = 0;

foreach ($rooms as $room) {
    $roomId = (int)$room['id'];
    $assignments = $bookingMap[$roomId] ?? [];
    $current = !empty($assignments) ? $assignments[0] : null;

    $rawHousekeeping = strtolower(trim((string)($room['housekeeping_status'] ?? $room['status'] ?? '')));
    if ($rawHousekeeping === '') {
        $rawHousekeeping = 'clean';
    }

    $occupancyStatus = 'vacant';
    if ($current) {
        $checkInDate = substr((string)($current['check_in'] ?? ''), 0, 10);
        $checkOutDate = substr((string)($current['check_out'] ?? ''), 0, 10);

        $slotCheckedIn = ((int)($current['checked_in_status'] ?? 0) === 1);
        $slotCheckedOut = ((int)($current['checked_out_status'] ?? 0) === 1);

        if ($checkInDate === $viewDate && !$slotCheckedIn && !$slotCheckedOut) {
            $occupancyStatus = 'arrival';
            if (!empty($current['order_id'])) {
                $arrivalOrderIdsSeen[(int)$current['order_id']] = true;
            }
        } elseif ($checkOutDate === $viewDate && !$slotCheckedOut) {
            $occupancyStatus = 'departure';
        } elseif ($slotCheckedIn && !$slotCheckedOut) {
            /* A room checked in today should immediately show as Occupied, not just Arrival. */
            $occupancyStatus = 'occupied';
            if ($checkInDate === $viewDate && !empty($current['order_id'])) {
                $arrivalOrderIdsSeen[(int)$current['order_id']] = true;
            }
        } else {
            $occupancyStatus = 'occupied';
        }
    }

    $meta = room_status_meta($occupancyStatus, $rawHousekeeping);

    switch ($meta['label']) {
        case 'Vacant Clean':
            $totalVacantClean++;
            break;
        case 'Vacant Dirty':
            $totalVacantDirty++;
            break;
        case 'Occupied':
            $totalOccupied++;
            break;
        case 'Arrival Today':
            $totalArrivals++;
            break;
        case 'Departure Today':
        case 'Departure / Clean':
            $totalDepartures++;
            break;
        case 'Out of Order':
            $totalOOO++;
            break;
    }

    if ($filterStatus !== '') {
        $pass = false;

        if ($filterStatus === 'vacant_clean' && $meta['label'] === 'Vacant Clean') $pass = true;
        if ($filterStatus === 'vacant_dirty' && $meta['label'] === 'Vacant Dirty') $pass = true;
        if ($filterStatus === 'occupied' && $meta['label'] === 'Occupied') $pass = true;
        if ($filterStatus === 'arrival' && $meta['label'] === 'Arrival Today') $pass = true;
        if ($filterStatus === 'departure' && in_array($meta['label'], ['Departure Today', 'Departure / Clean'], true)) $pass = true;
        if ($filterStatus === 'ooo' && $meta['label'] === 'Out of Order') $pass = true;

        if (!$pass) {
            continue;
        }
    }

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

    $rackRows[] = [
        'room'               => $room,
        'property'           => $propertyLabel,
        'assignment'         => $current,
        'occupancy_status'   => $occupancyStatus,
        'housekeeping_status'=> $rawHousekeeping,
        'meta'               => $meta,
    ];
}


/*
   Add any arrivals that were found by arrivals_today.php logic but were not
   visible through the room-based housekeeping matching. These are usually
   not-yet-room-assigned, older bookings with room_no only, or bookings where
   the rooming row has not been linked to rooms.id yet.
*/
foreach ($arrivalsToday as $arrival) {
    $arrivalOrderId = (int)($arrival['id'] ?? 0);
    if ($arrivalOrderId <= 0 || isset($arrivalOrderIdsSeen[$arrivalOrderId])) {
        continue;
    }

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

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

    $rackRows[] = [
        'room' => [
            'id' => 0,
            'room_no' => $roomLabel,
            'room_type' => $arrival['room_mix'] ?? '',
            'room_name' => 'Arrival booking not linked to a physical room card',
            'housekeeping_status' => 'clean',
            'housekeeping_note' => '',
            'housekeeping_note_updated_at' => '',
        ],
        'property' => $propertyLabel !== '' ? $propertyLabel : 'Not set',
        'assignment' => [
            'order_id' => $arrivalOrderId,
            'order_no' => $arrival['order_no'] ?? '',
            'check_in' => $arrival['check_in'] ?? '',
            'check_out' => $arrival['check_out'] ?? '',
            'expected_arrival_time' => $arrival['expected_arrival_time'] ?? '',
            'firstname' => $arrival['firstname'] ?? '',
            'lastname' => $arrival['lastname'] ?? '',
            'agent_name' => $arrival['agent_name'] ?? '',
            'booking_balance' => $arrival['booking_balance'] ?? 0,
            'room_slots_total' => $arrival['room_slots_total'] ?? 0,
            'room_slots_checked_in' => $arrival['room_slots_checked_in'] ?? 0,
            'room_slots_checked_out' => $arrival['room_slots_checked_out'] ?? 0,
        ],
        'occupancy_status' => 'arrival',
        'housekeeping_status' => 'clean',
        'meta' => room_status_meta('arrival', 'clean'),
        'virtual_arrival' => true,
    ];
}

/*
   Arrival metric must agree with arrivals_today.php: count bookings arriving
   today, not only rooms that could be matched to the room rack.
*/
$totalArrivals = count($arrivalsToday);


$hkLanes = [
    'vacant_dirty' => ['title' => 'Dirty Rooms', 'icon' => 'bi-droplet-half', 'class' => 'warning', 'subtitle' => 'Needs cleaning'],
    'departure'    => ['title' => 'Departures', 'icon' => 'bi-box-arrow-right', 'class' => 'info', 'subtitle' => 'Due out / turnover'],
    'arrival'      => ['title' => 'Arrivals', 'icon' => 'bi-box-arrow-in-right', 'class' => 'primary', 'subtitle' => 'Expected today'],
    'occupied'     => ['title' => 'Occupied', 'icon' => 'bi-house-door', 'class' => 'danger', 'subtitle' => 'Stayover rooms'],
    'vacant_clean' => ['title' => 'Clean / Ready', 'icon' => 'bi-check2-square', 'class' => 'success', 'subtitle' => 'Ready to sell'],
    'ooo'          => ['title' => 'Out of Order', 'icon' => 'bi-tools', 'class' => 'dark', 'subtitle' => 'Maintenance blocked'],
];

$hkLaneRows = [];
foreach ($hkLanes as $laneKey => $laneMeta) {
    $hkLaneRows[$laneKey] = [];
}

foreach ($rackRows as $laneRow) {
    $label = (string)($laneRow['meta']['label'] ?? '');
    $laneKey = 'occupied';

    if ($label === 'Vacant Dirty') {
        $laneKey = 'vacant_dirty';
    } elseif (in_array($label, ['Departure Today', 'Departure / Clean'], true)) {
        $laneKey = 'departure';
    } elseif ($label === 'Arrival Today') {
        $laneKey = 'arrival';
    } elseif ($label === 'Occupied') {
        $laneKey = 'occupied';
    } elseif ($label === 'Vacant Clean' || $label === 'Vacant') {
        $laneKey = 'vacant_clean';
    } elseif ($label === 'Out of Order') {
        $laneKey = 'ooo';
    }

    if (!isset($hkLaneRows[$laneKey])) {
        $hkLaneRows[$laneKey] = [];
    }
    $hkLaneRows[$laneKey][] = $laneRow;
}

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

<div class="hero-band hk-board-hero mb-2">
    <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-brush"></i> Operations</div>
            <div class="hero-title">Housekeeping Board</div>
            <div class="hero-subtitle">Elite board mode for cleaning, inspections, stayovers, arrivals and departures.</div>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="housekeeping_pdf.php?<?php echo h(http_build_query(['view_date'=>$viewDate,'property_id'=>$propertyId,'q'=>$search,'filter_status'=>$filterStatus])); ?>"
               target="_blank"
               class="btn btn-sm btn-light">
                <i class="bi bi-file-earmark-pdf me-1"></i>PDF
            </a>
            <button type="button" class="btn btn-sm btn-outline-light" onclick="window.print()">
                <i class="bi bi-printer me-1"></i>Print
            </button>
            <a href="/rooms/modules/payments/frontdesk_dashboard.php" class="btn btn-sm btn-outline-light">
                <i class="bi bi-arrow-left me-1"></i>Front Desk
            </a>
            <a href="housekeeping_board.php" class="btn btn-sm btn-light">
                <i class="bi bi-arrow-clockwise me-1"></i>Today
            </a>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success py-2 mb-2"><?php echo h($success); ?></div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger py-2 mb-2">
        <div class="fw-bold mb-1">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="hk-toolbar card panel-card mb-2">
    <div class="card-body p-2">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-lg-2 col-md-3">
                <label class="form-label">View Date</label>
                <input type="date" name="view_date" class="form-control" value="<?php echo h($viewDate); ?>">
            </div>

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

            <div class="col-lg-2 col-md-3">
                <label class="form-label">Status</label>
                <select name="filter_status" class="form-select">
                    <option value="">All statuses</option>
                    <option value="vacant_clean" <?php echo $filterStatus === 'vacant_clean' ? 'selected' : ''; ?>>Clean / Ready</option>
                    <option value="vacant_dirty" <?php echo $filterStatus === 'vacant_dirty' ? 'selected' : ''; ?>>Dirty</option>
                    <option value="occupied" <?php echo $filterStatus === 'occupied' ? 'selected' : ''; ?>>Occupied</option>
                    <option value="arrival" <?php echo $filterStatus === 'arrival' ? 'selected' : ''; ?>>Arrival</option>
                    <option value="departure" <?php echo $filterStatus === 'departure' ? 'selected' : ''; ?>>Departure</option>
                    <option value="ooo" <?php echo $filterStatus === 'ooo' ? 'selected' : ''; ?>>Out of Order</option>
                </select>
            </div>

            <div class="col-lg-3 col-md-4">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Room no, room name, room type...">
            </div>

            <div class="col-lg-2 col-md-2 d-grid">
                <button class="btn btn-primary"><i class="bi bi-funnel me-1"></i>Apply</button>
            </div>
        </form>
    </div>
</div>

<div class="hk-metric-strip mb-2">
    <a class="hk-metric text-success" href="housekeeping_board.php?<?php echo h(http_build_query(['view_date'=>$viewDate,'property_id'=>$propertyId,'q'=>$search,'filter_status'=>'vacant_clean'])); ?>">
        <span><i class="bi bi-check2-square"></i> Clean</span><strong><?php echo number_format($totalVacantClean); ?></strong>
    </a>
    <a class="hk-metric text-warning" href="housekeeping_board.php?<?php echo h(http_build_query(['view_date'=>$viewDate,'property_id'=>$propertyId,'q'=>$search,'filter_status'=>'vacant_dirty'])); ?>">
        <span><i class="bi bi-droplet-half"></i> Dirty</span><strong><?php echo number_format($totalVacantDirty); ?></strong>
    </a>
    <a class="hk-metric text-danger" href="housekeeping_board.php?<?php echo h(http_build_query(['view_date'=>$viewDate,'property_id'=>$propertyId,'q'=>$search,'filter_status'=>'occupied'])); ?>">
        <span><i class="bi bi-house-door"></i> Occupied</span><strong><?php echo number_format($totalOccupied); ?></strong>
    </a>
    <a class="hk-metric text-primary" href="housekeeping_board.php?<?php echo h(http_build_query(['view_date'=>$viewDate,'property_id'=>$propertyId,'q'=>$search,'filter_status'=>'arrival'])); ?>">
        <span><i class="bi bi-box-arrow-in-right"></i> Arrivals</span><strong><?php echo number_format($totalArrivals); ?></strong>
    </a>
    <a class="hk-metric text-info" href="housekeeping_board.php?<?php echo h(http_build_query(['view_date'=>$viewDate,'property_id'=>$propertyId,'q'=>$search,'filter_status'=>'departure'])); ?>">
        <span><i class="bi bi-box-arrow-right"></i> Departures</span><strong><?php echo number_format($totalDepartures); ?></strong>
    </a>
    <a class="hk-metric text-dark" href="housekeeping_board.php?<?php echo h(http_build_query(['view_date'=>$viewDate,'property_id'=>$propertyId,'q'=>$search,'filter_status'=>'ooo'])); ?>">
        <span><i class="bi bi-tools"></i> OOO</span><strong><?php echo number_format($totalOOO); ?></strong>
    </a>
</div>

<?php if (!$rackRows): ?>
    <div class="card panel-card">
        <div class="card-body text-center text-muted py-5">No rooms found.</div>
    </div>
<?php else: ?>
    <div class="hk-board-wrap">
        <div class="hk-board">
            <?php foreach ($hkLanes as $laneKey => $laneMeta): ?>
                <?php $laneItems = $hkLaneRows[$laneKey] ?? []; ?>
                <?php if ($filterStatus !== '' && $laneKey !== $filterStatus && !($filterStatus === 'ooo' && $laneKey === 'ooo')) continue; ?>
                <section class="hk-lane hk-lane-<?php echo h($laneKey); ?>">
                    <div class="hk-lane-head">
                        <div>
                            <div class="hk-lane-title text-<?php echo h($laneMeta['class']); ?>">
                                <i class="bi <?php echo h($laneMeta['icon']); ?>"></i>
                                <?php echo h($laneMeta['title']); ?>
                            </div>
                            <div class="hk-lane-subtitle"><?php echo h($laneMeta['subtitle']); ?></div>
                        </div>
                        <span class="badge text-bg-<?php echo h($laneMeta['class']); ?>"><?php echo number_format(count($laneItems)); ?></span>
                    </div>

                    <div class="hk-lane-body">
                        <?php if (!$laneItems): ?>
                            <div class="hk-empty-lane">No rooms</div>
                        <?php endif; ?>

                        <?php foreach ($laneItems as $row): ?>
                            <?php
                            $room = $row['room'];
                            $assignment = $row['assignment'];
                            $meta = $row['meta'];
                            $housekeepingStatus = $row['housekeeping_status'];

                            $roomNo = trim((string)($room['room_no'] ?? ''));
                            $roomType = trim((string)($room['room_type'] ?? ''));
                            $roomName = $hkHasRoomNameColumn ? trim((string)($room['room_name'] ?? '')) : '';
                            $housekeepingNote = trim((string)($room['housekeeping_note'] ?? ''));
                            $housekeepingNoteAt = trim((string)($room['housekeeping_note_updated_at'] ?? ''));
                            $bookingId = (int)($assignment['order_id'] ?? 0);
                            $bookingNo = trim((string)($assignment['order_no'] ?? ''));
                            $guestName = trim((string)($assignment['firstname'] ?? '') . ' ' . (string)($assignment['lastname'] ?? ''));
                            if ($guestName === '') { $guestName = '—'; }
                            $agentName = trim((string)($assignment['agent_name'] ?? ''));
                            if ($agentName === '') { $agentName = 'Direct'; }
                            $balance = (float)($assignment['booking_balance'] ?? 0);

                            $capabilityBadges = [];
                            if (array_key_exists('max_occupancy', $room)) {
                                $capabilityBadges[] = 'Max Occ ' . (int)($room['max_occupancy'] ?? 0);
                            }
                            if (!empty($room['allows_extra_bed'])) {
                                $capabilityBadges[] = 'Extra Bed x ' . (int)($room['max_extra_beds'] ?? 0);
                            }
                            if (!empty($room['allows_baby_cot'])) {
                                $capabilityBadges[] = 'Cot x ' . (int)($room['max_cots'] ?? 0);
                            }
                            if (!empty($room['wheelchair_accessible'])) {
                                $capabilityBadges[] = 'Wheelchair';
                            }
                            if (trim((string)($room['interleading_group'] ?? '')) !== '') {
                                $capabilityBadges[] = 'Interleading ' . trim((string)$room['interleading_group']);
                            }
                            if (!empty($room['balcony'])) {
                                $capabilityBadges[] = 'Balcony';
                            }
                            if (trim((string)($room['view_type'] ?? '')) !== '') {
                                $capabilityBadges[] = trim((string)$room['view_type']);
                            }
                            $bathShower = [];
                            if (!empty($room['bath'])) { $bathShower[] = 'Bath'; }
                            if (!empty($room['shower'])) { $bathShower[] = 'Shower'; }
                            if ($bathShower) { $capabilityBadges[] = implode(' / ', $bathShower); }

                            $setupBadges = [];
                            if ($assignment) {
                                $eta = trim((string)($assignment['expected_arrival_time'] ?? ''));
                                if ($eta !== '') {
                                    $setupBadges[] = 'ETA ' . substr($eta, 0, 5);
                                }
                                if ((int)($assignment['extra_beds_required'] ?? 0) > 0) {
                                    $setupBadges[] = 'Extra Bed x ' . (int)$assignment['extra_beds_required'];
                                }
                                if ((int)($assignment['cots_required'] ?? 0) > 0) {
                                    $setupBadges[] = 'Cot x ' . (int)$assignment['cots_required'];
                                }
                                if (!empty($assignment['wheelchair_room_required'])) {
                                    $setupBadges[] = 'Wheelchair Required';
                                }
                                if (!empty($assignment['interleading_required'])) {
                                    $setupBadges[] = 'Interleading Required';
                                }
                            }

                            $roomConfigNotes = trim((string)($room['room_configuration_notes'] ?? ''));
                            $roomSetupNotes = trim((string)($assignment['room_setup_notes'] ?? ''));
                            $roomingHousekeepingNotes = trim((string)($assignment['housekeeping_notes'] ?? ''));
                            $specialOccasion = trim((string)($assignment['special_occasion'] ?? ''));
                            ?>
                            <article class="hk-card hk-card-<?php echo h($laneKey); ?>">
                                <div class="hk-card-top">
                                    <div>
                                        <div class="hk-room"><?php echo h($roomNo !== '' ? $roomNo : 'Room'); ?></div>
                                        <div class="hk-room-meta">
                                            <?php echo h($roomType !== '' ? $roomType : 'No type'); ?>
                                            <?php if ($roomName !== ''): ?> • <?php echo h($roomName); ?><?php endif; ?>
                                        </div>
                                    </div>
                                    <span class="badge text-bg-<?php echo h($meta['class']); ?>"><?php echo h($meta['label']); ?></span>
                                </div>

                                <div class="hk-property"><i class="bi bi-building me-1"></i><?php echo h($row['property']); ?></div>

                                <?php if ($capabilityBadges): ?>
                                    <div class="hk-badge-wrap mb-2">
                                        <?php foreach ($capabilityBadges as $badge): ?>
                                            <span class="hk-mini-badge hk-mini-badge-room"><?php echo h($badge); ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>

                                <?php if ($setupBadges || $roomSetupNotes !== '' || $roomingHousekeepingNotes !== '' || $specialOccasion !== '' || $roomConfigNotes !== ''): ?>
                                    <div class="hk-setup-box mb-2">
                                        <?php if ($setupBadges): ?>
                                            <div class="hk-badge-wrap mb-1">
                                                <?php foreach ($setupBadges as $badge): ?>
                                                    <span class="hk-mini-badge hk-mini-badge-setup"><?php echo h($badge); ?></span>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($specialOccasion !== ''): ?>
                                            <div><strong>Occasion:</strong> <?php echo h($specialOccasion); ?></div>
                                        <?php endif; ?>
                                        <?php if ($roomSetupNotes !== ''): ?>
                                            <div><strong>Setup:</strong> <?php echo h($roomSetupNotes); ?></div>
                                        <?php endif; ?>
                                        <?php if ($roomingHousekeepingNotes !== ''): ?>
                                            <div><strong>HK:</strong> <?php echo h($roomingHousekeepingNotes); ?></div>
                                        <?php endif; ?>
                                        <?php if ($roomConfigNotes !== ''): ?>
                                            <div><strong>Room Config:</strong> <?php echo h($roomConfigNotes); ?></div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>

                                <?php if ($housekeepingNote !== ''): ?>
                                    <div class="hk-note mb-2">
                                        <div class="small fw-semibold text-muted mb-1">
                                            <i class="bi bi-card-text me-1"></i>Note
                                            <?php if ($housekeepingNoteAt !== ''): ?>
                                                <span class="text-muted fw-normal">• <?php echo h($housekeepingNoteAt); ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <div><?php echo nl2br(h($housekeepingNote)); ?></div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($assignment): ?>
                                    <div class="hk-line"><span>Booking</span><strong><?php echo h($bookingNo !== '' ? $bookingNo : ('#' . $bookingId)); ?></strong></div>
                                    <div class="hk-line"><span>Guest</span><strong><?php echo h($guestName); ?></strong></div>
                                    <div class="hk-line"><span>Stay</span><strong><?php echo h($assignment['check_in']); ?> → <?php echo h($assignment['check_out']); ?></strong></div>
                                    <?php if (!empty($assignment['expected_arrival_time'])): ?>
                                        <div class="hk-line"><span>ETA</span><strong><?php echo h(substr((string)$assignment['expected_arrival_time'], 0, 5)); ?></strong></div>
                                    <?php endif; ?>
                                    <div class="hk-line"><span>Balance</span><strong><?php echo money_fmt($balance); ?></strong></div>
                                    <?php if (isset($assignment['room_slots_total'])): ?>
                                        <div class="hk-line"><span>Check-In</span><strong><?php echo (int)($assignment['room_slots_checked_in'] ?? 0); ?>/<?php echo (int)($assignment['room_slots_total'] ?? 0); ?> rooms</strong></div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <div class="hk-line"><span>Occupancy</span><strong>Vacant</strong></div>
                                    <div class="hk-line"><span>Date</span><strong><?php echo h($viewDate); ?></strong></div>
                                    <div class="hk-line"><span>Status</span><strong><?php echo h(ucwords(str_replace('_', ' ', $housekeepingStatus))); ?></strong></div>
                                <?php endif; ?>

                                <?php if ((int)($room['id'] ?? 0) > 0): ?>
                                    <div class="hk-actions mt-2">
                                        <form method="post">
                                            <input type="hidden" name="room_id" value="<?php echo (int)$room['id']; ?>">
                                            <input type="hidden" name="new_status" value="clean">
                                            <input type="hidden" name="view_date" value="<?php echo h($viewDate); ?>">
                                            <input type="hidden" name="property_id" value="<?php echo (int)$propertyId; ?>">
                                            <input type="hidden" name="q" value="<?php echo h($search); ?>">
                                            <input type="hidden" name="filter_status" value="<?php echo h($filterStatus); ?>">
                                            <button type="submit" name="update_room_status" value="1" class="btn btn-sm btn-outline-success">Clean</button>
                                        </form>

                                        <form method="post">
                                            <input type="hidden" name="room_id" value="<?php echo (int)$room['id']; ?>">
                                            <input type="hidden" name="new_status" value="dirty">
                                            <input type="hidden" name="view_date" value="<?php echo h($viewDate); ?>">
                                            <input type="hidden" name="property_id" value="<?php echo (int)$propertyId; ?>">
                                            <input type="hidden" name="q" value="<?php echo h($search); ?>">
                                            <input type="hidden" name="filter_status" value="<?php echo h($filterStatus); ?>">
                                            <button type="submit" name="update_room_status" value="1" class="btn btn-sm btn-outline-warning">Dirty</button>
                                        </form>

                                        <button type="button"
                                                class="btn btn-sm btn-outline-info hk-note-action"
                                                data-bs-toggle="modal"
                                                data-bs-target="#hkNoteModal"
                                                data-room-id="<?php echo (int)$room['id']; ?>"
                                                data-room-label="<?php echo h($roomNo !== '' ? $roomNo : ('Room #' . (int)$room['id'])); ?>"
                                                data-new-status="inspected"
                                                data-modal-title="Inspection Notes"
                                                data-note-label="Inspection Notes"
                                                data-note-placeholder="Enter inspection findings, defects noticed, or handover notes..."
                                                data-existing-note="<?php echo h($housekeepingNote); ?>">
                                            Inspect
                                        </button>

                                        <form method="post">
                                            <input type="hidden" name="room_id" value="<?php echo (int)$room['id']; ?>">
                                            <input type="hidden" name="new_status" value="available">
                                            <input type="hidden" name="view_date" value="<?php echo h($viewDate); ?>">
                                            <input type="hidden" name="property_id" value="<?php echo (int)$propertyId; ?>">
                                            <input type="hidden" name="q" value="<?php echo h($search); ?>">
                                            <input type="hidden" name="filter_status" value="<?php echo h($filterStatus); ?>">
                                            <button type="submit" name="update_room_status" value="1" class="btn btn-sm btn-outline-secondary">Ready</button>
                                        </form>
                                    </div>

                                    <button type="button"
                                            class="btn btn-sm btn-outline-dark w-100 mt-2 hk-note-action"
                                            data-bs-toggle="modal"
                                            data-bs-target="#hkNoteModal"
                                            data-room-id="<?php echo (int)$room['id']; ?>"
                                            data-room-label="<?php echo h($roomNo !== '' ? $roomNo : ('Room #' . (int)$room['id'])); ?>"
                                            data-new-status="out_of_order"
                                            data-modal-title="Out of Order Notes"
                                            data-note-label="Reason / Maintenance Notes"
                                            data-note-placeholder="Enter the reason, maintenance issue, expected action, or follow-up notes..."
                                            data-existing-note="<?php echo h($housekeepingNote); ?>">
                                        <i class="bi bi-tools me-1"></i>Out of Order
                                    </button>
                                <?php else: ?>
                                    <div class="alert alert-warning py-2 px-2 small mb-2">
                                        <strong>Arrival not linked to a physical room card.</strong><br>
                                        Assign/check in from the booking to attach housekeeping room actions.
                                    </div>
                                <?php endif; ?>

                                <?php if ($assignment): ?>
                                    <div class="hk-front-actions mt-2">
                                        <a href="/rooms/modules/payments/payments.php?order_id=<?php echo $bookingId; ?>" class="btn btn-sm btn-outline-primary">Payments</a>
                                        <a href="/rooms/modules/payments/folio.php?q=<?php echo urlencode((string)($bookingNo !== '' ? $bookingNo : $bookingId)); ?>" class="btn btn-sm btn-outline-secondary">Folios</a>
                                        <a href="/rooms/modules/reservations/reservation_view.php?order_id=<?php echo $bookingId; ?>" class="btn btn-sm btn-light">View</a>
                                    </div>
                                <?php endif; ?>
                            </article>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endforeach; ?>
        </div>
    </div>
<?php endif; ?>

<div class="modal fade" id="hkNoteModal" tabindex="-1" aria-labelledby="hkNoteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form method="post" class="modal-content">
            <div class="modal-header">
                <div>
                    <h5 class="modal-title" id="hkNoteModalLabel">Housekeeping Notes</h5>
                    <div class="small text-muted" id="hkNoteModalRoom">Room</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <input type="hidden" name="room_id" id="hk_modal_room_id" value="">
                <input type="hidden" name="new_status" id="hk_modal_new_status" value="">
                <input type="hidden" name="view_date" value="<?php echo h($viewDate); ?>">
                <input type="hidden" name="property_id" value="<?php echo (int)$propertyId; ?>">
                <input type="hidden" name="q" value="<?php echo h($search); ?>">
                <input type="hidden" name="filter_status" value="<?php echo h($filterStatus); ?>">

                <label class="form-label fw-semibold" id="hkNoteModalTextareaLabel" for="hk_modal_status_note">Notes</label>
                <textarea name="status_note"
                          id="hk_modal_status_note"
                          class="form-control"
                          rows="5"
                          required
                          placeholder="Enter notes..."></textarea>
                <div class="form-text">Notes are required for Inspect and Out of Order actions.</div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" name="update_room_status" value="1" class="btn btn-primary" id="hkNoteModalSaveBtn">Save Status</button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var modal = document.getElementById('hkNoteModal');
    if (!modal) return;

    modal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        if (!button) return;

        var roomId = button.getAttribute('data-room-id') || '';
        var roomLabel = button.getAttribute('data-room-label') || 'Room';
        var newStatus = button.getAttribute('data-new-status') || '';
        var modalTitle = button.getAttribute('data-modal-title') || 'Housekeeping Notes';
        var noteLabel = button.getAttribute('data-note-label') || 'Notes';
        var notePlaceholder = button.getAttribute('data-note-placeholder') || 'Enter notes...';
        var existingNote = button.getAttribute('data-existing-note') || '';

        var titleEl = document.getElementById('hkNoteModalLabel');
        var roomEl = document.getElementById('hkNoteModalRoom');
        var roomIdEl = document.getElementById('hk_modal_room_id');
        var statusEl = document.getElementById('hk_modal_new_status');
        var labelEl = document.getElementById('hkNoteModalTextareaLabel');
        var noteEl = document.getElementById('hk_modal_status_note');
        var saveBtn = document.getElementById('hkNoteModalSaveBtn');

        if (titleEl) titleEl.textContent = modalTitle;
        if (roomEl) roomEl.textContent = roomLabel;
        if (roomIdEl) roomIdEl.value = roomId;
        if (statusEl) statusEl.value = newStatus;
        if (labelEl) labelEl.textContent = noteLabel;
        if (noteEl) {
            noteEl.value = existingNote;
            noteEl.placeholder = notePlaceholder;
            setTimeout(function () { noteEl.focus(); }, 250);
        }
        if (saveBtn) {
            saveBtn.className = newStatus === 'out_of_order' ? 'btn btn-dark' : 'btn btn-info';
            saveBtn.textContent = newStatus === 'out_of_order' ? 'Save Out of Order' : 'Save Inspection';
        }
    });
});
</script>

<style>
/* Elite Housekeeping Board Mode */
.hk-board-hero{
    padding:12px 16px !important;
    border-radius:16px;
}
.hk-board-hero .hero-title{
    font-size:1.12rem;
    line-height:1.1;
    margin-top:2px !important;
}
.hk-board-hero .hero-subtitle{
    font-size:.78rem;
    line-height:1.2;
    margin-top:3px !important;
}
.hk-board-hero .page-eyebrow{
    font-size:.7rem;
}
.hk-toolbar{
    position:sticky;
    top:0;
    z-index:30;
    border-radius:16px;
}
.hk-toolbar .form-label{
    font-size:.72rem;
    font-weight:700;
    margin-bottom:2px;
    color:#64748b;
}
.hk-toolbar .form-control,
.hk-toolbar .form-select{
    min-height:32px;
    padding:.3rem .55rem;
    font-size:.82rem;
    border-radius:10px;
}
.hk-toolbar .btn{
    min-height:32px;
    padding:.3rem .65rem;
    font-size:.82rem;
    border-radius:10px;
}
.hk-metric-strip{
    display:grid;
    grid-template-columns:repeat(6,minmax(120px,1fr));
    gap:8px;
}
.hk-metric{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:8px;
    text-decoration:none;
    background:#fff;
    border:1px solid #e7edf5;
    border-radius:14px;
    padding:8px 10px;
    box-shadow:0 6px 18px rgba(15,23,42,.04);
}
.hk-metric span{
    font-size:.74rem;
    font-weight:800;
    white-space:nowrap;
}
.hk-metric strong{
    font-size:1rem;
    color:#0f172a;
}
.hk-board-wrap{
    overflow-x:auto;
    padding-bottom:8px;
}
.hk-board{
    display:grid;
    grid-template-columns:repeat(6,minmax(260px,1fr));
    gap:12px;
    align-items:start;
    min-width:1560px;
}
.hk-lane{
    background:#f8fafc;
    border:1px solid #e6edf5;
    border-radius:18px;
    overflow:hidden;
    min-height:360px;
}
.hk-lane-head{
    position:sticky;
    top:56px;
    z-index:10;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    padding:10px 12px;
    background:rgba(255,255,255,.96);
    border-bottom:1px solid #e6edf5;
    backdrop-filter:blur(6px);
}
.hk-lane-title{
    display:flex;
    align-items:center;
    gap:6px;
    font-size:.86rem;
    font-weight:900;
    line-height:1.1;
}
.hk-lane-subtitle{
    font-size:.68rem;
    color:#64748b;
    margin-top:2px;
}
.hk-lane-body{
    padding:10px;
    display:flex;
    flex-direction:column;
    gap:10px;
}
.hk-empty-lane{
    border:1px dashed #cbd5e1;
    border-radius:14px;
    padding:18px 10px;
    color:#94a3b8;
    text-align:center;
    font-size:.82rem;
    background:#fff;
}
.hk-card{
    background:#fff;
    border:1px solid #e6edf5;
    border-radius:16px;
    padding:10px;
    box-shadow:0 8px 22px rgba(15,23,42,.06);
}
.hk-card-vacant_dirty{border-left:4px solid #f59e0b;}
.hk-card-departure{border-left:4px solid #0dcaf0;}
.hk-card-arrival{border-left:4px solid #0d6efd;}
.hk-card-occupied{border-left:4px solid #dc3545;}
.hk-card-vacant_clean{border-left:4px solid #198754;}
.hk-card-ooo{border-left:4px solid #212529;}
.hk-card-top{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:8px;
    margin-bottom:6px;
}
.hk-room{
    font-size:1.1rem;
    font-weight:900;
    color:#111827;
    line-height:1.05;
}
.hk-room-meta,
.hk-property{
    color:#64748b;
    font-size:.74rem;
    line-height:1.2;
}
.hk-property{
    margin-bottom:8px;
}
.hk-line{
    display:flex;
    justify-content:space-between;
    gap:10px;
    padding:5px 0;
    border-bottom:1px dashed #eef2f7;
    font-size:.8rem;
}
.hk-line:last-of-type{border-bottom:none;}
.hk-line span{color:#64748b;}
.hk-line strong{
    text-align:right;
    color:#111827;
    max-width:62%;
    overflow:hidden;
    text-overflow:ellipsis;
}
.hk-note{
    border:1px solid #e5e7eb;
    border-left:4px solid #0dcaf0;
    background:#f8fafc;
    border-radius:12px;
    padding:8px 10px;
    font-size:.78rem;
    color:#334155;
}
.hk-actions{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:6px;
}
.hk-actions form,
.hk-actions button,
.hk-front-actions a{
    min-width:0;
}
.hk-actions .btn,
.hk-front-actions .btn{
    width:100%;
    padding:.25rem .45rem;
    font-size:.76rem;
    border-radius:10px;
}
.hk-front-actions{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:6px;
}

.hk-badge-wrap{
    display:flex;
    flex-wrap:wrap;
    gap:4px;
}
.hk-mini-badge{
    display:inline-flex;
    align-items:center;
    border-radius:999px;
    padding:2px 6px;
    font-size:.66rem;
    font-weight:800;
    line-height:1.25;
    border:1px solid transparent;
}
.hk-mini-badge-room{
    background:#eff6ff;
    border-color:#bfdbfe;
    color:#1d4ed8;
}
.hk-mini-badge-setup{
    background:#fef3c7;
    border-color:#fde68a;
    color:#92400e;
}
.hk-setup-box{
    background:#fff7ed;
    border:1px solid #fed7aa;
    border-left:4px solid #f97316;
    border-radius:12px;
    padding:7px 9px;
    font-size:.72rem;
    color:#7c2d12;
}

@media (max-width: 1199.98px){
    .hk-metric-strip{grid-template-columns:repeat(3,1fr);}
}
@media (max-width: 767.98px){
    .hk-metric-strip{grid-template-columns:repeat(2,1fr);}
    .hk-board{grid-template-columns:repeat(6,260px);}
    .hk-board-hero{padding:10px 12px !important;}
}
</style>

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