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

$pageTitle = 'Reservation Waitlist';

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

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

if (!function_exists('fetch_room_types_by_property')) {
    function fetch_room_types_by_property(PDO $pdo, int $propertyId): array
    {
        if ($propertyId <= 0) {
            return [];
        }

        $stmt = $pdo->prepare("
            SELECT id, title, higher_occupancy
            FROM room_types
            WHERE property_id = :property_id
            ORDER BY title ASC
        ");
        $stmt->execute([':property_id' => $propertyId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}

if (!function_exists('count_available_rooms_by_type')) {
    function count_available_rooms_by_type(PDO $pdo, int $propertyId, int $roomTypeId, string $checkIn, string $checkOut, int $excludeOrderId = 0): array
    {
        if ($propertyId <= 0 || $roomTypeId <= 0 || $checkIn === '' || $checkOut === '') {
            return [
                'total_rooms'     => 0,
                'occupied_rooms'  => 0,
                'available_rooms' => 0,
            ];
        }

        $stmtTotal = $pdo->prepare("
            SELECT COUNT(*)
            FROM rooms
            WHERE property_id = :property_id
              AND room_type_id = :room_type_id
        ");
        $stmtTotal->execute([
            ':property_id'  => $propertyId,
            ':room_type_id' => $roomTypeId,
        ]);
        $totalRooms = (int)$stmtTotal->fetchColumn();

        /*
           Important waitlist adjustment:
           Availability must be based on actual rooming allocations, not orders.totalrooms.
           This keeps waitlist matching in sync with check-out/release logic:
           - checked-out rooming lines no longer block rooms
           - cancelled/void bookings do not block rooms
           - multi-room allocations are counted from order_rooming
        */
        $sql = "
            SELECT COUNT(DISTINCT orm.room_id)
            FROM order_rooming orm
            INNER JOIN orders o ON o.id = orm.order_id
            INNER JOIN rooms rm ON rm.id = orm.room_id
            WHERE o.property_id = :property_id
              AND rm.room_type_id = :room_type_id
              AND orm.room_id > 0
              AND COALESCE(o.status, 1) <> 0
              AND COALESCE(orm.checked_out_status, 0) = 0
              AND orm.check_in < :check_out
              AND orm.check_out > :check_in
        ";
        $params = [
            ':property_id'  => $propertyId,
            ':room_type_id' => $roomTypeId,
            ':check_in'     => $checkIn,
            ':check_out'    => $checkOut,
        ];

        if ($excludeOrderId > 0) {
            $sql .= " AND o.id <> :exclude_order_id ";
            $params[':exclude_order_id'] = $excludeOrderId;
        }

        $stmtOcc = $pdo->prepare($sql);
        $stmtOcc->execute($params);
        $occupiedRooms = (int)$stmtOcc->fetchColumn();

        return [
            'total_rooms'     => $totalRooms,
            'occupied_rooms'  => $occupiedRooms,
            'available_rooms' => max(0, $totalRooms - $occupiedRooms),
        ];
    }
}

if (!function_exists('normalize_room_groups')) {
    function normalize_room_groups(array $rows): array
    {
        $clean = [];

        foreach ($rows as $row) {
            $roomTypeId = (int)($row['room_type_id'] ?? 0);
            $qtyRooms   = max(1, (int)($row['qty_rooms'] ?? 1));
            $adults     = max(0, (int)($row['adults'] ?? 0));
            $children   = max(0, (int)($row['children'] ?? 0));

            if ($roomTypeId <= 0 && $adults <= 0 && $children <= 0) {
                continue;
            }

            $clean[] = [
                'room_type_id' => $roomTypeId,
                'qty_rooms'    => $qtyRooms,
                'adults'       => $adults,
                'children'     => $children,
            ];
        }

        if (!$clean) {
            $clean[] = [
                'room_type_id' => 0,
                'qty_rooms'    => 1,
                'adults'       => 1,
                'children'     => 0,
            ];
        }

        return array_values($clean);
    }
}

if (!function_exists('summarize_room_groups')) {
    function summarize_room_groups(array $groups): array
    {
        $totalRooms = 0;
        $adults = 0;
        $kids = 0;

        foreach ($groups as $group) {
            $totalRooms += max(1, (int)($group['qty_rooms'] ?? 1));
            $adults += max(0, (int)($group['adults'] ?? 0));
            $kids   += max(0, (int)($group['children'] ?? 0));
        }

        return [
            'totalrooms' => $totalRooms,
            'adults'     => $adults,
            'kids'       => $kids,
            'total_pax'  => $adults + $kids,
        ];
    }
}

if (!function_exists('fetch_waitlist_room_groups')) {
    function fetch_waitlist_room_groups(PDO $pdo, int $waitlistId): array
    {
        if ($waitlistId <= 0) {
            return [];
        }

        try {
            $stmt = $pdo->prepare("
                SELECT room_type_id, qty_rooms, adults, children
                FROM reservation_waitlist_groups
                WHERE waitlist_id = :waitlist_id
                ORDER BY id ASC
            ");
            $stmt->execute([':waitlist_id' => $waitlistId]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('save_waitlist_room_groups')) {
    function save_waitlist_room_groups(PDO $pdo, int $waitlistId, int $propertyId, string $checkIn, string $checkOut, array $groups): void
    {
        if ($waitlistId <= 0) {
            return;
        }

        $pdo->prepare("DELETE FROM reservation_waitlist_groups WHERE waitlist_id = :waitlist_id")
            ->execute([':waitlist_id' => $waitlistId]);

        $insert = $pdo->prepare("
            INSERT INTO reservation_waitlist_groups
            (
                waitlist_id,
                property_id,
                room_type_id,
                qty_rooms,
                adults,
                children,
                check_in,
                check_out
            )
            VALUES
            (
                :waitlist_id,
                :property_id,
                :room_type_id,
                :qty_rooms,
                :adults,
                :children,
                :check_in,
                :check_out
            )
        ");

        foreach ($groups as $group) {
            $insert->execute([
                ':waitlist_id' => $waitlistId,
                ':property_id' => $propertyId,
                ':room_type_id' => (int)$group['room_type_id'],
                ':qty_rooms' => max(1, (int)$group['qty_rooms']),
                ':adults' => max(0, (int)$group['adults']),
                ':children' => max(0, (int)$group['children']),
                ':check_in' => $checkIn,
                ':check_out' => $checkOut,
            ]);
        }
    }
}

if (!function_exists('build_grouped_availability_rows')) {
    function build_grouped_availability_rows(PDO $pdo, int $propertyId, string $checkIn, string $checkOut, array $roomGroups): array
    {
        $rows = [];
        foreach ($roomGroups as $idx => $group) {
            $roomTypeId = (int)($group['room_type_id'] ?? 0);
            $qtyRooms = max(1, (int)($group['qty_rooms'] ?? 1));
            if ($roomTypeId <= 0) {
                continue;
            }

            $availability = count_available_rooms_by_type($pdo, $propertyId, $roomTypeId, $checkIn, $checkOut);
            $rows[] = [
                'row_no' => $idx + 1,
                'room_type_id' => $roomTypeId,
                'qty_rooms' => $qtyRooms,
                'availability' => $availability,
                'can_confirm' => ((int)($availability['available_rooms'] ?? 0) >= $qtyRooms),
            ];
        }
        return $rows;
    }
}

if (!function_exists('fetch_room_type_map')) {
    function fetch_room_type_map(PDO $pdo, int $propertyId): array
    {
        $map = [];
        foreach (fetch_room_types_by_property($pdo, $propertyId) as $row) {
            $map[(int)$row['id']] = $row;
        }
        return $map;
    }
}

$properties = $pdo->query("
    SELECT id, name, code
    FROM properties
    WHERE is_active = 1
    ORDER BY name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$agents = $pdo->query("
    SELECT id, firstname, lastname
    FROM agents
    ORDER BY firstname, lastname ASC
")->fetchAll(PDO::FETCH_ASSOC);

$nationalities = $pdo->query("
    SELECT id, nationality
    FROM nationality
    ORDER BY nationality ASC
")->fetchAll(PDO::FETCH_ASSOC);

$occassions = $pdo->query("
    SELECT id, occassion_name
    FROM occassions
    ORDER BY occassion_name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$form = [
    'id'                 => 0,
    'property_id'        => '',
    'guest_name'         => '',
    'agent_id'           => '',
    'contact_id'         => '',
    'originating_agent'  => '',
    'voucher_no'         => '',
    'occassion_id'       => '',
    'nationality_id'     => '',
    'reservation_notes'  => '',
    'internal_memo'      => '',
    'reminder_info'      => '',
    'check_in'           => date('Y-m-d'),
    'check_out'          => date('Y-m-d', strtotime('+1 day')),
    'room_type_id'       => '',
    'totalrooms'         => 1,
    'adults'             => 2,
    'kids'               => 0,
    'priority'           => 0,
    'room_groups'        => [[
        'room_type_id' => '',
        'qty_rooms'    => 1,
        'adults'       => 2,
        'children'     => 0,
    ]],
];

$errors = [];
$success = '';
if (isset($_GET['saved'])) {
    $success = 'Waitlist saved successfully.';
}
if (isset($_GET['cancelled'])) {
    $success = 'Waitlist entry cancelled.';
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'room_types') {
    header('Content-Type: application/json; charset=utf-8');
    $propertyId = (int)($_GET['property_id'] ?? 0);
    echo json_encode([
        'ok'   => true,
        'rows' => fetch_room_types_by_property($pdo, $propertyId),
    ]);
    exit;
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'availability_grouped') {
    header('Content-Type: application/json; charset=utf-8');

    $propertyId = (int)($_GET['property_id'] ?? 0);
    $checkIn    = trim((string)($_GET['check_in'] ?? ''));
    $checkOut   = trim((string)($_GET['check_out'] ?? ''));
    $postedGroups = json_decode((string)($_GET['room_groups'] ?? '[]'), true);
    $roomGroups = normalize_room_groups(is_array($postedGroups) ? $postedGroups : []);
    $summary = summarize_room_groups($roomGroups);
    $rows = build_grouped_availability_rows($pdo, $propertyId, $checkIn, $checkOut, $roomGroups);

    $canConfirmAll = !empty($rows);
    $minimumAvailable = null;
    foreach ($rows as $row) {
        $available = (int)($row['availability']['available_rooms'] ?? 0);
        if ($minimumAvailable === null || $available < $minimumAvailable) {
            $minimumAvailable = $available;
        }
        if (!$row['can_confirm']) {
            $canConfirmAll = false;
        }
    }

    echo json_encode([
        'ok' => true,
        'summary' => $summary,
        'rows' => $rows,
        'can_confirm_all' => $canConfirmAll,
        'minimum_available' => $minimumAvailable ?? 0,
    ]);
    exit;
}

$currentId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($currentId > 0 && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $row = fetch_waitlist_by_id($pdo, $currentId);
    if ($row) {
        $form = array_merge($form, [
            'id'                 => (int)$row['id'],
            'property_id'        => (string)($row['property_id'] ?? ''),
            'guest_name'         => (string)($row['guest_name'] ?? ''),
            'agent_id'           => (string)($row['agent_id'] ?? ''),
            'contact_id'         => (string)($row['contact_id'] ?? ''),
            'originating_agent'  => (string)($row['originating_agent'] ?? ''),
            'voucher_no'         => (string)($row['voucher_no'] ?? ''),
            'occassion_id'       => (string)($row['occassion_id'] ?? ''),
            'nationality_id'     => (string)($row['nationality_id'] ?? ''),
            'reservation_notes'  => (string)($row['reservation_notes'] ?? ''),
            'internal_memo'      => (string)($row['internal_memo'] ?? ''),
            'reminder_info'      => (string)($row['reminder_info'] ?? ''),
            'check_in'           => (string)($row['check_in'] ?? ''),
            'check_out'          => (string)($row['check_out'] ?? ''),
            'room_type_id'       => (string)($row['room_type_id'] ?? ''),
            'totalrooms'         => (int)($row['totalrooms'] ?? 1),
            'adults'             => (int)($row['adults'] ?? 2),
            'kids'               => (int)($row['kids'] ?? 0),
            'priority'           => (int)($row['priority'] ?? 0),
        ]);

        $savedGroups = fetch_waitlist_room_groups($pdo, $currentId);
        if ($savedGroups) {
            $form['room_groups'] = [];
            foreach ($savedGroups as $grp) {
                $form['room_groups'][] = [
                    'room_type_id' => (string)($grp['room_type_id'] ?? ''),
                    'qty_rooms'    => (int)($grp['qty_rooms'] ?? 1),
                    'adults'       => (int)($grp['adults'] ?? 0),
                    'children'     => (int)($grp['children'] ?? 0),
                ];
            }
            $summary = summarize_room_groups($form['room_groups']);
            $form['totalrooms'] = $summary['totalrooms'];
            $form['adults'] = $summary['adults'];
            $form['kids'] = $summary['kids'];
            $form['room_type_id'] = (string)($form['room_groups'][0]['room_type_id'] ?? '');
        } else {
            $form['room_groups'] = [[
                'room_type_id' => (string)($row['room_type_id'] ?? ''),
                'qty_rooms'    => (int)($row['totalrooms'] ?? 1),
                'adults'       => (int)($row['adults'] ?? 2),
                'children'     => (int)($row['kids'] ?? 0),
            ]];
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_waitlist'])) {
    $form['id']                = (int)($_POST['id'] ?? 0);
    $form['property_id']       = trim((string)($_POST['property_id'] ?? ''));
    $form['guest_name']        = trim((string)($_POST['guest_name'] ?? ''));
    $form['agent_id']          = trim((string)($_POST['agent_id'] ?? ''));
    $form['contact_id']        = trim((string)($_POST['contact_id'] ?? ''));
    $form['originating_agent'] = trim((string)($_POST['originating_agent'] ?? ''));
    $form['voucher_no']        = trim((string)($_POST['voucher_no'] ?? ''));
    $form['occassion_id']      = trim((string)($_POST['occassion_id'] ?? ''));
    $form['nationality_id']    = trim((string)($_POST['nationality_id'] ?? ''));
    $form['reservation_notes'] = trim((string)($_POST['reservation_notes'] ?? ''));
    $form['internal_memo']     = trim((string)($_POST['internal_memo'] ?? ''));
    $form['reminder_info']     = trim((string)($_POST['reminder_info'] ?? ''));
    $form['check_in']          = trim((string)($_POST['check_in'] ?? ''));
    $form['check_out']         = trim((string)($_POST['check_out'] ?? ''));
    $form['priority']          = max(0, (int)($_POST['priority'] ?? 0));

    $postedRoomGroups = $_POST['room_groups'] ?? [];
    $form['room_groups'] = normalize_room_groups(is_array($postedRoomGroups) ? $postedRoomGroups : []);

    $summary = summarize_room_groups($form['room_groups']);
    $form['totalrooms'] = $summary['totalrooms'];
    $form['adults'] = $summary['adults'];
    $form['kids'] = $summary['kids'];
    $form['room_type_id'] = !empty($form['room_groups'][0]['room_type_id']) ? (string)$form['room_groups'][0]['room_type_id'] : '';

    if ((int)$form['property_id'] <= 0) {
        $errors[] = 'Please select a property.';
    }
    if ($form['guest_name'] === '') {
        $errors[] = 'Please enter guest name.';
    }
    if ($form['check_in'] === '' || $form['check_out'] === '') {
        $errors[] = 'Please enter check-in and check-out dates.';
    } else {
        $inTs  = strtotime($form['check_in']);
        $outTs = strtotime($form['check_out']);
        if (!$inTs || !$outTs || $outTs <= $inTs) {
            $errors[] = 'Check-out must be at least 1 day after check-in.';
        }
    }

    if (empty($form['room_groups'])) {
        $errors[] = 'Please add at least one room type row.';
    }

    $roomTypeMap = fetch_room_type_map($pdo, (int)$form['property_id']);

    $seenRoomTypes = [];
    foreach ($form['room_groups'] as $idx => $grp) {
        $rowNo      = $idx + 1;
        $rt         = (int)($grp['room_type_id'] ?? 0);
        $qtyRooms   = max(1, (int)($grp['qty_rooms'] ?? 1));
        $adults     = max(0, (int)($grp['adults'] ?? 0));
        $children   = max(0, (int)($grp['children'] ?? 0));
        $totalPax   = $adults + $children;

        if ($rt <= 0) {
            $errors[] = 'Please select a room type on row ' . $rowNo . '.';
            continue;
        }

        if (isset($seenRoomTypes[$rt])) {
            $errors[] = 'Duplicate room type detected on row ' . $rowNo . '. Combine rows with the same room type.';
            continue;
        }
        $seenRoomTypes[$rt] = true;

        if ($totalPax <= 0) {
            $errors[] = 'Please enter at least 1 guest on row ' . $rowNo . '.';
        }

        if ($qtyRooms > $totalPax && $totalPax > 0) {
            $errors[] = 'Row ' . $rowNo . ': number of rooms cannot be more than total adults + children.';
        }

        $higherOccupancy = (int)($roomTypeMap[$rt]['higher_occupancy'] ?? 0);
        if ($higherOccupancy > 0) {
            $maxAdultsAllowed = $higherOccupancy * $qtyRooms;
            if ($adults > $maxAdultsAllowed) {
                $errors[] = 'Row ' . $rowNo . ': adults cannot exceed ' . $higherOccupancy . ' per room × ' . $qtyRooms . ' room(s) = ' . $maxAdultsAllowed . '.';
            }
        }
    }

    $groupAvailabilityRows = build_grouped_availability_rows(
        $pdo,
        (int)$form['property_id'],
        $form['check_in'],
        $form['check_out'],
        $form['room_groups']
    );

    if (!$errors) {
        try {
            $pdo->beginTransaction();

            $guestId = null;
            $nameParts = preg_split('/\s+/', trim($form['guest_name']), 2);
            $first = trim((string)($nameParts[0] ?? ''));
            $last = trim((string)($nameParts[1] ?? ''));
            if ($first !== '' || $last !== '') {
                $findGuest = $pdo->prepare("SELECT id FROM guests WHERE firstname = :firstname AND lastname = :lastname LIMIT 1");
                $findGuest->execute([':firstname' => $first, ':lastname' => $last]);
                $guestId = (int)($findGuest->fetchColumn() ?: 0);
                if ($guestId <= 0) {
                    $insGuest = $pdo->prepare("INSERT INTO guests (firstname, lastname) VALUES (:firstname, :lastname)");
                    $insGuest->execute([':firstname' => $first, ':lastname' => $last]);
                    $guestId = (int)$pdo->lastInsertId();
                }
            }

            $availableRoomsLast = 0;
            if ($groupAvailabilityRows) {
                $mins = array_map(function ($r) {
                    return (int)($r['availability']['available_rooms'] ?? 0);
                }, $groupAvailabilityRows);
                $availableRoomsLast = (int)min($mins);
            }

            $waitlistId = save_waitlist_entry($pdo, [
                'id'                 => (int)$form['id'],
                'property_id'        => (int)$form['property_id'],
                'guest_id'           => $guestId,
                'guest_name'         => $form['guest_name'],
                'agent_id'           => (int)$form['agent_id'],
                'contact_id'         => (int)$form['contact_id'],
                'originating_agent'  => (int)$form['originating_agent'],
                'voucher_no'         => $form['voucher_no'],
                'occassion_id'       => (int)$form['occassion_id'],
                'nationality_id'     => (int)$form['nationality_id'],
                'reservation_notes'  => $form['reservation_notes'],
                'internal_memo'      => $form['internal_memo'],
                'reminder_info'      => $form['reminder_info'],
                'check_in'           => $form['check_in'],
                'check_out'          => $form['check_out'],
                'room_type_id'       => (int)$form['room_type_id'],
                'totalrooms'         => (int)$form['totalrooms'],
                'adults'             => (int)$form['adults'],
                'kids'               => (int)$form['kids'],
                'priority'           => (int)$form['priority'],
                'status'             => 'waiting',
                'source'             => 'waitlist_page',
                'available_rooms_last' => $availableRoomsLast,
            ], (int)($_SESSION['user_id'] ?? 0));

            save_waitlist_room_groups(
                $pdo,
                $waitlistId,
                (int)$form['property_id'],
                $form['check_in'],
                $form['check_out'],
                $form['room_groups']
            );

            foreach ($form['room_groups'] as $group) {
                if ((int)$group['room_type_id'] > 0) {
                    refresh_waitlist_matches($pdo, (int)$form['property_id'], (int)$group['room_type_id']);
                }
            }

            $pdo->commit();

            header('Location: waitlist.php?id=' . $waitlistId . '&saved=1');
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['cancel_waitlist'])) {
    $cancelId = (int)$_GET['cancel_waitlist'];
    mark_waitlist_cancelled($pdo, $cancelId);
    header('Location: waitlist.php?cancelled=1');
    exit;
}

refresh_waitlist_matches($pdo);
$roomTypes = fetch_room_types_by_property($pdo, (int)$form['property_id']);

$contacts = [];
$selectedAgentId = (int)($form['agent_id'] ?? 0);
if ($selectedAgentId > 0) {
    $stmt = $pdo->prepare("
        SELECT id, firstname, lastname, email, mobile, phone
        FROM consultants
        WHERE agent_id = :agent_id
        ORDER BY firstname, lastname
    ");
    $stmt->execute([':agent_id' => $selectedAgentId]);
    $contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$currentAvailabilityRows = build_grouped_availability_rows(
    $pdo,
    (int)$form['property_id'],
    $form['check_in'],
    $form['check_out'],
    $form['room_groups']
);

$currentCanConfirmAll = !empty($currentAvailabilityRows);
foreach ($currentAvailabilityRows as $row) {
    if (!$row['can_confirm']) {
        $currentCanConfirmAll = false;
        break;
    }
}

$listStmt = $pdo->query("
    SELECT wl.*, p.name AS property_name, rt.title AS room_type_name
    FROM reservation_waitlist wl
    LEFT JOIN properties p ON p.id = wl.property_id
    LEFT JOIN room_types rt ON rt.id = wl.room_type_id
    WHERE wl.status IN ('waiting','notified')
    ORDER BY wl.status DESC, wl.priority DESC, wl.created_at ASC
");
$waitlistRows = $listStmt->fetchAll(PDO::FETCH_ASSOC);

$notifiedRows = array_values(array_filter($waitlistRows, function ($row) {
    return ($row['status'] ?? '') === 'notified';
}));

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

<div class="hero-band waitlist-hero-compact mb-2">
    <div class="row g-2 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-hourglass-split"></i> Reservations</div>
            <div class="hero-title mt-1">Reservation Waitlist</div>
            <div class="hero-subtitle mt-1">Save requests that have no availability now, then confirm them later when rooms open up.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="reservation_form.php" class="btn btn-sm btn-outline-light me-2">
                <i class="bi bi-plus-circle me-2"></i>New Reservation
            </a>
            <a href="/rooms/modules/reservations/reservation_list.php" class="btn btn-sm btn-outline-light">
                <i class="bi bi-arrow-left me-2"></i>Back to List
            </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; ?>

<?php if ($notifiedRows): ?>
    <div class="alert alert-warning py-2 mb-2 d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <strong><?php echo count($notifiedRows); ?> waitlisted booking(s)</strong> can now be confirmed.
        </div>
        <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#notifiedModal">
            <i class="bi bi-bell me-1"></i>View Alerts
        </button>
    </div>
<?php endif; ?>

<div class="row g-2 waitlist-main-row">
    <div class="col-xl-5">
        <form method="post" class="form-section waitlist-compact-section" id="waitlistForm">
            <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">

            <div class="form-section-title">
                <i class="bi bi-person-lines-fill"></i>
                Waitlist Request
            </div>

            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Property</label>
                    <select name="property_id" id="property_id" class="form-select" required>
                        <option value="">Select property</option>
                        <?php foreach ($properties as $p): ?>
                            <option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$form['property_id'] === (int)$p['id'] ? 'selected' : ''; ?>>
                                <?php echo h($p['name']); ?> - <?php echo h($p['code']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Guest Name</label>
                    <input type="text" name="guest_name" class="form-control" value="<?php echo h($form['guest_name']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Agent</label>
                    <select name="agent_id" class="form-select" required>
                        <option value="">Select Agent</option>
                        <?php foreach ($agents as $agent): ?>
                            <?php $agentName = trim(($agent['firstname'] ?? '') . ' ' . ($agent['lastname'] ?? '')); ?>
                            <option value="<?php echo (int)$agent['id']; ?>" <?php echo (int)$form['agent_id'] === (int)$agent['id'] ? 'selected' : ''; ?>>
                                <?php echo h($agentName !== '' ? $agentName : ('Agent #' . $agent['id'])); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Check In</label>
                    <input type="date" name="check_in" id="check_in" class="form-control" value="<?php echo h($form['check_in']); ?>" required>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Check Out</label>
                    <input type="date" name="check_out" id="check_out" class="form-control" value="<?php echo h($form['check_out']); ?>" required>
                </div>

                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0">Room Types Requested</label>
                        <button type="button" class="btn btn-sm btn-outline-primary" id="addRoomRowBtn">
                            <i class="bi bi-plus-circle me-1"></i>Add Room
                        </button>
                    </div>

                    <div id="roomRowsWrap">
                        <?php foreach (($form['room_groups'] ?? []) as $idx => $grp): ?>
                            <div class="border rounded-3 p-3 mb-3 room-row" data-index="<?php echo (int)$idx; ?>">
                                <div class="row g-3 align-items-end">
                                    <div class="col-md-4">
                                        <label class="form-label">Room Type</label>
                                        <select name="room_groups[<?php echo (int)$idx; ?>][room_type_id]" class="form-select room-type-select" required>
                                            <option value="">Select room type</option>
                                            <?php foreach ($roomTypes as $roomType): ?>
                                                <option
                                                    value="<?php echo (int)$roomType['id']; ?>"
                                                    data-higher-occupancy="<?php echo (int)($roomType['higher_occupancy'] ?? 0); ?>"
                                                    <?php echo (int)$grp['room_type_id'] === (int)$roomType['id'] ? 'selected' : ''; ?>
                                                >
                                                    <?php echo h($roomType['title']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

                                    <div class="col-md-2">
                                        <label class="form-label">No. Rooms</label>
                                        <input type="number" min="1" name="room_groups[<?php echo (int)$idx; ?>][qty_rooms]" class="form-control room-qty" value="<?php echo (int)$grp['qty_rooms']; ?>" required>
                                    </div>

                                    <div class="col-md-2">
                                        <label class="form-label">Adults</label>
                                        <input type="number" min="0" name="room_groups[<?php echo (int)$idx; ?>][adults]" class="form-control room-adults" value="<?php echo (int)$grp['adults']; ?>" required>
                                    </div>

                                    <div class="col-md-2">
                                        <label class="form-label">Children</label>
                                        <input type="number" min="0" name="room_groups[<?php echo (int)$idx; ?>][children]" class="form-control room-children" value="<?php echo (int)$grp['children']; ?>">
                                    </div>

                                    <div class="col-md-2 text-md-end">
                                        <button type="button" class="btn btn-outline-danger remove-room-row">
                                            <i class="bi bi-trash me-1"></i>Remove
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Total Rooms</label>
                    <input type="number" class="form-control" id="summary_totalrooms" value="<?php echo (int)$form['totalrooms']; ?>" readonly>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Adults</label>
                    <input type="number" class="form-control" id="summary_adults" value="<?php echo (int)$form['adults']; ?>" readonly>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Children</label>
                    <input type="number" class="form-control" id="summary_children" value="<?php echo (int)$form['kids']; ?>" readonly>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Contact</label>
                    <select name="contact_id" id="contact_id" class="form-select">
                        <option value="">Select contact</option>
                        <?php foreach ($contacts as $contact): ?>
                            <?php
                            $contactName = trim(($contact['firstname'] ?? '') . ' ' . ($contact['lastname'] ?? ''));
                            $contactMeta = [];
                            if (!empty($contact['email'])) $contactMeta[] = $contact['email'];
                            if (!empty($contact['mobile'])) $contactMeta[] = $contact['mobile'];
                            elseif (!empty($contact['phone'])) $contactMeta[] = $contact['phone'];
                            ?>
                            <option value="<?php echo (int)$contact['id']; ?>" <?php echo (int)$form['contact_id'] === (int)$contact['id'] ? 'selected' : ''; ?>>
                                <?php echo h($contactName); ?><?php echo $contactMeta ? ' - ' . h(implode(' / ', $contactMeta)) : ''; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Priority</label>
                    <select name="priority" class="form-select">
                        <option value="0" <?php echo (int)$form['priority'] === 0 ? 'selected' : ''; ?>>Normal</option>
                        <option value="1" <?php echo (int)$form['priority'] === 1 ? 'selected' : ''; ?>>High</option>
                        <option value="2" <?php echo (int)$form['priority'] === 2 ? 'selected' : ''; ?>>Urgent</option>
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Voucher No</label>
                    <input type="text" name="voucher_no" class="form-control" value="<?php echo h($form['voucher_no']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Originating Agent</label>
                    <select name="originating_agent" class="form-select">
                        <option value="">Select Agent</option>
                        <?php foreach ($agents as $agent): ?>
                            <?php $agentName = trim(($agent['firstname'] ?? '') . ' ' . ($agent['lastname'] ?? '')); ?>
                            <option value="<?php echo (int)$agent['id']; ?>" <?php echo (int)$form['originating_agent'] === (int)$agent['id'] ? 'selected' : ''; ?>>
                                <?php echo h($agentName !== '' ? $agentName : ('Agent #' . $agent['id'])); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Occasion</label>
                    <select name="occassion_id" class="form-select">
                        <option value="">Select occasion</option>
                        <?php foreach ($occassions as $occ): ?>
                            <option value="<?php echo (int)$occ['id']; ?>" <?php echo (int)$form['occassion_id'] === (int)$occ['id'] ? 'selected' : ''; ?>>
                                <?php echo h($occ['occassion_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Guest Nationality</label>
                    <select name="nationality_id" class="form-select">
                        <option value="">Select nationality</option>
                        <?php foreach ($nationalities as $nat): ?>
                            <option value="<?php echo (int)$nat['id']; ?>" <?php echo (int)$form['nationality_id'] === (int)$nat['id'] ? 'selected' : ''; ?>>
                                <?php echo h($nat['nationality']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12">
                    <label class="form-label">Reservation Notes</label>
                    <textarea name="reservation_notes" class="form-control" rows="3"><?php echo h($form['reservation_notes']); ?></textarea>
                </div>

                <div class="col-12" style="display:none">
                    <label class="form-label">Internal Memo</label>
                    <textarea name="internal_memo" class="form-control" rows="3"><?php echo h($form['internal_memo']); ?></textarea>
                </div>

                <div class="col-12" style="display:none">
                    <label class="form-label">Reminder Info</label>
                    <textarea name="reminder_info" class="form-control" rows="3"><?php echo h($form['reminder_info']); ?></textarea>
                </div>
            </div>

            <div class="d-grid gap-2 mt-4">
                <button type="submit" name="save_waitlist" value="1" class="btn btn-warning btn-lg">
                    <i class="bi bi-hourglass-split me-2"></i><?php echo (int)$form['id'] > 0 ? 'Update Waitlist' : 'Save to Waitlist'; ?>
                </button>
                <?php if ((int)$form['id'] > 0): ?>
                    <a href="reservation_form.php?waitlist_id=<?php echo (int)$form['id']; ?>" class="btn btn-outline-primary">
                        <i class="bi bi-check2-circle me-2"></i>Try Confirm in Reservation Form
                    </a>
                    <a href="waitlist.php?cancel_waitlist=<?php echo (int)$form['id']; ?>" class="btn btn-outline-danger" onclick="return confirm('Cancel this waitlist entry?');">
                        <i class="bi bi-x-circle me-2"></i>Cancel Waitlist
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <div class="col-xl-7">
        <div class="form-section waitlist-compact-section mb-2">
            <div class="form-section-title">
                <i class="bi bi-info-circle"></i>
                Current Availability Snapshot
            </div>

            <div class="mini-stat mb-3"><span>Total Requested Rooms</span><strong id="snapshot_total_requested"><?php echo (int)$form['totalrooms']; ?></strong></div>
            <div class="mini-stat mb-3"><span>Total Adults</span><strong id="snapshot_total_adults"><?php echo (int)$form['adults']; ?></strong></div>
            <div class="mini-stat mb-3"><span>Total Children</span><strong id="snapshot_total_children"><?php echo (int)$form['kids']; ?></strong></div>

            <div class="table-responsive mb-3">
                <table class="table table-sm align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Room Type</th>
                            <th class="text-center">Req</th>
                            <th class="text-center">Avail</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody id="availabilityGroupBody">
                        <?php if (!$currentAvailabilityRows): ?>
                            <tr><td colspan="4" class="text-muted">Add room type rows to view availability.</td></tr>
                        <?php else: ?>
                            <?php $typeMap = fetch_room_type_map($pdo, (int)$form['property_id']); ?>
                            <?php foreach ($currentAvailabilityRows as $row): ?>
                                <tr>
                                    <td><?php echo h($typeMap[(int)$row['room_type_id']]['title'] ?? ('Type #' . (int)$row['room_type_id'])); ?></td>
                                    <td class="text-center"><?php echo (int)$row['qty_rooms']; ?></td>
                                    <td class="text-center"><?php echo (int)($row['availability']['available_rooms'] ?? 0); ?></td>
                                    <td>
                                        <?php if ($row['can_confirm']): ?>
                                            <span class="badge text-bg-success">Can Confirm</span>
                                        <?php else: ?>
                                            <span class="badge text-bg-warning">Insufficient</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div id="availability_status_wrap">
                <?php if ($currentAvailabilityRows): ?>
                    <?php if ($currentCanConfirmAll): ?>
                        <div class="alert alert-success mb-0" id="availability_status_alert">All requested room types currently have enough availability.</div>
                    <?php else: ?>
                        <div class="alert alert-warning mb-0" id="availability_status_alert">One or more requested room types still do not have enough availability.</div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="alert alert-secondary mb-0" id="availability_status_alert">Select property, add room types, and stay dates to view availability.</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="card panel-card waitlist-active-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="mb-0">Active Waitlist</h5>
                    <small>Waiting requests automatically move to notified when enough rooms become free.</small>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Ref</th>
                                <th>Guest</th>
                                <th>Stay</th>
                                <th>Property / Primary Room Type</th>
                                <th>Req</th>
                                <th>Avail</th>
                                <th>Status</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (!$waitlistRows): ?>
                            <tr>
                                <td colspan="8" class="text-center text-muted py-4">No active waitlist entries.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($waitlistRows as $row): ?>
                                <tr>
                                    <td><?php echo h($row['waitlist_no']); ?></td>
                                    <td>
                                        <div class="fw-semibold"><?php echo h($row['guest_name']); ?></div>
                                        <div class="small text-muted">Priority: <?php echo (int)$row['priority']; ?></div>
                                    </td>
                                    <td>
                                        <?php echo h($row['check_in']); ?><br>
                                        <span class="text-muted small"><?php echo h($row['check_out']); ?></span>
                                    </td>
                                    <td>
                                        <div><?php echo h($row['property_name'] ?? ''); ?></div>
                                        <div class="small text-muted"><?php echo h($row['room_type_name'] ?? ''); ?></div>
                                    </td>
                                    <td><?php echo (int)$row['totalrooms']; ?></td>
                                    <td><?php echo (int)$row['available_rooms_last']; ?></td>
                                    <td>
                                        <?php if (($row['status'] ?? '') === 'notified'): ?>
                                            <span class="badge text-bg-warning">Can Confirm</span>
                                        <?php else: ?>
                                            <span class="badge text-bg-secondary">Waiting</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <a href="waitlist.php?id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-light">Edit</a>
                                        <a href="reservation_form.php?waitlist_id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-primary">Confirm</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if ($notifiedRows): ?>
<div class="modal fade" id="notifiedModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Waitlist Availability Alerts</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <?php foreach ($notifiedRows as $row): ?>
                    <div class="border rounded-3 p-3 mb-3">
                        <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap">
                            <div>
                                <div class="fw-semibold"><?php echo h($row['guest_name']); ?></div>
                                <div class="small text-muted">
                                    <?php echo h($row['property_name'] ?? ''); ?> / <?php echo h($row['room_type_name'] ?? ''); ?>
                                </div>
                                <div class="small text-muted">
                                    <?php echo h($row['check_in']); ?> to <?php echo h($row['check_out']); ?> / Requested <?php echo (int)$row['totalrooms']; ?> room(s)
                                </div>
                            </div>
                            <a href="reservation_form.php?waitlist_id=<?php echo (int)$row['id']; ?>" class="btn btn-primary btn-sm">
                                Confirm Now
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>


<style>
/* Compact waitlist header + operational layout */
.waitlist-hero-compact{padding:12px 16px!important;border-radius:16px;}
.waitlist-hero-compact .hero-title{font-size:1.15rem;line-height:1.1;margin:0!important;}
.waitlist-hero-compact .hero-subtitle{font-size:.78rem;line-height:1.2;}
.waitlist-hero-compact .page-eyebrow{font-size:.7rem;}
.waitlist-hero-compact .btn{padding:.3rem .6rem;font-size:.8rem;border-radius:10px;}
.waitlist-main-row{align-items:flex-start;}
.waitlist-compact-section{padding:12px!important;border-radius:16px!important;}
.waitlist-compact-section .form-section-title{font-size:.92rem;margin-bottom:.65rem!important;}
.waitlist-compact-section .form-label{font-size:.74rem;font-weight:700;margin-bottom:2px;color:#64748b;}
.waitlist-compact-section .form-control,
.waitlist-compact-section .form-select{min-height:32px;padding:.32rem .55rem;font-size:.83rem;border-radius:10px;}
.waitlist-compact-section textarea.form-control{min-height:58px;}
.waitlist-compact-section .row.g-3{--bs-gutter-y:.55rem;--bs-gutter-x:.55rem;}
.waitlist-compact-section .room-row{padding:8px!important;margin-bottom:8px!important;border-radius:12px!important;background:#f8fafc;}
.waitlist-compact-section .room-row .btn{padding:.3rem .55rem;font-size:.8rem;border-radius:10px;}
.waitlist-compact-section .btn-lg{padding:.48rem .75rem;font-size:.92rem;border-radius:12px;}
.waitlist-compact-section .mini-stat{padding:7px 10px!important;border-radius:12px;margin-bottom:6px!important;}
.waitlist-compact-section .alert{padding:.5rem .7rem;font-size:.85rem;}
.waitlist-active-card .card-header{padding:.65rem .85rem!important;}
.waitlist-active-card .card-header h5{font-size:.95rem;}
.waitlist-active-card .card-header small{font-size:.72rem;}
.waitlist-active-card th{position:sticky;top:0;background:#fff;z-index:3;}
.waitlist-active-card .table td,
.waitlist-active-card .table th{font-size:.82rem;padding:.5rem .55rem;}
@media (min-width:1200px){
    .waitlist-active-card .table-responsive{max-height:58vh;overflow:auto;}
    .waitlist-compact-section:first-child{position:sticky;top:0;}
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('waitlistForm');
    if (!form) return;

    const propertyField = form.querySelector('[name="property_id"]');
    const agentField = form.querySelector('[name="agent_id"]');
    const roomRowsWrap = document.getElementById('roomRowsWrap');
    const addRoomRowBtn = document.getElementById('addRoomRowBtn');
    const summaryTotalRooms = document.getElementById('summary_totalrooms');
    const summaryAdults = document.getElementById('summary_adults');
    const summaryChildren = document.getElementById('summary_children');
    const availabilityGroupBody = document.getElementById('availabilityGroupBody');
    const availabilityStatusAlert = document.getElementById('availability_status_alert');
    const snapshotTotalRequested = document.getElementById('snapshot_total_requested');
    const snapshotTotalAdults = document.getElementById('snapshot_total_adults');
    const snapshotTotalChildren = document.getElementById('snapshot_total_children');
    const checkInField = form.querySelector('[name="check_in"]');
    const checkOutField = form.querySelector('[name="check_out"]');

    function resetSelect(selectEl, placeholder) {
        if (!selectEl) return;
        selectEl.innerHTML = '';
        const opt = document.createElement('option');
        opt.value = '';
        opt.textContent = placeholder;
        selectEl.appendChild(opt);
    }

    function addOneDay(dateStr) {
        const d = new Date(dateStr);
        if (isNaN(d.getTime())) return null;
        d.setDate(d.getDate() + 1);
        return d.toISOString().split('T')[0];
    }

    function enforceCheckoutMin() {
        if (!checkInField || !checkOutField || !checkInField.value) return;
        const minCheckout = addOneDay(checkInField.value);
        if (!minCheckout) return;
        checkOutField.setAttribute('min', minCheckout);
        if (!checkOutField.value || checkOutField.value <= checkInField.value) {
            checkOutField.value = minCheckout;
        }
    }

    function getAllSelectedRoomTypes() {
        const selected = [];
        roomRowsWrap.querySelectorAll('.room-type-select').forEach(function (selectEl) {
            const val = (selectEl.value || '').trim();
            if (val !== '') selected.push(val);
        });
        return selected;
    }

    function getAvailableRoomTypeValues() {
        const firstSelect = roomRowsWrap.querySelector('.room-type-select');
        if (!firstSelect) return [];

        return Array.from(firstSelect.options)
            .map(function (opt) { return (opt.value || '').trim(); })
            .filter(function (val) { return val !== ''; });
    }

    function getSelectedRoomTypeValues() {
        const vals = [];
        roomRowsWrap.querySelectorAll('.room-type-select').forEach(function (selectEl) {
            const val = (selectEl.value || '').trim();
            if (val !== '' && !vals.includes(val)) vals.push(val);
        });
        return vals;
    }

    function refreshAddRoomButtonState() {
        if (!addRoomRowBtn) return;
        const allTypes = getAvailableRoomTypeValues();
        const selectedTypes = getSelectedRoomTypeValues();
        const exhausted = allTypes.length > 0 && selectedTypes.length >= allTypes.length;

        addRoomRowBtn.disabled = exhausted;
        if (exhausted) {
            addRoomRowBtn.innerHTML = '<i class="bi bi-check2-circle me-1"></i>All room types added';
            addRoomRowBtn.classList.remove('btn-outline-primary');
            addRoomRowBtn.classList.add('btn-outline-secondary');
        } else {
            addRoomRowBtn.innerHTML = '<i class="bi bi-plus-circle me-1"></i>Add Room';
            addRoomRowBtn.classList.remove('btn-outline-secondary');
            addRoomRowBtn.classList.add('btn-outline-primary');
        }
    }

    function refreshRoomTypeFilters() {
        const allSelected = getAllSelectedRoomTypes();

        roomRowsWrap.querySelectorAll('.room-row').forEach(function (row) {
            const currentSelect = row.querySelector('.room-type-select');
            if (!currentSelect) return;

            const currentValue = (currentSelect.value || '').trim();

            Array.from(currentSelect.options).forEach(function (opt) {
                if (!opt.value) {
                    opt.disabled = false;
                    opt.hidden = false;
                    return;
                }

                const pickedSomewhereElse = allSelected.includes(opt.value) && opt.value !== currentValue;
                opt.disabled = pickedSomewhereElse;
                opt.hidden = pickedSomewhereElse;
            });
        });

        refreshAddRoomButtonState();
    }

    function getSelectedOptionData(selectEl) {
        if (!selectEl) return null;
        const opt = selectEl.options[selectEl.selectedIndex];
        if (!opt) return null;
        return {
            higherOccupancy: parseInt(opt.getAttribute('data-higher-occupancy') || '0', 10) || 0,
            title: opt.textContent || ''
        };
    }

    function updateSummary() {
        let totalRooms = 0;
        let adults = 0;
        let children = 0;

        roomRowsWrap.querySelectorAll('.room-row').forEach(function (row) {
            totalRooms += parseInt((row.querySelector('.room-qty') || {}).value || '0', 10) || 0;
            adults += parseInt((row.querySelector('.room-adults') || {}).value || '0', 10) || 0;
            children += parseInt((row.querySelector('.room-children') || {}).value || '0', 10) || 0;
        });

        if (summaryTotalRooms) summaryTotalRooms.value = totalRooms;
        if (summaryAdults) summaryAdults.value = adults;
        if (summaryChildren) summaryChildren.value = children;

        if (snapshotTotalRequested) snapshotTotalRequested.textContent = totalRooms;
        if (snapshotTotalAdults) snapshotTotalAdults.textContent = adults;
        if (snapshotTotalChildren) snapshotTotalChildren.textContent = children;
    }

    function validateRoomRow(row) {
        const roomType = row.querySelector('.room-type-select');
        const qtyRooms = row.querySelector('.room-qty');
        const adults = row.querySelector('.room-adults');
        const children = row.querySelector('.room-children');
        if (!roomType || !qtyRooms || !adults || !children) return;

        const qty = parseInt(qtyRooms.value || '0', 10) || 0;
        const adultCount = parseInt(adults.value || '0', 10) || 0;
        const childCount = parseInt(children.value || '0', 10) || 0;
        const totalPax = adultCount + childCount;
        const meta = getSelectedOptionData(roomType);
        const higherOccupancy = meta ? meta.higherOccupancy : 0;

        qtyRooms.max = totalPax > 0 ? String(totalPax) : '';
        adults.max = (higherOccupancy > 0 && qty > 0) ? String(higherOccupancy * qty) : '';

        if (qty > totalPax && totalPax > 0) {
            qtyRooms.setCustomValidity('Number of rooms cannot be more than total adults + children.');
        } else {
            qtyRooms.setCustomValidity('');
        }

        if (higherOccupancy > 0 && adultCount > (higherOccupancy * qty)) {
            adults.setCustomValidity('Adults cannot exceed ' + higherOccupancy + ' per room × ' + qty + ' room(s) = ' + (higherOccupancy * qty) + '.');
        } else {
            adults.setCustomValidity('');
        }
    }

    function reindexRoomRows() {
        const rows = roomRowsWrap.querySelectorAll('.room-row');
        rows.forEach(function (row, idx) {
            row.dataset.index = idx;
            const roomType = row.querySelector('.room-type-select');
            const qtyRooms = row.querySelector('.room-qty');
            const adults = row.querySelector('.room-adults');
            const children = row.querySelector('.room-children');

            if (roomType) roomType.name = 'room_groups[' + idx + '][room_type_id]';
            if (qtyRooms) qtyRooms.name = 'room_groups[' + idx + '][qty_rooms]';
            if (adults) adults.name = 'room_groups[' + idx + '][adults]';
            if (children) children.name = 'room_groups[' + idx + '][children]';

            validateRoomRow(row);
        });

        updateSummary();
        refreshRoomTypeFilters();
    }

    function getRoomTypeOptionsHtml() {
        const first = roomRowsWrap.querySelector('.room-type-select');
        return first ? first.innerHTML : '<option value="">Select room type</option>';
    }

    function attachRowEvents(row) {
        const roomType = row.querySelector('.room-type-select');
        const removeBtn = row.querySelector('.remove-room-row');

        if (roomType) {
            roomType.addEventListener('change', function () {
                refreshRoomTypeFilters();
                validateRoomRow(row);
                updateSummary();
                refreshAvailabilitySnapshot();
            });
        }

        row.querySelectorAll('input').forEach(function (input) {
            input.addEventListener('change', function () {
                validateRoomRow(row);
                updateSummary();
                refreshAvailabilitySnapshot();
            });
            input.addEventListener('input', function () {
                validateRoomRow(row);
                updateSummary();
                refreshAvailabilitySnapshot();
            });
        });

        if (removeBtn) {
            removeBtn.addEventListener('click', function () {
                const rows = roomRowsWrap.querySelectorAll('.room-row');
                if (rows.length <= 1) return;
                row.remove();
                reindexRoomRows();
                refreshAvailabilitySnapshot();
            });
        }

        validateRoomRow(row);
    }

    function renderAvailabilitySnapshot(json) {
        if (!json) return;
        const rows = json.rows || [];
        const summary = json.summary || {};
        const canConfirmAll = !!json.can_confirm_all;

        if (snapshotTotalRequested) snapshotTotalRequested.textContent = parseInt(summary.totalrooms || 0, 10) || 0;
        if (snapshotTotalAdults) snapshotTotalAdults.textContent = parseInt(summary.adults || 0, 10) || 0;
        if (snapshotTotalChildren) snapshotTotalChildren.textContent = parseInt(summary.kids || 0, 10) || 0;

        if (availabilityGroupBody) {
            if (!rows.length) {
                availabilityGroupBody.innerHTML = '<tr><td colspan="4" class="text-muted">Add room type rows to view availability.</td></tr>';
            } else {
                const html = rows.map(function (row) {
                    const select = roomRowsWrap.querySelector('.room-row[data-index="' + (row.row_no - 1) + '"] .room-type-select');
                    const meta = getSelectedOptionData(select);
                    const title = meta && meta.title ? meta.title : ('Type #' + row.room_type_id);
                    const available = parseInt((row.availability || {}).available_rooms || 0, 10) || 0;
                    const badge = row.can_confirm
                        ? '<span class="badge text-bg-success">Can Confirm</span>'
                        : '<span class="badge text-bg-warning">Insufficient</span>';
                    return '<tr>' +
                        '<td>' + title + '</td>' +
                        '<td class="text-center">' + row.qty_rooms + '</td>' +
                        '<td class="text-center">' + available + '</td>' +
                        '<td>' + badge + '</td>' +
                    '</tr>';
                }).join('');
                availabilityGroupBody.innerHTML = html;
            }
        }

        if (availabilityStatusAlert) {
            if (!propertyField.value || !checkInField.value || !checkOutField.value) {
                availabilityStatusAlert.className = 'alert alert-secondary mb-0';
                availabilityStatusAlert.textContent = 'Select property, add room types, and stay dates to view availability.';
            } else if (!rows.length) {
                availabilityStatusAlert.className = 'alert alert-secondary mb-0';
                availabilityStatusAlert.textContent = 'Add room type rows to view availability.';
            } else if (canConfirmAll) {
                availabilityStatusAlert.className = 'alert alert-success mb-0';
                availabilityStatusAlert.textContent = 'All requested room types currently have enough availability.';
            } else {
                availabilityStatusAlert.className = 'alert alert-warning mb-0';
                availabilityStatusAlert.textContent = 'One or more requested room types still do not have enough availability.';
            }
        }
    }

    async function refreshAvailabilitySnapshot() {
        if (!propertyField || !checkInField || !checkOutField) return;

        const roomGroups = [];
        roomRowsWrap.querySelectorAll('.room-row').forEach(function (row) {
            roomGroups.push({
                room_type_id: (row.querySelector('.room-type-select') || {}).value || '',
                qty_rooms: (row.querySelector('.room-qty') || {}).value || '1',
                adults: (row.querySelector('.room-adults') || {}).value || '0',
                children: (row.querySelector('.room-children') || {}).value || '0'
            });
        });

        const params = new URLSearchParams({
            ajax: 'availability_grouped',
            property_id: propertyField.value || '',
            check_in: checkInField.value || '',
            check_out: checkOutField.value || '',
            room_groups: JSON.stringify(roomGroups)
        });

        try {
            const resp = await fetch('waitlist.php?' + params.toString(), { credentials: 'same-origin' });
            const json = await resp.json();
            if (json && json.ok) renderAvailabilitySnapshot(json);
        } catch (e) {
            // ignore
        }
    }

    function addRoomRow() {
        const allTypes = getAvailableRoomTypeValues();
        const selectedTypes = getSelectedRoomTypeValues();
        if (allTypes.length > 0 && selectedTypes.length >= allTypes.length) {
            refreshAddRoomButtonState();
            return;
        }

        const idx = roomRowsWrap.querySelectorAll('.room-row').length;
        const div = document.createElement('div');
        div.className = 'border rounded-3 p-3 mb-3 room-row';
        div.dataset.index = idx;
        div.innerHTML = `
            <div class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label class="form-label">Room Type</label>
                    <select name="room_groups[${idx}][room_type_id]" class="form-select room-type-select" required>
                        ${getRoomTypeOptionsHtml()}
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">No. Rooms</label>
                    <input type="number" min="1" name="room_groups[${idx}][qty_rooms]" class="form-control room-qty" value="1" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Adults</label>
                    <input type="number" min="0" name="room_groups[${idx}][adults]" class="form-control room-adults" value="1" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Children</label>
                    <input type="number" min="0" name="room_groups[${idx}][children]" class="form-control room-children" value="0">
                </div>
                <div class="col-md-2 text-md-end">
                    <button type="button" class="btn btn-outline-danger remove-room-row">
                        <i class="bi bi-trash me-1"></i>Remove
                    </button>
                </div>
            </div>
        `;
        roomRowsWrap.appendChild(div);
        attachRowEvents(div);
        reindexRoomRows();
        refreshAvailabilitySnapshot();
        const newSelect = div.querySelector('.room-type-select');
        if (newSelect) newSelect.focus();
    }

    async function loadRoomTypes(propertyId) {
        if (!propertyId) {
            roomRowsWrap.querySelectorAll('.room-type-select').forEach(function (selectEl) {
                resetSelect(selectEl, 'Select room type');
            });
            refreshRoomTypeFilters();
            return;
        }

        try {
            const resp = await fetch('waitlist.php?ajax=room_types&property_id=' + encodeURIComponent(propertyId), { credentials: 'same-origin' });
            const json = await resp.json();
            let html = '<option value="">Select room type</option>';
            (json.rows || []).forEach(function (row) {
                html += '<option value="' + row.id + '" data-higher-occupancy="' + (row.higher_occupancy || 0) + '">' + row.title + '</option>';
            });
            roomRowsWrap.querySelectorAll('.room-type-select').forEach(function (selectEl) {
                const current = selectEl.value;
                selectEl.innerHTML = html;
                if (current) selectEl.value = current;
            });
            reindexRoomRows();
            refreshAvailabilitySnapshot();
        } catch (e) {
            roomRowsWrap.querySelectorAll('.room-type-select').forEach(function (selectEl) {
                resetSelect(selectEl, 'Select room type');
            });
            refreshRoomTypeFilters();
        }
    }

    roomRowsWrap.querySelectorAll('.room-row').forEach(attachRowEvents);

    if (addRoomRowBtn) {
        addRoomRowBtn.addEventListener('click', function () { addRoomRow(); });
    }

    if (propertyField) {
        propertyField.addEventListener('change', async function () {
            await loadRoomTypes(this.value);
        });
    }

    if (agentField) {
        agentField.addEventListener('change', function () {});
    }

    if (checkInField) {
        checkInField.addEventListener('change', function () {
            enforceCheckoutMin();
            refreshAvailabilitySnapshot();
        });
    }

    if (checkOutField) {
        checkOutField.addEventListener('change', function () {
            if (checkInField.value && checkOutField.value && checkOutField.value <= checkInField.value) {
                const minCheckout = addOneDay(checkInField.value);
                if (minCheckout) checkOutField.value = minCheckout;
            }
            refreshAvailabilitySnapshot();
        });
    }

    enforceCheckoutMin();
    updateSummary();
    refreshRoomTypeFilters();
    refreshAddRoomButtonState();
    refreshAvailabilitySnapshot();

    <?php if ($notifiedRows): ?>
    const modalEl = document.getElementById('notifiedModal');
    if (modalEl && window.bootstrap && bootstrap.Modal) {
        const modal = new bootstrap.Modal(modalEl);
        modal.show();
    }
    <?php endif; ?>
});
</script>

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