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

$pageTitle = 'Restaurant Order';

if (!function_exists('h')) {
    function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($v): string { return number_format((float)$v, 2); }
}

$id = (int)($_GET['id'] ?? 0);
$order = null;
$items = [];
$payments = [];
$error = '';

try {
    if ($id <= 0) {
        throw new RuntimeException('Invalid restaurant order selected.');
    }

    $stmt = $pdo->prepare("\n        SELECT\n            ro.*,\n            rt.table_no,\n            rt.table_name,\n            ra.area_name\n        FROM restaurant_orders ro\n        LEFT JOIN restaurant_tables rt ON rt.id = ro.table_id\n        LEFT JOIN restaurant_areas ra ON ra.id = ro.area_id\n        WHERE ro.id = :id\n        LIMIT 1\n    ");
    $stmt->execute([':id' => $id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($order) {
        $it = $pdo->prepare("\n            SELECT *\n            FROM restaurant_order_items\n            WHERE restaurant_order_id = :id\n            ORDER BY id ASC\n        ");
        $it->execute([':id' => $id]);
        $items = $it->fetchAll(PDO::FETCH_ASSOC);

        try {
            $pay = $pdo->prepare("\n                SELECT *\n                FROM restaurant_payments\n                WHERE restaurant_order_id = :id\n                ORDER BY payment_date ASC, id ASC\n            ");
            $pay->execute([':id' => $id]);
            $payments = $pay->fetchAll(PDO::FETCH_ASSOC);
        } catch (Throwable $ignored) {
            $payments = [];
        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$totalPaid = 0.0;
foreach ($payments as $payment) {
    if (($payment['status'] ?? 'posted') === 'posted') {
        $totalPaid += (float)($payment['amount'] ?? 0);
    }
}
$balance = max(0, (float)($order['total_amount'] ?? 0) - $totalPaid);

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

<div class="hero-band restaurant-order-hero">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <div class="page-eyebrow text-white-50">
                <i class="bi bi-receipt"></i> Restaurant
            </div>
            <div class="hero-title mt-1">
                Order <?php echo h($order['order_no'] ?? ('#' . $id)); ?>
            </div>
            <?php if ($order): ?>
                <div class="hero-subtitle mt-1">
                    <?php echo h(($order['table_no'] ?? '') ? ('Table ' . $order['table_no']) : 'Walk-in / Takeaway'); ?>
                    <?php if (!empty($order['area_name'])): ?> • <?php echo h($order['area_name']); ?><?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-outline-light btn-sm" href="restaurant_planner.php">
                <i class="bi bi-grid-3x3-gap me-1"></i>Planner
            </a>
            <a class="btn btn-light btn-sm" href="orders.php">
                <i class="bi bi-arrow-left me-1"></i>Back to Orders
            </a>
        </div>
    </div>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?php echo h($error); ?></div>
<?php endif; ?>

<?php if (!$order): ?>
    <div class="alert alert-warning">Order not found.</div>
<?php else: ?>
    <div class="row g-3">
        <div class="col-xl-4">
            <div class="card panel-card mb-3">
                <div class="card-header">
                    <h5 class="mb-0">Order Summary</h5>
                </div>
                <div class="card-body">
                    <div class="mini-stat mb-2">
                        <span>Table</span>
                        <strong>
                            <?php
                                $tableLabel = trim((string)($order['table_no'] ?? ''));
                                if ($tableLabel !== '') {
                                    echo h('Table ' . $tableLabel . (!empty($order['table_name']) ? ' - ' . $order['table_name'] : ''));
                                } else {
                                    echo h($order['guest_name'] ?: 'Walk-in / Takeaway');
                                }
                            ?>
                        </strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Status</span>
                        <strong><?php echo h(ucwords(str_replace('_', ' ', (string)$order['status']))); ?></strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Payment</span>
                        <strong><?php echo h(ucwords(str_replace('_', ' ', (string)$order['payment_status']))); ?></strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Subtotal</span>
                        <strong><?php echo money_fmt($order['subtotal'] ?? 0); ?></strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Tax</span>
                        <strong><?php echo money_fmt($order['tax_total'] ?? 0); ?></strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Total</span>
                        <strong><?php echo money_fmt($order['total_amount'] ?? 0); ?></strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Paid</span>
                        <strong><?php echo money_fmt($totalPaid); ?></strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Balance</span>
                        <strong><?php echo money_fmt($balance); ?></strong>
                    </div>
                    <div class="mini-stat mb-2">
                        <span>Created</span>
                        <strong><?php echo h($order['created_at'] ?? $order['opened_at'] ?? ''); ?></strong>
                    </div>

                    <?php if (!empty($order['linked_order_id'])): ?>
                        <div class="alert alert-success mt-3 small mb-0">
                            Posted to lodge booking #<?php echo (int)$order['linked_order_id']; ?>
                            <?php if (!empty($order['linked_folio_id'])): ?>
                                / folio #<?php echo (int)$order['linked_folio_id']; ?>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info mt-3 small mb-0">
                            Close/payment posting is handled from the Restaurant Planner order panel.
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($payments): ?>
                <div class="card panel-card">
                    <div class="card-header">
                        <h5 class="mb-0">Payments</h5>
                    </div>
                    <div class="card-body p-0">
                        <table class="table table-modern mb-0">
                            <thead>
                            <tr>
                                <th>Date</th>
                                <th>Method</th>
                                <th class="text-end">Amount</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($payments as $payment): ?>
                                <tr class="<?php echo ($payment['status'] ?? '') === 'void' ? 'text-muted text-decoration-line-through' : ''; ?>">
                                    <td><?php echo h($payment['payment_date'] ?? $payment['created_at'] ?? ''); ?></td>
                                    <td>
                                        <?php echo h($payment['payment_method'] ?? ''); ?>
                                        <?php if (!empty($payment['reference_no'])): ?>
                                            <div class="small text-muted"><?php echo h($payment['reference_no']); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end fw-bold"><?php echo money_fmt($payment['amount'] ?? 0); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="col-xl-8">
            <div class="card panel-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Items</h5>
                    <span class="badge text-bg-light border text-dark"><?php echo count($items); ?> line(s)</span>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-modern mb-0">
                            <thead>
                            <tr>
                                <th>Item</th>
                                <th>Station</th>
                                <th>Status</th>
                                <th class="text-end">Qty</th>
                                <th class="text-end">Price</th>
                                <th class="text-end">Tax</th>
                                <th class="text-end">Total</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (!$items): ?>
                                <tr>
                                    <td colspan="7" class="text-center text-muted py-4">No items on this order.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($items as $i): ?>
                                    <?php $isVoid = (($i['status'] ?? '') === 'void'); ?>
                                    <tr class="<?php echo $isVoid ? 'text-muted text-decoration-line-through' : ''; ?>">
                                        <td>
                                            <strong><?php echo h($i['item_name']); ?></strong>
                                            <?php if (!empty($i['notes'])): ?>
                                                <div class="small text-muted"><?php echo h($i['notes']); ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo h($i['printer_role'] ?: '-'); ?></td>
                                        <td>
                                            <span class="badge text-bg-light border text-dark">
                                                <?php echo h(($i['print_status'] ?? '-') . ' / ' . ($i['status'] ?? '-')); ?>
                                            </span>
                                        </td>
                                        <td class="text-end"><?php echo money_fmt($i['qty'] ?? 0); ?></td>
                                        <td class="text-end"><?php echo money_fmt($i['unit_price'] ?? 0); ?></td>
                                        <td class="text-end"><?php echo money_fmt($i['tax_amount'] ?? 0); ?></td>
                                        <td class="text-end fw-bold">
                                            <?php echo money_fmt((float)($i['line_total'] ?? 0) + (float)($i['tax_amount'] ?? 0)); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<style>
.restaurant-order-hero{padding:12px 16px!important;margin-bottom:10px!important}
.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07);border:1px solid #eef2f7}
.table-modern thead th{background:#f8fafc;font-size:.72rem;text-transform:uppercase;color:#64748b;white-space:nowrap}
.table-modern td,.table-modern th{padding:.62rem .75rem;border-bottom:1px solid #eef2f7;vertical-align:middle}
.mini-stat{display:flex;justify-content:space-between;gap:12px;border-bottom:1px solid #eef2f7;padding:8px 0}
.mini-stat span{color:#64748b;font-weight:700}
.mini-stat strong{text-align:right;color:#0f172a}
</style>

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