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

$pageTitle = 'Folio View';

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

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

        switch ($type) {
            case 'room_charge':
                return '<span class="badge text-bg-primary">Room Charge</span>';
            case 'payment':
                return '<span class="badge text-bg-success">Payment</span>';
            case 'extra':
            case 'extras':
            case 'restaurant':
            case 'bar':
            case 'spa':
            case 'spar':
            case 'curio':
            case 'minibar':
            case 'laundry':
            case 'transfer':
            case 'park_fee':
                return '<span class="badge text-bg-warning text-dark">' . htmlspecialchars(ucwords(str_replace('_', ' ', $type)), ENT_QUOTES, 'UTF-8') . '</span>';
            case 'adjustment':
                return '<span class="badge text-bg-secondary">Adjustment</span>';
            case 'reversal':
                return '<span class="badge text-bg-danger">Reversal</span>';
            default:
                return '<span class="badge text-bg-light text-dark border">' . htmlspecialchars(ucwords(str_replace('_', ' ', $type)), ENT_QUOTES, 'UTF-8') . '</span>';
        }
    }
}

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

if (!function_exists('season_badge_class')) {
    function season_badge_class(?string $color): string
    {
        $allowed = ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark'];
        $color = strtolower(trim((string)$color));
        return in_array($color, $allowed, true) ? $color : 'secondary';
    }
}

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 Folio</span>';
            case 'room':
                return '<span class="badge text-bg-primary">Room Folio</span>';
            case 'guest':
                return '<span class="badge text-bg-info text-dark">Guest Folio</span>';
            default:
                return '<span class="badge text-bg-secondary">' . htmlspecialchars(ucfirst($type !== '' ? $type : 'Unknown'), ENT_QUOTES, 'UTF-8') . '</span>';
        }
    }
}

if (!function_exists('build_room_mix_from_rows')) {
    function build_room_mix_from_rows(array $rows): string
    {
        $bucket = [];
        foreach ($rows as $row) {
            $title = trim((string)($row['room_type_title'] ?? ''));
            if ($title === '') {
                $title = 'Unspecified';
            }
            if (!isset($bucket[$title])) {
                $bucket[$title] = 0;
            }
            $bucket[$title]++;
        }

        if (!$bucket) {
            return '';
        }

        ksort($bucket, SORT_NATURAL | SORT_FLAG_CASE);
        $parts = [];
        foreach ($bucket as $title => $qty) {
            $parts[] = $title . ' x ' . $qty;
        }
        return implode(', ', $parts);
    }
}


if (!function_exists('folio_view_table_exists')) {
    function folio_view_table_exists(PDO $pdo, string $table): bool
    {
        static $cache = [];
        if (array_key_exists($table, $cache)) return $cache[$table];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table_name");
            $stmt->execute([':table_name' => $table]);
            $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$table] = false;
        }
        return $cache[$table];
    }
}

if (!function_exists('folio_view_tx_category')) {
    function folio_view_tx_category(array $tx): string
    {
        $blob = strtolower(trim(implode(' ', [
            (string)($tx['tx_type'] ?? ''),
            (string)($tx['source_table'] ?? ''),
            (string)($tx['description'] ?? ''),
            (string)($tx['extra_category_name'] ?? ''),
            (string)($tx['extra_item_name'] ?? ''),
            (string)($tx['extra_item_code'] ?? ''),
        ])));

        if (strpos($blob, 'room_charge') !== false || strpos($blob, 'accommodation') !== false || strpos($blob, 'rel_orders_prices') !== false || strpos($blob, 'room charge') !== false) {
            return 'accommodation';
        }
        if (strpos($blob, 'restaurant') !== false || strpos($blob, 'food') !== false) return 'restaurant';
        if (strpos($blob, 'bar') !== false || strpos($blob, 'drink') !== false || strpos($blob, 'beverage') !== false) return 'bar';
        if (strpos($blob, 'spa') !== false || strpos($blob, 'spar') !== false) return 'spa';
        if (strpos($blob, 'curio') !== false || strpos($blob, 'inventory_items') !== false) return 'curio';
        if (strpos($blob, 'payment') !== false || strpos($blob, 'receipt') !== false || strpos($blob, 'deposit') !== false) return 'payment';
        return 'extras';
    }
}

if (!function_exists('folio_view_category_label')) {
    function folio_view_category_label(string $key): string
    {
        switch ($key) {
            case 'accommodation': return 'Accommodation';
            case 'restaurant': return 'Restaurant';
            case 'bar': return 'Bar';
            case 'spa': return 'Spa';
            case 'curio': return 'Curio';
            case 'payment': return 'Payment';
            default: return 'Other Extras';
        }
    }
}

if (!function_exists('folio_view_display_description')) {
    function folio_view_display_description(array $tx): string
    {
        $itemName = trim((string)($tx['extra_item_name'] ?? ''));
        if ($itemName === '') {
            return trim((string)($tx['description'] ?? ''));
        }

        $category = trim((string)($tx['extra_category_name'] ?? ''));
        $code = trim((string)($tx['extra_item_code'] ?? ''));
        $qty = (float)($tx['extra_qty'] ?? 0);
        $unit = (float)($tx['extra_unit_price'] ?? 0);

        $desc = $category !== '' ? ($category . ' - ' . $itemName) : $itemName;
        if ($code !== '') $desc .= ' [' . $code . ']';
        if (abs($qty) > 0.00001) {
            $desc .= ' x ' . number_format($qty, 2);
            if (abs($unit) > 0.00001) $desc .= ' @ ' . money_fmt($unit);
        }
        return $desc;
    }
}

if (!function_exists('folio_view_is_payment_tx')) {
    function folio_view_is_payment_tx(array $tx): bool
    {
        $type = strtolower(trim((string)($tx['tx_type'] ?? '')));
        $source = strtolower(trim((string)($tx['source_table'] ?? '')));
        return in_array($type, ['payment','receipt','deposit','payment_received','folio_payment','guest_payment'], true)
            || in_array($source, ['payments','payment','receipts','receipt'], true);
    }
}

if (!function_exists('folio_view_is_reversal_tx')) {
    function folio_view_is_reversal_tx(array $tx): bool
    {
        $type = strtolower(trim((string)($tx['tx_type'] ?? '')));
        $desc = strtolower(trim((string)($tx['description'] ?? '')));
        return in_array($type, ['payment_void','void_payment','payment_reversal','reversal','refund','payment_refund'], true)
            || strpos($desc, 'void') !== false
            || strpos($desc, 'reversal') !== false
            || strpos($desc, 'refund') !== false;
    }
}

if (!function_exists('folio_view_calculate_totals')) {
    function folio_view_calculate_totals(array $transactions): array
    {
        $charges = 0.0;
        $payments = 0.0;
        $voided = 0.0;
        $breakdown = [
            'accommodation' => 0.0,
            'restaurant' => 0.0,
            'bar' => 0.0,
            'spa' => 0.0,
            'curio' => 0.0,
            'extras' => 0.0,
        ];

        foreach ($transactions as $tx) {
            $debit = (float)($tx['debit'] ?? 0);
            $credit = (float)($tx['credit'] ?? 0);
            $isVoided = (int)($tx['is_voided'] ?? 0) === 1;
            $isPayment = folio_view_is_payment_tx($tx);
            $isReversal = folio_view_is_reversal_tx($tx);

            if ($isVoided) {
                if ($credit > 0) $voided += $credit;
                continue;
            }

            if ($isPayment && $credit > 0) {
                $payments += $credit;
                continue;
            }

            if ($isReversal) {
                if ($debit > 0) {
                    $payments -= $debit;
                    $voided += $debit;
                } elseif ($credit < 0) {
                    $payments += $credit;
                    $voided += abs($credit);
                }
                continue;
            }

            if ($debit > 0) {
                $charges += $debit;
                $category = folio_view_tx_category($tx);
                if ($category === 'payment') $category = 'extras';
                if (!isset($breakdown[$category])) $breakdown[$category] = 0.0;
                $breakdown[$category] += $debit;
            }
        }

        $payments = max(0, $payments);
        return [
            'charges' => round($charges, 2),
            'payments' => round($payments, 2),
            'balance' => round($charges - $payments, 2),
            'voided_payments' => round($voided, 2),
            'breakdown' => array_map(fn($v) => round((float)$v, 2), $breakdown),
        ];
    }
}

if (!function_exists('folio_view_render_breakdown_chips')) {
    function folio_view_render_breakdown_chips(array $breakdown): string
    {
        $classes = [
            'accommodation' => 'primary',
            'restaurant' => 'success',
            'bar' => 'info',
            'spa' => 'warning',
            'curio' => 'dark',
            'extras' => 'secondary',
        ];
        $html = '';
        foreach ($breakdown as $key => $amount) {
            $amount = (float)$amount;
            if (abs($amount) <= 0.00001) continue;
            $class = $classes[$key] ?? 'secondary';
            $html .= '<span class="folio-break-chip text-bg-' . h($class) . '">' . h(folio_view_category_label((string)$key)) . ' ' . money_fmt($amount) . '</span>';
        }
        return $html !== '' ? $html : '<span class="text-muted small">No charge breakdown</span>';
    }
}

$folioId = (int)($_GET['folio_id'] ?? 0);
$orderId = (int)($_GET['order_id'] ?? 0);

$errors = [];
$folio = null;
$order = null;
$transactions = [];
$roomingRows = [];
$bookingFolios = [];
$selectedPropertyId = 0;
$roomMix = '';
$totalAdultsBooked = 0;
$totalChildrenBooked = 0;
$hasExtraChargeItems = folio_view_table_exists($pdo, 'extra_charge_items');

/* ---------------------------------
   Resolve folio
--------------------------------- */
if ($folioId > 0) {
    $stmt = $pdo->prepare("
        SELECT f.*, r.room_no AS actual_room_no, rt.title AS actual_room_type
        FROM folios f
        LEFT JOIN rooms r ON r.id = f.room_id
        LEFT JOIN room_types rt ON rt.id = r.room_type_id
        WHERE f.id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $folioId]);
    $folio = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($folio) {
        $orderId = (int)$folio['order_id'];
        $selectedPropertyId = (int)($folio['property_id'] ?? 0);
    } else {
        $errors[] = 'Selected folio not found.';
    }
}

if (!$folio && $orderId > 0) {
    $stmt = $pdo->prepare("
        SELECT f.*, r.room_no AS actual_room_no, rt.title AS actual_room_type
        FROM folios f
        LEFT JOIN rooms r ON r.id = f.room_id
        LEFT JOIN room_types rt ON rt.id = r.room_type_id
        WHERE f.order_id = :order_id
        ORDER BY
            CASE f.folio_type
                WHEN 'master' THEN 1
                WHEN 'room' THEN 2
                WHEN 'guest' THEN 3
                ELSE 9
            END,
            f.id ASC
        LIMIT 1
    ");
    $stmt->execute([':order_id' => $orderId]);
    $folio = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($folio) {
        $folioId = (int)$folio['id'];
        $selectedPropertyId = (int)($folio['property_id'] ?? 0);
    }
}

if ($orderId > 0) {
    $stmt = $pdo->prepare("
        SELECT
            o.*,
            g.firstname,
            g.lastname,
            rt.title AS header_room_type,
            p.name AS property_name,
            p.code AS property_code,
            COALESCE(a.firstname,'') AS agent_name
        FROM orders o
        LEFT JOIN guests g ON g.id = o.guest_id
        LEFT JOIN room_types rt ON rt.id = o.room_type_id
        LEFT JOIN properties p ON p.id = o.property_id
        LEFT JOIN agents a ON a.id = o.agent_id
        WHERE o.id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        $errors[] = 'Booking not found.';
    } else {
        $selectedPropertyId = (int)($order['property_id'] ?? $selectedPropertyId);

        if ($folio) {
            $extraSelectSql = $hasExtraChargeItems ? "
                , eci.id AS extra_charge_item_id,
                  eci.item_name AS extra_item_name,
                  eci.item_code AS extra_item_code,
                  eci.category_name AS extra_category_name,
                  eci.qty AS extra_qty,
                  eci.unit_price AS extra_unit_price,
                  eci.line_total AS extra_line_total,
                  eci.source_table AS extra_source_table,
                  eci.source_id AS extra_source_id
            " : "
                , NULL AS extra_charge_item_id,
                  NULL AS extra_item_name,
                  NULL AS extra_item_code,
                  NULL AS extra_category_name,
                  NULL AS extra_qty,
                  NULL AS extra_unit_price,
                  NULL AS extra_line_total,
                  NULL AS extra_source_table,
                  NULL AS extra_source_id
            ";
            $extraJoinSql = $hasExtraChargeItems ? " LEFT JOIN extra_charge_items eci ON eci.folio_transaction_id = ft.id " : "";

            $stmt = $pdo->prepare("
                SELECT ft.*
                       {$extraSelectSql}
                FROM folio_transactions ft
                {$extraJoinSql}
                WHERE ft.folio_id = :folio_id
                ORDER BY ft.tx_date ASC, ft.id ASC
            ");
            $stmt->execute([':folio_id' => (int)$folio['id']]);
            $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $currentTotals = folio_view_calculate_totals($transactions);
            $folio['total_charges'] = $currentTotals['charges'];
            $folio['total_payments'] = $currentTotals['payments'];
            $folio['balance'] = $currentTotals['balance'];
            $folio['voided_payments'] = $currentTotals['voided_payments'];
            $folio['charge_breakdown'] = $currentTotals['breakdown'];
        }

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

        foreach ($roomingRows as $rr) {
            $totalAdultsBooked += (int)($rr['adults'] ?? 0);
            $totalChildrenBooked += (int)($rr['children'] ?? 0);
        }

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

        if ($bookingFolios) {
            $folioIds = [];
            foreach ($bookingFolios as $bfRow) {
                $fid = (int)($bfRow['id'] ?? 0);
                if ($fid > 0) $folioIds[$fid] = $fid;
            }

            if ($folioIds) {
                $extraSelectSqlAll = $hasExtraChargeItems ? "
                    , eci.id AS extra_charge_item_id,
                      eci.item_name AS extra_item_name,
                      eci.item_code AS extra_item_code,
                      eci.category_name AS extra_category_name,
                      eci.qty AS extra_qty,
                      eci.unit_price AS extra_unit_price,
                      eci.line_total AS extra_line_total,
                      eci.source_table AS extra_source_table,
                      eci.source_id AS extra_source_id
                " : "
                    , NULL AS extra_charge_item_id,
                      NULL AS extra_item_name,
                      NULL AS extra_item_code,
                      NULL AS extra_category_name,
                      NULL AS extra_qty,
                      NULL AS extra_unit_price,
                      NULL AS extra_line_total,
                      NULL AS extra_source_table,
                      NULL AS extra_source_id
                ";
                $extraJoinSqlAll = $hasExtraChargeItems ? " LEFT JOIN extra_charge_items eci ON eci.folio_transaction_id = ft.id " : "";
                $ph = implode(',', array_fill(0, count($folioIds), '?'));
                $stmtLive = $pdo->prepare("
                    SELECT ft.*
                           {$extraSelectSqlAll}
                    FROM folio_transactions ft
                    {$extraJoinSqlAll}
                    WHERE ft.folio_id IN ($ph)
                    ORDER BY ft.folio_id ASC, ft.tx_date ASC, ft.id ASC
                ");
                $stmtLive->execute(array_values($folioIds));
                $txByFolio = [];
                foreach ($stmtLive->fetchAll(PDO::FETCH_ASSOC) as $txLive) {
                    $txByFolio[(int)($txLive['folio_id'] ?? 0)][] = $txLive;
                }

                foreach ($bookingFolios as &$bfLive) {
                    $fid = (int)($bfLive['id'] ?? 0);
                    $calcLive = folio_view_calculate_totals($txByFolio[$fid] ?? []);
                    $bfLive['total_charges'] = $calcLive['charges'];
                    $bfLive['total_payments'] = $calcLive['payments'];
                    $bfLive['balance'] = $calcLive['balance'];
                    $bfLive['charge_breakdown'] = $calcLive['breakdown'];
                }
                unset($bfLive);
            }
        }
    }
} else {
    $errors[] = 'No folio or booking selected.';
}

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

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-receipt-cutoff"></i> Folios</div>
            <div class="hero-title mt-2">Folio View</div>
            <div class="hero-subtitle mt-2">
                Review a single folio ledger with charges, payments, reversals, and current balance, while still seeing the other folios on the booking.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <?php if ($order): ?>
                <a href="/rooms/modules/payments/payments.php?order_id=<?php echo (int)$order['id']; ?>" class="btn btn-outline-light me-2">
                    <i class="bi bi-arrow-left me-2"></i>Back to Payments
                </a>
            <?php endif; ?>
            <button type="button" class="btn btn-light" onclick="window.print();">
                <i class="bi bi-printer me-2"></i>Print
            </button>
        </div>
    </div>
</div>

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

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

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

    $folioTitle = 'Folio';
    $folioType = strtolower(trim((string)($folio['folio_type'] ?? '')));
    if ($folioType === 'master') {
        $folioTitle = 'Master Folio';
    } elseif ($folioType === 'room') {
        $folioTitle = 'Room Folio';
    } elseif ($folioType === 'guest') {
        $folioTitle = 'Guest Folio';
    }

    $folioSubLabel = trim((string)($folio['folio_name'] ?? ''));
    if ($folioType === 'room') {
        $roomBits = [];
        if (!empty($folio['actual_room_no'])) {
            $roomBits[] = 'Room ' . $folio['actual_room_no'];
        }
        if (!empty($folio['actual_room_type'])) {
            $roomBits[] = $folio['actual_room_type'];
        }
        if ($roomBits) {
            $folioSubLabel .= ($folioSubLabel !== '' ? ' • ' : '') . implode(' • ', $roomBits);
        }
    }

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

    $roomMixDisplay = $roomMix !== '' ? $roomMix : trim((string)($order['header_room_type'] ?? ''));
    if ($roomMixDisplay === '') {
        $roomMixDisplay = 'Not set';
    }

    if ($totalAdultsBooked <= 0 && $totalChildrenBooked <= 0) {
        $totalAdultsBooked = (int)($order['adults'] ?? 0);
        $totalChildrenBooked = (int)($order['kids'] ?? 0);
    }
    ?>
    <div class="card panel-card print-card">
        <div class="card-body p-4 p-lg-5">
            <div class="d-flex justify-content-between align-items-start mb-4 flex-wrap gap-3">
                <div>
                    <h2 class="mb-1"><?php echo h($folioTitle); ?></h2>
                    <div class="text-muted">
                        Folio No: <strong><?php echo h($folio['folio_no']); ?></strong>
                    </div>
                    <div class="mt-2">
                        <?php echo folio_type_badge((string)($folio['folio_type'] ?? '')); ?>
                    </div>
                </div>
                <div class="text-lg-end">
                    <div><strong>Booking:</strong> <?php echo h($order['order_no'] ?: ('#' . $order['id'])); ?></div>
                    <div><strong>Status:</strong> <?php echo h((string)$order['status']); ?></div>
                    <div><strong>Date:</strong> <?php echo h(date('d M Y')); ?></div>
                </div>
            </div>

            <div class="row g-4 mb-4">
                <div class="col-lg-6">
                    <div class="folio-box">
                        <div class="folio-box-title">Guest & Stay</div>
                        <div class="folio-line"><span>Property</span><strong><?php echo h($propertyLabel); ?></strong></div>
                        <div class="folio-line"><span>Guest</span><strong><?php echo h($guestName); ?></strong></div>
                        <div class="folio-line"><span>Agent</span><strong><?php echo h($agentName); ?></strong></div>
                        <div class="folio-line"><span>Check In</span><strong><?php echo h($order['check_in']); ?></strong></div>
                        <div class="folio-line"><span>Check Out</span><strong><?php echo h($order['check_out']); ?></strong></div>
                        <div class="folio-line"><span>Nights</span><strong><?php echo (int)$nights; ?></strong></div>
                        <div class="folio-line"><span>Room Mix</span><strong><?php echo h($roomMixDisplay); ?></strong></div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="folio-box">
                        <div class="folio-box-title">Folio Summary</div>
                        <div class="folio-line"><span>Folio Type</span><strong><?php echo h(ucfirst($folioType !== '' ? $folioType : 'unknown')); ?></strong></div>
                        <div class="folio-line"><span>Folio Name</span><strong><?php echo h($folioSubLabel !== '' ? $folioSubLabel : $folioTitle); ?></strong></div>
                        <div class="folio-line"><span>Booked Rooms / Pax</span><strong><?php echo (int)($order['totalrooms'] ?? max(1, count($roomingRows))); ?> room(s) • <?php echo (int)$totalAdultsBooked; ?>A / <?php echo (int)$totalChildrenBooked; ?>C</strong></div>
                        <div class="folio-line"><span>Total Charges</span><strong><?php echo money_fmt($folio['total_charges']); ?></strong></div>
                        <div class="folio-line"><span>Total Payments</span><strong><?php echo money_fmt($folio['total_payments']); ?></strong></div>
                        <?php if (!empty($folio['voided_payments'])): ?>
                            <div class="folio-line"><span>Voided/Reversed Payments</span><strong><?php echo money_fmt($folio['voided_payments']); ?></strong></div>
                        <?php endif; ?>
                        <div class="folio-line"><span>Folio Balance</span><strong><?php echo money_fmt($folio['balance']); ?></strong></div>
                        <div class="folio-breakdown-wrap mt-3">
                            <?php echo folio_view_render_breakdown_chips($folio['charge_breakdown'] ?? []); ?>
                        </div>
                    </div>
                </div>
            </div>

            <?php if (!empty($bookingFolios)): ?>
                <div class="mb-4 no-print">
                    <h5 class="mb-3">Other Folios on this Booking</h5>
                    <div class="table-responsive">
                        <table class="table table-modern align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>Folio</th>
                                    <th>Type</th>
                                    <th>Room</th>
                                    <th>Room Type</th>
                                    <th class="text-end">Charges</th>
                                    <th class="text-end">Payments</th>
                                    <th class="text-end">Balance</th>
                                    <th>Breakdown</th>
                                    <th class="text-end">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($bookingFolios as $bf): ?>
                                    <?php $isCurrent = (int)$bf['id'] === (int)$folio['id']; ?>
                                    <tr class="<?php echo $isCurrent ? 'table-primary' : ''; ?>">
                                        <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 echo !empty($bf['actual_room_no']) ? h($bf['actual_room_no']) : '-'; ?></td>
                                        <td><?php echo !empty($bf['actual_room_type']) ? h($bf['actual_room_type']) : '-'; ?></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><div class="folio-breakdown-wrap small"><?php echo folio_view_render_breakdown_chips($bf['charge_breakdown'] ?? []); ?></div></td>
                                        <td class="text-end">
                                            <?php if ($isCurrent): ?>
                                                <span class="badge text-bg-primary">Current</span>
                                            <?php else: ?>
                                                <a href="/rooms/modules/payments/folio_view.php?folio_id=<?php echo (int)$bf['id']; ?>"
                                                   class="btn btn-sm btn-outline-primary">
                                                    Open
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>

            <?php if (!empty($roomingRows)): ?>
                <div class="mb-4">
                    <h5 class="mb-3">Rooming Summary</h5>
                    <div class="table-responsive">
                        <table class="table table-modern align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>Room Slot</th>
                                    <th>Requested Type</th>
                                    <th>Adults</th>
                                    <th>Children</th>
                                    <th>Assigned Room</th>
                                    <th>Stay</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($roomingRows as $rr): ?>
                                    <tr>
                                        <td><?php echo (int)$rr['room_no']; ?></td>
                                        <td><?php echo h($rr['room_type_title'] ?? ''); ?></td>
                                        <td><?php echo (int)$rr['adults']; ?></td>
                                        <td><?php echo (int)$rr['children']; ?></td>
                                        <td><?php echo !empty($rr['actual_room_no']) ? h($rr['actual_room_no']) : 'Unassigned'; ?></td>
                                        <td><?php echo h($rr['check_in']); ?> to <?php echo h($rr['check_out']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>

            <div class="mb-4">
                <h5 class="mb-3">Charge Breakdown</h5>
                <div class="folio-breakdown-panel">
                    <?php echo folio_view_render_breakdown_chips($folio['charge_breakdown'] ?? []); ?>
                </div>
            </div>

            <div class="mb-4">
                <h5 class="mb-3">Folio Ledger</h5>
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Category</th>
                                <th>Description</th>
                                <th class="text-end">Debit</th>
                                <th class="text-end">Credit</th>
                                <th class="text-end">Balance</th>
                                <th class="text-end no-print">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$transactions): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4">No folio transactions found.</td>
                                </tr>
                            <?php else: ?>
                                <?php $runningBalance = 0.0; ?>
                                <?php foreach ($transactions as $tx): ?>
                                    <?php $runningBalance += ((float)$tx['debit'] - (float)$tx['credit']); ?>
                                    <?php
                                    $seasonText = '';
                                    $seasonClass = 'secondary';

                                    if ((string)$tx['tx_type'] === 'room_charge') {
                                        if (stripos((string)$tx['description'], 'Peak') !== false) {
                                            $seasonText = 'Peak';
                                            $seasonClass = 'danger';
                                        } elseif (stripos((string)$tx['description'], 'High') !== false) {
                                            $seasonText = 'High';
                                            $seasonClass = 'warning';
                                        } elseif (stripos((string)$tx['description'], 'Mid') !== false) {
                                            $seasonText = 'Mid';
                                            $seasonClass = 'primary';
                                        } elseif (stripos((string)$tx['description'], 'Low') !== false) {
                                            $seasonText = 'Low';
                                            $seasonClass = 'success';
                                        } elseif (stripos((string)$tx['description'], 'Special') !== false) {
                                            $seasonText = 'Special';
                                            $seasonClass = 'dark';
                                        } elseif (stripos((string)$tx['description'], 'Festive') !== false) {
                                            $seasonText = 'Festive';
                                            $seasonClass = 'danger';
                                        } elseif (stripos((string)$tx['description'], 'Promo') !== false) {
                                            $seasonText = 'Promo';
                                            $seasonClass = 'info';
                                        }
                                    }
                                    $txCategoryKey = folio_view_tx_category($tx);
                                    $txDisplayDescription = folio_view_display_description($tx);
                                    ?>
                                    <tr class="<?php echo !empty($tx['is_voided']) ? 'table-secondary' : ''; ?>">
                                        <td><?php echo h($tx['tx_date']); ?></td>
                                        <td><?php echo folio_tx_badge((string)$tx['tx_type']); ?></td>
                                        <td><span class="badge text-bg-light border text-dark"><?php echo h(folio_view_category_label($txCategoryKey)); ?></span></td>
                                        <td>
                                            <?php echo h($txDisplayDescription); ?>
                                            <?php if (!empty($tx['extra_charge_item_id'])): ?>
                                                <div class="small text-muted mt-1">
                                                    Linked item #<?php echo (int)$tx['extra_charge_item_id']; ?>
                                                    <?php if (!empty($tx['extra_source_table'])): ?> • <?php echo h($tx['extra_source_table']); ?> #<?php echo (int)($tx['extra_source_id'] ?? 0); ?><?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                            <?php if ($seasonText !== ''): ?>
                                                <div class="mt-1">
                                                    <span class="badge text-bg-<?php echo h(season_badge_class($seasonClass)); ?>">
                                                        <?php echo h($seasonText); ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                            <?php if (!empty($tx['is_voided'])): ?>
                                                <div class="small text-danger mt-1">
                                                    Voided<?php echo !empty($tx['void_reason']) ? ': ' . h($tx['void_reason']) : ''; ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end"><?php echo money_fmt($tx['debit']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($tx['credit']); ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($runningBalance); ?></td>
                                        <td class="text-end no-print">
                                            <?php if (empty($tx['is_voided']) && (string)$tx['tx_type'] !== 'reversal'): ?>
                                                <form method="post" action="/rooms/modules/payments/reverse_folio_transaction.php" onsubmit="return confirm('Reverse this transaction?');" class="d-inline">
                                                    <input type="hidden" name="tx_id" value="<?php echo (int)$tx['id']; ?>">
                                                    <input type="hidden" name="reason" value="Reversed from folio view">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                                        Reverse
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th colspan="4" class="text-end">Total Charges</th>
                                <th class="text-end"><?php echo money_fmt($folio['total_charges']); ?></th>
                                <th></th>
                                <th></th>
                                <th class="no-print"></th>
                            </tr>
                            <tr>
                                <th colspan="4" class="text-end">Total Payments</th>
                                <th></th>
                                <th class="text-end"><?php echo money_fmt($folio['total_payments']); ?></th>
                                <th></th>
                                <th class="no-print"></th>
                            </tr>
                            <tr>
                                <th colspan="6" class="text-end">Balance</th>
                                <th class="text-end"><?php echo money_fmt($folio['balance']); ?></th>
                                <th class="no-print"></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>

            <div class="folio-signoff">
                <div class="text-muted small">
                    This page shows the ledger for the selected folio only. Other folios on the same booking may carry their own charges, payments, and balances.
                </div>
            </div>
        </div>
    </div>

    <style>
        .folio-box{
            border:1px solid #e9ecef;
            border-radius:16px;
            padding:16px 18px;
            background:#fff;
            height:100%;
        }
        .folio-box-title{
            font-weight:700;
            margin-bottom:12px;
            color:#1f2937;
        }
        .folio-line{
            display:flex;
            justify-content:space-between;
            gap:16px;
            padding:7px 0;
            border-bottom:1px dashed #eef2f7;
        }
        .folio-line:last-child{
            border-bottom:none;
        }
        .folio-line span{
            color:#6b7280;
        }
        .folio-signoff{
            margin-top:24px;
            padding-top:16px;
            border-top:1px solid #e9ecef;
        }
        .folio-breakdown-wrap,
        .folio-breakdown-panel{
            display:flex;
            flex-wrap:wrap;
            gap:.35rem;
            align-items:center;
        }
        .folio-breakdown-panel{
            border:1px solid #eef2f7;
            border-radius:16px;
            background:#fbfdff;
            padding:12px;
        }
        .folio-break-chip{
            display:inline-flex;
            align-items:center;
            border-radius:999px;
            padding:.24rem .55rem;
            font-size:.72rem;
            font-weight:800;
            white-space:nowrap;
        }
        @media print {
            .no-print,
            .sidebar,
            .navbar,
            .btn,
            footer {
                display:none !important;
            }
            .print-card{
                border:none !important;
                box-shadow:none !important;
            }
            body{
                background:#fff !important;
            }
            .container, .container-fluid{
                width:100% !important;
                max-width:100% !important;
                padding:0 !important;
                margin:0 !important;
            }
        }
    </style>
<?php endif; ?>

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