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

$pageTitle = 'Reservation View';

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('rv_column_exists')) {
    function rv_column_exists(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];
        $key = $table . '.' . $column;

        if (array_key_exists($key, $cache)) {
            return $cache[$key];
        }

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

        return $cache[$key];
    }
}

if (!function_exists('rv_override_label')) {
    function rv_override_label(string $type): string
    {
        $type = strtolower(trim($type));

        switch ($type) {
            case 'total': return 'Full Night Override';
            case 'extra_bed': return 'Extra Bed / Triple';
            case 'sharing': return 'Sharing Rate';
            case 'single': return 'Single Rate';
            case 'child': return 'Child Rate';
            default: return $type !== '' ? ucwords(str_replace('_', ' ', $type)) : 'Manual Override';
        }
    }
}


if (!function_exists('booking_status_badge')) {
    function booking_status_badge($status): string
    {
        switch ((string)$status) {
            case '1':
            case 'confirmed':
                return '<span class="badge text-bg-success">Confirmed</span>';
            case '2':
            case 'pending':
                return '<span class="badge text-bg-warning text-dark">Pending</span>';
            case '3':
            case 'checked_in':
            case 'in_house':
                return '<span class="badge text-bg-primary">In House</span>';
            case '4':
            case 'checked_out':
                return '<span class="badge text-bg-secondary">Checked Out</span>';
            case '0':
            case 'cancelled':
                return '<span class="badge text-bg-danger">Cancelled</span>';
            default:
                return '<span class="badge text-bg-dark">Open</span>';
        }
    }
}

if (!function_exists('payment_badge_meta')) {
    function payment_badge_meta($status): array
    {
        switch ((string)$status) {
            case '2': return ['Paid', 'success'];
            case '1': return ['Part Paid', 'warning'];
            case '0':
            default:  return ['Unpaid', 'danger'];
        }
    }
}

if (!function_exists('folio_type_badge')) {
    function folio_type_badge(string $type): string
    {
        $type = strtolower(trim($type));
        switch ($type) {
            case 'master':
                return '<span class="badge text-bg-dark">Master</span>';
            case 'room':
                return '<span class="badge text-bg-primary">Room</span>';
            case 'guest':
                return '<span class="badge text-bg-info text-dark">Guest</span>';
            default:
                return '<span class="badge text-bg-secondary">' . h(ucfirst($type !== '' ? $type : 'Unknown')) . '</span>';
        }
    }
}

$orderId = (int)($_GET['order_id'] ?? $_GET['id'] ?? 0);
$errors = [];
$order = null;
$roomingRows = [];
$roomMixRows = [];
$bookingFolios = [];
$occupantMap = [];
$folioByRooming = [];
$timeline = [];
$rateOverrideSummary = [
    'override_nights' => 0,
    'calculated_room_total' => 0.0,
    'final_room_total' => 0.0,
    'override_types' => '',
];

$hasRateOverriddenColumn = rv_column_exists($pdo, 'rel_orders_prices', 'rate_overridden');
$hasOriginalTotalColumn = rv_column_exists($pdo, 'rel_orders_prices', 'original_total');
$hasOverrideTotalColumn = rv_column_exists($pdo, 'rel_orders_prices', 'override_total');
$hasOverrideReasonColumn = rv_column_exists($pdo, 'rel_orders_prices', 'override_reason');
$hasOverrideTypeColumn = rv_column_exists($pdo, 'rel_orders_prices', 'override_type');
$hasOverrideValueColumn = rv_column_exists($pdo, 'rel_orders_prices', 'override_value');
$hasExtraBedOverrideColumn = rv_column_exists($pdo, 'rel_orders_prices', 'extra_bed_override');

if ($orderId <= 0) {
    $errors[] = 'Invalid booking selected.';
} else {
    $stmt = $pdo->prepare("\n        SELECT\n            o.*,\n            g.firstname,\n            g.lastname,\n            p.name AS property_name,\n            p.code AS property_code,\n            CONCAT(COALESCE(a.firstname,''), ' ') AS agent_name,\n            CONCAT(COALESCE(c.firstname,''), ' ', COALESCE(c.lastname,'')) AS contact_name,\n            n.nationality AS nationality_name,\n            COALESCE(ex.extras_total, 0) AS extras_total\n        FROM orders o\n        LEFT JOIN guests g ON g.id = o.guest_id\n        LEFT JOIN properties p ON p.id = o.property_id\n        LEFT JOIN agents a ON a.id = o.agent_id\n        LEFT JOIN consultants c ON c.id = o.contact_id\n        LEFT JOIN nationality n ON n.id = o.nationality_id\n        LEFT JOIN (\n            SELECT\n                ft.order_id,\n                SUM(\n                    CASE\n                        WHEN COALESCE(ft.is_voided, 0) = 0\n                         AND (\n                            LOWER(COALESCE(ft.tx_type, '')) IN ('extra', 'extras', 'extra_charge', 'addon', 'add_on', 'transfer', 'restaurant', 'minibar', 'laundry', 'park_fee')\n                            OR LOWER(COALESCE(ft.source_table, '')) IN ('extras', 'order_extras', 'booking_extras', 'reservation_extras', 'order_extra_items', 'manual_extra')\n                         )\n                        THEN (COALESCE(ft.debit, 0) - COALESCE(ft.credit, 0))\n                        ELSE 0\n                    END\n                ) AS extras_total\n            FROM folio_transactions ft\n            GROUP BY ft.order_id\n        ) ex ON ex.order_id = o.id\n        WHERE o.id = :id\n        LIMIT 1\n    ");
    $stmt->execute([':id' => $orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        $errors[] = 'Booking not found.';
    } else {
        $stmt = $pdo->prepare("\n            SELECT\n                rmg.*,\n                rm.room_no AS actual_room_no,\n                rt.title AS room_type_title\n            FROM order_rooming rmg\n            LEFT JOIN rooms rm ON rm.id = rmg.room_id\n            LEFT JOIN room_types rt ON rt.id = rmg.room_type_id\n            WHERE rmg.order_id = :order_id\n            ORDER BY rmg.room_no ASC, rmg.id ASC\n        ");
        $stmt->execute([':order_id' => $orderId]);
        $roomingRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("\n            SELECT\n                rt.title AS room_type_title,\n                COUNT(*) AS qty_rooms,\n                COALESCE(SUM(rmg.adults), 0) AS adults_total,\n                COALESCE(SUM(rmg.children), 0) AS children_total\n            FROM order_rooming rmg\n            INNER JOIN room_types rt ON rt.id = rmg.room_type_id\n            WHERE rmg.order_id = :order_id\n            GROUP BY rmg.room_type_id, rt.title\n            ORDER BY rt.title ASC\n        ");
        $stmt->execute([':order_id' => $orderId]);
        $roomMixRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($roomingRows) {
            $roomingIds = array_map(function ($r) {
                return (int)$r['id'];
            }, $roomingRows);

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

            $stmt = $pdo->prepare("\n                SELECT *\n                FROM order_rooming_guests\n                WHERE rooming_id IN ($placeholders)\n                ORDER BY rooming_id ASC, is_primary DESC, id ASC\n            ");
            $stmt->execute($roomingIds);
            $guestRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($guestRows as $gr) {
                $rid = (int)$gr['rooming_id'];
                if (!isset($occupantMap[$rid])) {
                    $occupantMap[$rid] = [];
                }
                $occupantMap[$rid][] = $gr;
            }
        }

        $stmt = $pdo->prepare("\n            SELECT\n                f.*,\n                r.room_no AS actual_room_no,\n                rt.title AS room_type_title\n            FROM folios f\n            LEFT JOIN rooms r ON r.id = f.room_id\n            LEFT JOIN order_rooming rmg ON rmg.id = f.rooming_id\n            LEFT JOIN room_types rt ON rt.id = rmg.room_type_id\n            WHERE f.order_id = :order_id\n            ORDER BY\n                CASE f.folio_type\n                    WHEN 'master' THEN 1\n                    WHEN 'room' THEN 2\n                    WHEN 'guest' THEN 3\n                    ELSE 9\n                END,\n                f.id ASC\n        ");
        $stmt->execute([':order_id' => $orderId]);
        $bookingFolios = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($bookingFolios as $folio) {
            $rid = (int)($folio['rooming_id'] ?? 0);
            if ($rid > 0) {
                $folioByRooming[$rid] = $folio;
            }
        }
        $timelineSelect = [
            "date",
            "total",
            "rate_plan_title",
            "adults_count",
            "kids_count"
        ];

        $timelineSelect[] = $hasRateOverriddenColumn ? "rate_overridden" : "0 AS rate_overridden";
        $timelineSelect[] = $hasOriginalTotalColumn ? "original_total" : "NULL AS original_total";
        $timelineSelect[] = $hasOverrideTotalColumn ? "override_total" : "NULL AS override_total";
        $timelineSelect[] = $hasOverrideReasonColumn ? "override_reason" : "NULL AS override_reason";
        $timelineSelect[] = $hasOverrideTypeColumn ? "override_type" : "'' AS override_type";
        $timelineSelect[] = $hasOverrideValueColumn ? "override_value" : "NULL AS override_value";
        $timelineSelect[] = $hasExtraBedOverrideColumn ? "extra_bed_override" : "NULL AS extra_bed_override";

        $stmt = $pdo->prepare("
            SELECT " . implode(", ", $timelineSelect) . "
            FROM rel_orders_prices
            WHERE order_id = :order_id
            ORDER BY date ASC
        ");
        $stmt->execute([':order_id' => $orderId]);
        $timeline = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $calculatedRoomTotal = 0.0;
        $finalRoomTotal = 0.0;
        $overrideTypes = [];

        foreach ($timeline as $nightRow) {
            $final = (float)($nightRow['total'] ?? 0);
            $original = $nightRow['original_total'] !== null && $nightRow['original_total'] !== ''
                ? (float)$nightRow['original_total']
                : $final;

            $calculatedRoomTotal += $original;
            $finalRoomTotal += $final;

            if (!empty($nightRow['rate_overridden'])) {
                $rateOverrideSummary['override_nights']++;
                $type = trim((string)($nightRow['override_type'] ?? ''));
                if ($type !== '') {
                    $overrideTypes[$type] = rv_override_label($type);
                }
            }
        }

        $rateOverrideSummary['calculated_room_total'] = round($calculatedRoomTotal, 2);
        $rateOverrideSummary['final_room_total'] = round($finalRoomTotal, 2);
        $rateOverrideSummary['override_types'] = implode(', ', array_values($overrideTypes));

    }
}

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

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-journal-richtext"></i> Reservation Desk</div>
            <div class="hero-title mt-2">Reservation View</div>
            <div class="hero-subtitle mt-2">
                Premium booking dashboard with room mix, room-slot status, occupants, folios, value, and front-desk shortcuts.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <div class="d-inline-flex gap-2 flex-wrap justify-content-lg-end">
                <a href="/rooms/modules/reservations/reservation_list.php" class="btn btn-outline-light">
                    <i class="bi bi-arrow-left me-2"></i>Back to Reservations
                </a>
                <?php if ($order): ?>
                    <a href="/rooms/modules/reservations/reservation_form.php?id=<?php echo (int)$order['id']; ?>" class="btn btn-light">
                        <i class="bi bi-pencil-square me-2"></i>Edit Booking
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">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 ($order): ?>
    <?php
    $guestName = trim(($order['firstname'] ?? '') . ' ' . ($order['lastname'] ?? ''));
    if ($guestName === '') {
        $guestName = 'Guest';
    }

    $agentName = trim((string)($order['agent_name'] ?? ''));
    if ($agentName === '') {
        $agentName = 'Direct';
    }

    $contactName = trim((string)($order['contact_name'] ?? ''));
    if ($contactName === '') {
        $contactName = '-';
    }

    $nationalityName = trim((string)($order['nationality_name'] ?? ''));
    if ($nationalityName === '') {
        $nationalityName = '-';
    }

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

    [$paymentLabel, $paymentClass] = payment_badge_meta($order['payment_status'] ?? 0);

    $nights = (int)($order['nights'] ?? 0);
    if ($nights <= 0 && !empty($order['check_in']) && !empty($order['check_out'])) {
        $inTs = strtotime((string)$order['check_in']);
        $outTs = strtotime((string)$order['check_out']);
        if ($inTs && $outTs && $outTs > $inTs) {
            $nights = (int)(($outTs - $inTs) / 86400);
        }
    }

    $totalFoliosCharges = 0.0;
    $totalFoliosPayments = 0.0;
    $totalFoliosBalance = 0.0;
    foreach ($bookingFolios as $bf) {
        $totalFoliosCharges += (float)($bf['total_charges'] ?? 0);
        $totalFoliosPayments += (float)($bf['total_payments'] ?? 0);
        $totalFoliosBalance += (float)($bf['balance'] ?? 0);
    }

    $hasRateOverride = (int)($rateOverrideSummary['override_nights'] ?? 0) > 0;
    $calculatedRoomTotal = (float)($rateOverrideSummary['calculated_room_total'] ?? ($order['totalamount'] ?? 0));
    $finalRoomTotal = (float)($rateOverrideSummary['final_room_total'] ?? ($order['totalamount'] ?? 0));
    if ($finalRoomTotal <= 0 && !empty($order['totalamount'])) {
        $finalRoomTotal = (float)$order['totalamount'];
    }
    $overrideDifference = $finalRoomTotal - $calculatedRoomTotal;
    $overrideTypesText = trim((string)($rateOverrideSummary['override_types'] ?? ''));

    $checkedInRooms = 0;
    $checkedOutRooms = 0;
    foreach ($roomingRows as $rr) {
        if ((int)($rr['checked_in_status'] ?? 0) === 1) {
            $checkedInRooms++;
        }
        if ((int)($rr['checked_out_status'] ?? 0) === 1) {
            $checkedOutRooms++;
        }
    }

    $pendingRooms = max(0, count($roomingRows) - $checkedInRooms);
    ?>

    <div class="row g-2 mb-3">
        <div class="col-sm-6 col-xl-3">
            <div class="metric-card">
                <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-house-door"></i></div>
                <div>
                    <div class="metric-label">Room Slots</div>
                    <div class="metric-value"><?php echo number_format(count($roomingRows)); ?></div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="metric-card">
                <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check2-square"></i></div>
                <div>
                    <div class="metric-label">Checked In</div>
                    <div class="metric-value"><?php echo number_format($checkedInRooms); ?></div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="metric-card">
                <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-hourglass-split"></i></div>
                <div>
                    <div class="metric-label">Pending Rooms</div>
                    <div class="metric-value"><?php echo number_format($pendingRooms); ?></div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="metric-card">
                <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-cash-stack"></i></div>
                <div>
                    <div class="metric-label">Balance</div>
                    <div class="metric-value"><?php echo money_fmt($totalFoliosBalance); ?></div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-xl-4">
            <div class="form-section compact-section mb-3">
                <div class="form-section-title">
                    <i class="bi bi-journal-text"></i>
                    Booking Summary
                </div>

                <div class="summary-grid">
                <div class="mini-stat mb-3"><span>Booking</span><strong><?php echo h($order['order_no'] ?: ('#' . $order['id'])); ?></strong></div>
                <div class="mini-stat mb-3"><span>Status</span><strong><?php echo booking_status_badge((string)($order['status'] ?? '')); ?></strong></div>
                <div class="mini-stat mb-3"><span>Payment</span><strong><span class="badge text-bg-<?php echo h($paymentClass); ?>"><?php echo h($paymentLabel); ?></span></strong></div>
                <div class="mini-stat mb-3"><span>Property</span><strong><?php echo h($propertyLabel); ?></strong></div>
                <div class="mini-stat mb-3"><span>Lead Guest</span><strong><?php echo h($guestName); ?></strong></div>
                <div class="mini-stat mb-3"><span>Agent</span><strong><?php echo h($agentName); ?></strong></div>
                <div class="mini-stat mb-3"><span>Contact</span><strong><?php echo h($contactName); ?></strong></div>
                <div class="mini-stat mb-3"><span>Nationality</span><strong><?php echo h($nationalityName); ?></strong></div>
                <div class="mini-stat mb-3"><span>Voucher No</span><strong><?php echo h(trim((string)($order['voucher_no'] ?? '')) !== '' ? $order['voucher_no'] : '-'); ?></strong></div>
                <div class="mini-stat mb-3"><span>Stay</span><strong><?php echo h($order['check_in']); ?> to <?php echo h($order['check_out']); ?></strong></div>
                <div class="mini-stat mb-3"><span>Nights</span><strong><?php echo (int)$nights; ?></strong></div>
                <div class="mini-stat mb-3"><span>Room Mix</span><strong><?php echo h(!empty($roomMixRows) ? implode(', ', array_map(function ($r) { return $r['room_type_title'] . ' x ' . $r['qty_rooms']; }, $roomMixRows)) : 'Not set'); ?></strong></div>
                <div class="mini-stat mb-3"><span>Total Rooms</span><strong><?php echo (int)($order['totalrooms'] ?? count($roomingRows)); ?></strong></div>
                <div class="mini-stat mb-3"><span>Adults / Children</span><strong><?php echo (int)($order['adults'] ?? 0); ?>A / <?php echo (int)($order['kids'] ?? 0); ?>C</strong></div>
                <div class="mini-stat mb-3"><span>Accommodation</span><strong><?php echo money_fmt($finalRoomTotal); ?></strong></div>
                <?php if ($hasRateOverride): ?>
                    <div class="mini-stat mb-3 rate-override-stat">
                        <span>Rate Override</span>
                        <strong>
                            <?php echo (int)$rateOverrideSummary['override_nights']; ?> night(s)
                            <?php if ($overrideTypesText !== ''): ?>
                                <small><?php echo h($overrideTypesText); ?></small>
                            <?php endif; ?>
                        </strong>
                    </div>
                    <div class="mini-stat mb-3">
                        <span>Calculated</span>
                        <strong><?php echo money_fmt($calculatedRoomTotal); ?></strong>
                    </div>
                    <div class="mini-stat mb-3">
                        <span>Override Impact</span>
                        <strong><?php echo ($overrideDifference >= 0 ? '+' : ''); ?><?php echo money_fmt($overrideDifference); ?></strong>
                    </div>
                <?php endif; ?>
                <div class="mini-stat mb-3"><span>Extras</span><strong><?php echo money_fmt($order['extras_total'] ?? 0); ?></strong></div>
                <div class="mini-stat mb-0 balance-stat"><span>Grand Balance</span><strong><?php echo money_fmt($totalFoliosBalance); ?></strong></div>
                </div>

                <div class="divider-mini"></div>

                <div class="quick-action-grid">
                    <a href="/rooms/modules/reservations/reservation_form.php?id=<?php echo (int)$order['id']; ?>" class="btn btn-primary btn-sm">
                        <i class="bi bi-pencil-square me-1"></i>Edit
                    </a>
                    <a href="/rooms/modules/reservations/reservation_form.php?id=<?php echo (int)$order['id']; ?>#nightlyPricingPreview" class="btn btn-outline-dark btn-sm">
                        <i class="bi bi-cash-coin me-1"></i>Rates
                    </a>
                    <a href="/rooms/modules/payments/checkin.php?order_id=<?php echo (int)$order['id']; ?>" class="btn btn-outline-success btn-sm">
                        <i class="bi bi-door-open me-1"></i>Check In
                    </a>
                    <a href="/rooms/modules/payments/check_out.php?order_id=<?php echo (int)$order['id']; ?>" class="btn btn-outline-danger btn-sm">
                        <i class="bi bi-door-closed me-1"></i>Check Out
                    </a>
                    <a href="/rooms/modules/payments/payments.php?order_id=<?php echo (int)$order['id']; ?>" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-cash-stack me-1"></i>Payments
                    </a>
                    <a href="/rooms/modules/payments/folio_view.php?order_id=<?php echo (int)$order['id']; ?>" class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-receipt me-1"></i>Folio
                    </a>
                </div>
            </div>

            <?php if ($timeline): ?>
                <div class="form-section compact-section">
                    <div class="form-section-title">
                        <i class="bi bi-calendar3"></i>
                        Nightly Timeline
                    </div>
                    <div class="timeline-list">
                        <?php foreach ($timeline as $night): ?>
                            <?php
                            $nightFinal = (float)($night['total'] ?? 0);
                            $nightOriginal = ($night['original_total'] !== null && $night['original_total'] !== '')
                                ? (float)$night['original_total']
                                : $nightFinal;
                            $nightOverridden = !empty($night['rate_overridden']);
                            $nightOverrideType = trim((string)($night['override_type'] ?? ''));
                            $nightOverrideReason = trim((string)($night['override_reason'] ?? ''));
                            $nightOverrideValue = null;
                            if ($nightOverrideType === 'extra_bed' && $night['extra_bed_override'] !== null && $night['extra_bed_override'] !== '') {
                                $nightOverrideValue = (float)$night['extra_bed_override'];
                            } elseif ($night['override_value'] !== null && $night['override_value'] !== '') {
                                $nightOverrideValue = (float)$night['override_value'];
                            } elseif ($night['override_total'] !== null && $night['override_total'] !== '') {
                                $nightOverrideValue = (float)$night['override_total'];
                            }
                            ?>
                            <div class="timeline-row <?php echo $nightOverridden ? 'timeline-row-override' : ''; ?>">
                                <div>
                                    <strong><?php echo h($night['date']); ?></strong>
                                    <div class="small text-muted"><?php echo h(trim((string)($night['rate_plan_title'] ?? '')) !== '' ? $night['rate_plan_title'] : 'Night charge'); ?></div>
                                    <?php if ($nightOverridden): ?>
                                        <div class="rate-override-pill">
                                            <i class="bi bi-pencil-square"></i>
                                            <?php echo h(rv_override_label($nightOverrideType)); ?>
                                            <?php if ($nightOverrideValue !== null): ?>
                                                • <?php echo money_fmt($nightOverrideValue); ?>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($nightOverrideReason !== ''): ?>
                                            <div class="small text-muted mt-1">Reason: <?php echo h($nightOverrideReason); ?></div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                                <div class="text-end">
                                    <strong><?php echo money_fmt($nightFinal); ?></strong>
                                    <?php if ($nightOverridden && abs($nightOriginal - $nightFinal) > 0.00001): ?>
                                        <div class="small text-muted">
                                            Calc <?php echo money_fmt($nightOriginal); ?> → Final <?php echo money_fmt($nightFinal); ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="small text-muted"><?php echo (int)($night['adults_count'] ?? 0); ?>A / <?php echo (int)($night['kids_count'] ?? 0); ?>C</div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="col-xl-8">
            <div class="card panel-card mb-3">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <div>
                        <h5 class="mb-0">Room Mix Overview</h5>
                        <small>Grouped by requested room type</small>
                    </div>
                </div>
                <div class="card-body p-0">
                    <?php if (!$roomMixRows): ?>
                        <div class="text-center text-muted py-4">No room mix found for this booking.</div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-modern align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>Room Type</th>
                                        <th class="text-end">Rooms</th>
                                        <th class="text-end">Adults</th>
                                        <th class="text-end">Children</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($roomMixRows as $mix): ?>
                                        <tr>
                                            <td><strong><?php echo h($mix['room_type_title']); ?></strong></td>
                                            <td class="text-end"><?php echo (int)$mix['qty_rooms']; ?></td>
                                            <td class="text-end"><?php echo (int)$mix['adults_total']; ?></td>
                                            <td class="text-end"><?php echo (int)$mix['children_total']; ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card panel-card mb-3">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <div>
                        <h5 class="mb-0">Room Slot Dashboard</h5>
                        <small>Expanded room slots, occupants, folios, and front-desk status</small>
                    </div>
                </div>
                <div class="card-body p-0">
                    <?php if (!$roomingRows): ?>
                        <div class="text-center text-muted py-4">No room slots found for this booking.</div>
                    <?php else: ?>
                        <div class="accordion" id="roomSlotAccordion">
                            <?php foreach ($roomingRows as $idx => $room): ?>
                                <?php
                                $rid = (int)$room['id'];
                                $occupants = $occupantMap[$rid] ?? [];
                                $folio = $folioByRooming[$rid] ?? null;
                                $collapseId = 'slotCollapse' . $rid;
                                $headingId = 'slotHeading' . $rid;
                                $isOpen = $idx === 0 ? 'show' : '';
                                $btnState = $idx === 0 ? '' : 'collapsed';
                                $slotStatus = 'Pending';
                                $slotBadge = 'warning text-dark';
                                if ((int)($room['checked_out_status'] ?? 0) === 1) {
                                    $slotStatus = 'Checked Out';
                                    $slotBadge = 'secondary';
                                } elseif ((int)($room['checked_in_status'] ?? 0) === 1) {
                                    $slotStatus = 'Checked In';
                                    $slotBadge = 'success';
                                }
                                ?>
                                <div class="accordion-item mb-3 border rounded-3 overflow-hidden">
                                    <h2 class="accordion-header" id="<?php echo $headingId; ?>">
                                        <button class="accordion-button <?php echo $btnState; ?>" type="button"
                                                data-bs-toggle="collapse"
                                                data-bs-target="#<?php echo $collapseId; ?>"
                                                aria-expanded="<?php echo $idx === 0 ? 'true' : 'false'; ?>"
                                                aria-controls="<?php echo $collapseId; ?>">
                                            <div class="w-100 d-flex justify-content-between align-items-center pe-3 gap-3 flex-wrap">
                                                <div>
                                                    <strong>Room Slot <?php echo (int)$room['room_no']; ?> • <?php echo h($room['room_type_title'] ?: 'Room Type'); ?></strong>
                                                    <div class="small text-muted">
                                                        Assigned Room: <?php echo !empty($room['actual_room_no']) ? h($room['actual_room_no']) : 'Unassigned'; ?>
                                                        • <?php echo (int)($room['adults'] ?? 0); ?>A / <?php echo (int)($room['children'] ?? 0); ?>C
                                                        • <?php echo h($room['check_in']); ?> to <?php echo h($room['check_out']); ?>
                                                    </div>
                                                </div>
                                                <div class="text-end">
                                                    <span class="badge text-bg-<?php echo h($slotBadge); ?>"><?php echo h($slotStatus); ?></span>
                                                </div>
                                            </div>
                                        </button>
                                    </h2>
                                    <div id="<?php echo $collapseId; ?>"
                                         class="accordion-collapse collapse <?php echo $isOpen; ?>"
                                         aria-labelledby="<?php echo $headingId; ?>"
                                         data-bs-parent="#roomSlotAccordion">
                                        <div class="accordion-body">
                                            <div class="row g-3">
                                                <div class="col-lg-5">
                                                    <h6 class="mb-3">Occupants</h6>
                                                    <?php if (!$occupants): ?>
                                                        <div class="text-muted">No occupants captured yet.</div>
                                                    <?php else: ?>
                                                        <div class="table-responsive">
                                                            <table class="table table-modern align-middle mb-0">
                                                                <thead>
                                                                    <tr>
                                                                        <th>Name</th>
                                                                        <th>Primary</th>
                                                                        <th>In</th>
                                                                        <th>Out</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <?php foreach ($occupants as $occ): ?>
                                                                        <tr>
                                                                            <td><?php echo h(trim(($occ['first_name'] ?? '') . ' ' . ($occ['last_name'] ?? ''))); ?></td>
                                                                            <td><?php echo !empty($occ['is_primary']) ? '<span class="badge text-bg-primary">Primary</span>' : '<span class="text-muted">—</span>'; ?></td>
                                                                            <td><?php echo !empty($occ['checked_in_at']) ? h($occ['checked_in_at']) : '—'; ?></td>
                                                                            <td><?php echo !empty($occ['checked_out_at']) ? h($occ['checked_out_at']) : '—'; ?></td>
                                                                        </tr>
                                                                    <?php endforeach; ?>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="col-lg-4">
                                                    <h6 class="mb-3">Room Folio</h6>
                                                    <div class="folio-box">
                                                        <div class="folio-line"><span>Folio</span><strong><?php echo $folio ? h($folio['folio_no']) : 'Not created'; ?></strong></div>
                                                        <div class="folio-line"><span>Type</span><strong><?php echo $folio ? strip_tags(folio_type_badge((string)$folio['folio_type'])) : '—'; ?></strong></div>
                                                        <div class="folio-line"><span>Room Type</span><strong><?php echo h($room['room_type_title'] ?: 'Not set'); ?></strong></div>
                                                        <div class="folio-line"><span>Charges</span><strong><?php echo money_fmt($folio['total_charges'] ?? 0); ?></strong></div>
                                                        <div class="folio-line"><span>Payments</span><strong><?php echo money_fmt($folio['total_payments'] ?? 0); ?></strong></div>
                                                        <div class="folio-line"><span>Balance</span><strong><?php echo money_fmt($folio['balance'] ?? 0); ?></strong></div>
                                                    </div>
                                                </div>
                                                <div class="col-lg-3">
                                                    <h6 class="mb-3">Actions</h6>
                                                    <div class="d-grid gap-2">
                                                        <a href="/rooms/modules/payments/checkin.php?order_id=<?php echo (int)$order['id']; ?>" class="btn btn-outline-success btn-sm">Check In</a>
                                                        <a href="/rooms/modules/payments/check_out.php?order_id=<?php echo (int)$order['id']; ?>" class="btn btn-outline-danger btn-sm">Check Out</a>
                                                        <?php if ($folio): ?>
                                                            <a href="/rooms/modules/payments/folio_view.php?folio_id=<?php echo (int)$folio['id']; ?>" class="btn btn-outline-primary btn-sm">Open Folio</a>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card panel-card">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <div>
                        <h5 class="mb-0">Booking Folios</h5>
                        <small>Master, room, and guest folios for this booking</small>
                    </div>
                </div>
                <div class="card-body p-0">
                    <?php if (!$bookingFolios): ?>
                        <div class="text-center text-muted py-4">No folios found for this booking.</div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-modern align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>Folio</th>
                                        <th>Type</th>
                                        <th>Room / Type</th>
                                        <th class="text-end">Charges</th>
                                        <th class="text-end">Payments</th>
                                        <th class="text-end">Balance</th>
                                        <th class="text-end">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($bookingFolios as $bf): ?>
                                        <tr>
                                            <td>
                                                <div class="data-stack">
                                                    <strong><?php echo h($bf['folio_no']); ?></strong>
                                                    <small><?php echo h($bf['folio_name']); ?></small>
                                                </div>
                                            </td>
                                            <td><?php echo folio_type_badge((string)$bf['folio_type']); ?></td>
                                            <td>
                                                <?php if ((string)$bf['folio_type'] === 'room'): ?>
                                                    <div class="data-stack">
                                                        <strong><?php echo !empty($bf['actual_room_no']) ? 'Room ' . h($bf['actual_room_no']) : 'Room Folio'; ?></strong>
                                                        <small><?php echo h($bf['room_type_title'] ?? ''); ?></small>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted">—</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end"><?php echo money_fmt($bf['total_charges']); ?></td>
                                            <td class="text-end"><?php echo money_fmt($bf['total_payments']); ?></td>
                                            <td class="text-end"><?php echo money_fmt($bf['balance']); ?></td>
                                            <td class="text-end">
                                                <a href="/rooms/modules/payments/folio_view.php?folio_id=<?php echo (int)$bf['id']; ?>" class="btn btn-sm btn-outline-primary">Open</a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3" class="text-end">Totals</th>
                                        <th class="text-end"><?php echo money_fmt($totalFoliosCharges); ?></th>
                                        <th class="text-end"><?php echo money_fmt($totalFoliosPayments); ?></th>
                                        <th class="text-end"><?php echo money_fmt($totalFoliosBalance); ?></th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <style>
        /* Compact dashboard - preserves original left/right layout */
        .hero-band{padding:16px 18px !important;margin-bottom:12px !important;border-radius:20px !important;}
        .hero-band .row{--bs-gutter-y:.75rem;}
        .hero-title{font-size:1.45rem !important;line-height:1.15 !important;}
        .hero-subtitle{font-size:.86rem !important;margin-top:5px !important;}
        .page-eyebrow{font-size:.72rem !important;letter-spacing:.08em;text-transform:uppercase;}

        .metric-card{min-height:auto !important;padding:10px 12px !important;border-radius:16px !important;display:flex;align-items:center;gap:9px;box-shadow:0 6px 18px rgba(15,23,42,.05);}
        .metric-icon{width:34px !important;height:34px !important;min-width:34px !important;border-radius:12px !important;display:flex;align-items:center;justify-content:center;font-size:.95rem !important;}
        .metric-label{font-size:.68rem !important;line-height:1.1 !important;color:#64748b;margin-bottom:1px;text-transform:uppercase;letter-spacing:.04em;}
        .metric-value{font-size:1.12rem !important;line-height:1.1 !important;font-weight:850;color:#0f172a;}

        .compact-section,.form-section{padding:10px 12px !important;border-radius:18px !important;background:#fff;border:1px solid #edf2f7;box-shadow:0 8px 22px rgba(15,23,42,.055);}
        .form-section-title{display:flex;align-items:center;gap:7px;font-size:.84rem !important;font-weight:850;color:#0f172a;margin-bottom:8px !important;padding-bottom:7px;border-bottom:1px solid #edf2f7;}

        .summary-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px;}
        .mini-stat{margin:0 !important;padding:5px 6px !important;border:1px solid #eef2f7 !important;border-radius:10px;background:#fbfdff;display:flex;flex-direction:column;gap:1px;min-width:0;}
        .mini-stat span{font-size:.58rem !important;line-height:1.05;color:#64748b !important;text-transform:uppercase;letter-spacing:.03em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
        .mini-stat strong{font-size:.70rem !important;line-height:1.15;color:#111827;font-weight:850;overflow-wrap:anywhere;}
        .balance-stat{grid-column:1 / -1;background:linear-gradient(135deg,#fff7ed,#ffffff);border-color:#fed7aa !important;}
        .balance-stat strong{font-size:.90rem !important;}

        .rate-override-stat{background:linear-gradient(135deg,#eef2ff,#ffffff) !important;border-color:#c7d2fe !important;}
        .rate-override-stat strong small{display:block;font-size:.58rem;color:#4f46e5;margin-top:2px;}
        .rate-override-pill{display:inline-flex;align-items:center;gap:4px;margin-top:4px;padding:3px 7px;border-radius:999px;background:#eef2ff;color:#3730a3;border:1px solid #c7d2fe;font-size:.64rem;font-weight:850;}
        .timeline-row-override{background:linear-gradient(135deg,#f8faff,#ffffff) !important;border-color:#c7d2fe !important;}

        .divider-mini{height:1px;background:linear-gradient(to right,transparent,#e5eaf0,transparent);margin:6px 0;}
        .quick-action-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px;}
        .quick-action-grid .btn{padding:5px 5px !important;border-radius:9px !important;font-size:.68rem !important;font-weight:750;text-align:center;white-space:nowrap;}

        .timeline-list{display:grid;gap:6px;}
        .timeline-row{display:flex;justify-content:space-between;gap:8px;padding:7px 9px;border:1px solid #edf2f7;border-radius:11px;background:#fbfdff;}
        .timeline-row strong{font-size:.78rem;}
        .timeline-row .small{font-size:.66rem;}

        .panel-card{border-radius:18px !important;overflow:hidden;border:1px solid #edf2f7 !important;box-shadow:0 8px 22px rgba(15,23,42,.055);}
        .panel-card .card-header{padding:10px 12px !important;}
        .panel-card .card-header h5{font-size:.95rem !important;font-weight:850;}
        .panel-card .card-header small{font-size:.7rem !important;color:#64748b;}
        .panel-card .card-body{padding:10px !important;}
        .panel-card .card-body.p-0{padding:0 !important;}

        .accordion-item{margin-bottom:8px !important;border-radius:14px !important;border:1px solid #edf2f7 !important;}
        .accordion-button{padding:9px 11px !important;font-size:.82rem;}
        .accordion-button .small{font-size:.68rem !important;}
        .accordion-body{padding:10px !important;}
        .accordion-body h6{font-size:.78rem;font-weight:850;margin-bottom:7px !important;}

        .table-modern{font-size:.78rem;}
        .table-modern > :not(caption) > * > *{padding:7px 9px !important;}
        .data-stack strong{font-size:.78rem;}
        .data-stack small{font-size:.68rem;}

        .folio-box{border:1px solid #edf2f7;border-radius:13px;padding:8px 10px;background:#fbfdff;}
        .folio-line{display:flex;justify-content:space-between;gap:8px;padding:4px 0;border-bottom:1px dashed #e8eef5;font-size:.74rem;}
        .folio-line:last-child{border-bottom:none;}
        .folio-line span{color:#64748b;}

        @media (min-width:1200px){
            .col-xl-4 > .form-section:first-child{position:sticky;top:78px;z-index:2;}
        }
        @media (max-width:1399.98px){
            .summary-grid{grid-template-columns:repeat(3,minmax(0,1fr));}
            .quick-action-grid{grid-template-columns:repeat(3,minmax(0,1fr));}
        }
        @media (max-width:575.98px){
            .summary-grid{grid-template-columns:repeat(2,minmax(0,1fr));}
            .quick-action-grid{grid-template-columns:1fr 1fr;}
        }
    </style>
<?php endif; ?>

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