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

$pageTitle = 'Guest Folio Proformas';

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

$orderId = (int)($_GET['order_id'] ?? 0);
$bankId = (int)($_GET['bank'] ?? 0);
$errors = [];
$order = null;
$guestFolios = [];
$bankAccounts = [];

if ($orderId <= 0) {
    $errors[] = 'Missing booking / order id.';
}

try {
    if ($orderId > 0) {
        $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,''), ' ', COALESCE(a.lastname,'')) AS agent_name\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            WHERE o.id = :id\n            LIMIT 1\n        ");
        $stmt->execute([':id' => $orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            $errors[] = 'Booking not found.';
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load booking: ' . $e->getMessage();
}

try {
    if ($order) {
        $stmt = $pdo->prepare("\n            SELECT\n                f.*,\n                r.room_no,\n                rt.title AS room_type,\n                COALESCE(tx.total_charges, 0) AS live_total_charges,\n                COALESCE(tx.total_payments, 0) AS live_total_payments,\n                COALESCE(tx.balance, f.balance, 0) AS live_balance\n            FROM folios f\n            LEFT JOIN rooms r ON r.id = f.room_id\n            LEFT JOIN order_rooming orm ON orm.id = f.rooming_id\n            LEFT JOIN room_types rt ON rt.id = orm.room_type_id\n            LEFT JOIN (\n                SELECT\n                    folio_id,\n                    COALESCE(SUM(CASE\n                        WHEN COALESCE(is_voided,0) = 0\n                             AND LOWER(COALESCE(tx_type,'')) NOT IN (\n                                'payment','receipt','deposit','payment_received',\n                                'folio_payment','guest_payment',\n                                'payment_void','void_payment','payment_reversal',\n                                'reversal','refund','payment_refund'\n                             )\n                             AND LOWER(COALESCE(source_table,'')) NOT IN ('payment','payments','receipt','receipts')\n                        THEN COALESCE(debit,0)\n                        ELSE 0\n                    END), 0) AS total_charges,\n                    GREATEST(0, COALESCE(SUM(CASE\n                        WHEN COALESCE(is_voided,0) = 0\n                             AND (\n                                LOWER(COALESCE(tx_type,'')) IN ('payment','receipt','deposit','payment_received','folio_payment','guest_payment')\n                                OR LOWER(COALESCE(source_table,'')) IN ('payment','payments','receipt','receipts')\n                             )\n                             AND COALESCE(credit,0) > 0\n                        THEN COALESCE(credit,0)\n                        WHEN COALESCE(is_voided,0) = 0\n                             AND (\n                                LOWER(COALESCE(tx_type,'')) IN ('payment_void','void_payment','payment_reversal','reversal','refund','payment_refund')\n                                OR LOWER(COALESCE(description,'')) LIKE '%void%'\n                                OR LOWER(COALESCE(description,'')) LIKE '%reversal%'\n                                OR LOWER(COALESCE(description,'')) LIKE '%refund%'\n                             )\n                             AND COALESCE(debit,0) > 0\n                        THEN -1 * COALESCE(debit,0)\n                        ELSE 0\n                    END), 0)) AS total_payments,\n                    COALESCE(SUM(CASE\n                        WHEN COALESCE(is_voided,0) = 0\n                        THEN COALESCE(debit,0) - COALESCE(credit,0)\n                        ELSE 0\n                    END), 0) AS balance\n                FROM folio_transactions\n                GROUP BY folio_id\n            ) tx ON tx.folio_id = f.id\n            WHERE f.order_id = :order_id\n              AND f.folio_type = 'guest'\n              AND COALESCE(f.status, 1) = 1\n            ORDER BY COALESCE(r.room_no,''), f.occupant_name ASC, f.folio_name ASC, f.id ASC\n        ");
        $stmt->execute([':order_id' => $orderId]);
        $guestFolios = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load guest folios: ' . $e->getMessage();
}

try {
    if ($order) {
        $propertyId = (int)($order['property_id'] ?? 0);
        $sql = "\n            SELECT\n                b.ID,\n                b.AccountName,\n                b.Bank,\n                b.AccountNo,\n                b.Currency,\n                cur.CurrencyCode\n            FROM tblbankdetails b\n            LEFT JOIN tblcurrency cur ON cur.CurrencyID = b.Currency\n            WHERE b.bank_status = 1\n        ";
        $params = [];
        if ($propertyId > 0) {
            $sql .= " AND (b.property_id IS NULL OR b.property_id = 0 OR b.property_id = :property_id) ";
            $params[':property_id'] = $propertyId;
        }
        $sql .= " ORDER BY b.Bank ASC, b.AccountName ASC ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $bankAccounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $bankAccounts = [];
}

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

<div class="hero-band guest-folio-hero mb-3">
    <div class="row g-3 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-person-badge"></i> Folios &amp; Proformas</div>
            <div class="hero-title mt-1">Guest Folio Proformas</div>
            <div class="hero-subtitle mt-1">Select the individual guest folio to print so the correct account is used.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="/rooms/modules/reservations/reservation_list.php" class="btn btn-outline-light btn-sm">
                <i class="bi bi-arrow-left me-1"></i>Reservations
            </a>
            <?php if ($orderId > 0): ?>
                <a href="/rooms/modules/payments/payments.php?order_id=<?php echo (int)$orderId; ?>" class="btn btn-light btn-sm">
                    <i class="bi bi-cash-stack me-1"></i>Payments
                </a>
            <?php endif; ?>
        </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((string)($order['firstname'] ?? '') . ' ' . (string)($order['lastname'] ?? ''));
        if ($guestName === '') $guestName = 'Guest';
        $agentName = trim((string)($order['agent_name'] ?? ''));
        if ($agentName === '') $agentName = 'Direct';
        $propertyLabel = trim((string)($order['property_name'] ?? ''));
        if (!empty($order['property_code'])) $propertyLabel .= ($propertyLabel !== '' ? ' (' . $order['property_code'] . ')' : $order['property_code']);
    ?>

    <div class="card panel-card mb-3">
        <div class="card-body py-3">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <div class="small text-muted fw-bold">Booking</div>
                    <div class="fw-bold"><?php echo h($order['order_no'] ?: ('#' . $orderId)); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="small text-muted fw-bold">Main Guest</div>
                    <div class="fw-bold"><?php echo h($guestName); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="small text-muted fw-bold">Property</div>
                    <div class="fw-bold"><?php echo h($propertyLabel !== '' ? $propertyLabel : 'Not set'); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="small text-muted fw-bold">Agent</div>
                    <div class="fw-bold"><?php echo h($agentName); ?></div>
                </div>
            </div>
        </div>
    </div>

    <div class="card panel-card mb-3">
        <div class="card-body py-3">
            <form method="get" class="row g-3 align-items-end">
                <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">
                <div class="col-md-8">
                    <label class="form-label">Bank Account on Proforma</label>
                    <select name="bank" class="form-select">
                        <option value="0">Use default bank account</option>
                        <?php foreach ($bankAccounts as $bank): ?>
                            <option value="<?php echo (int)$bank['ID']; ?>" <?php echo $bankId === (int)$bank['ID'] ? 'selected' : ''; ?>>
                                <?php echo h($bank['Bank']); ?> - <?php echo h($bank['AccountName']); ?> <?php echo !empty($bank['CurrencyCode']) ? '(' . h($bank['CurrencyCode']) . ')' : ''; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 d-grid">
                    <button class="btn btn-primary"><i class="bi bi-check2-circle me-1"></i>Apply Bank</button>
                </div>
            </form>
        </div>
    </div>

    <?php if (!$guestFolios): ?>
        <div class="alert alert-warning">
            <strong>No guest folios found.</strong><br>
            Guest folios are created from check-in occupants. Open check-in for this booking and save individual occupants first.
        </div>
    <?php else: ?>
        <div class="row g-3">
            <?php foreach ($guestFolios as $folio): ?>
                <?php
                    $occupant = trim((string)($folio['occupant_name'] ?? ''));
                    if ($occupant === '') $occupant = trim((string)($folio['folio_name'] ?? 'Guest Folio'));
                    if ($occupant === '') $occupant = 'Guest Folio #' . (int)$folio['id'];
                    $roomNo = trim((string)($folio['room_no'] ?? ''));
                    $roomType = trim((string)($folio['room_type'] ?? ''));
                    $printUrl = '/rooms/modules/payments/proforma_guest_folio.php?' . http_build_query([
                        'order_id' => $orderId,
                        'folio_id' => (int)$folio['id'],
                    ] + ($bankId > 0 ? ['bank' => $bankId] : []));
                ?>
                <div class="col-md-6 col-xl-4">
                    <div class="card panel-card h-100 guest-folio-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start gap-2 mb-2">
                                <div>
                                    <div class="small text-muted fw-bold">Guest Folio</div>
                                    <h5 class="mb-1"><?php echo h($occupant); ?></h5>
                                    <div class="small text-muted"><?php echo h($folio['folio_no'] ?? ''); ?></div>
                                </div>
                                <span class="badge text-bg-success">Guest</span>
                            </div>

                            <div class="mini-stat mb-2"><span>Room</span><strong><?php echo h($roomNo !== '' ? $roomNo : 'N/A'); ?></strong></div>
                            <div class="mini-stat mb-2"><span>Room Type</span><strong><?php echo h($roomType !== '' ? $roomType : 'N/A'); ?></strong></div>
                            <div class="mini-stat mb-2"><span>Charges</span><strong><?php echo money_fmt($folio['live_total_charges'] ?? $folio['total_charges'] ?? 0); ?></strong></div>
                            <div class="mini-stat mb-2"><span>Payments</span><strong><?php echo money_fmt($folio['live_total_payments'] ?? $folio['total_payments'] ?? 0); ?></strong></div>
                            <div class="mini-stat mb-3"><span>Balance</span><strong><?php echo money_fmt($folio['live_balance'] ?? $folio['balance'] ?? 0); ?></strong></div>

                            <a href="<?php echo h($printUrl); ?>" target="_blank" class="btn btn-primary w-100">
                                <i class="bi bi-file-earmark-pdf me-1"></i>Print Guest Folio Proforma
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
<?php endif; ?>

<style>
.guest-folio-hero{padding:.85rem 1.1rem!important;border-radius:18px!important}
.guest-folio-hero .hero-title{font-size:1.35rem!important;line-height:1.1!important}
.guest-folio-hero .hero-subtitle{font-size:.82rem!important}
.guest-folio-card{border-radius:18px!important;overflow:hidden}
.guest-folio-card .mini-stat{display:flex;justify-content:space-between;gap:10px;border-bottom:1px solid #eef2f7;padding-bottom:.45rem}
.guest-folio-card .mini-stat span{color:#64748b;font-size:.75rem;font-weight:700}
.guest-folio-card .mini-stat strong{font-size:.82rem;text-align:right}
</style>

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