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

$pageTitle = 'Restaurant Orders';

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); }
}
if (!function_exists('ro_table_exists')) {
    function ro_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 = :t");
            $stmt->execute([':t' => $table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$table] = false;
        }
    }
}
if (!function_exists('ro_column_exists')) {
    function ro_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 = :t AND column_name = :c");
            $stmt->execute([':t' => $table, ':c' => $column]);
            return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$key] = false;
        }
    }
}
if (!function_exists('ro_status_badge_class')) {
    function ro_status_badge_class(string $status): string {
        $status = strtolower(trim($status));
        switch ($status) {
            case 'open': return 'success';
            case 'sent': return 'warning text-dark';
            case 'preparing': return 'info text-dark';
            case 'served': return 'primary';
            case 'bill_requested': return 'dark';
            case 'closed': return 'secondary';
            case 'void': return 'danger';
            default: return 'light text-dark border';
        }
    }
}
if (!function_exists('ro_payment_badge_class')) {
    function ro_payment_badge_class(string $status): string {
        $status = strtolower(trim($status));
        switch ($status) {
            case 'paid': return 'success';
            case 'part_paid': return 'warning text-dark';
            case 'room_charged': return 'primary';
            case 'void': return 'danger';
            case 'unpaid': return 'light text-dark border';
            default: return 'secondary';
        }
    }
}
if (!function_exists('ro_close_method_label')) {
    function ro_close_method_label(array $o): string {
        $explicit = trim((string)($o['close_method'] ?? ''));
        if ($explicit !== '') return ucwords(str_replace('_', ' ', $explicit));

        $paymentStatus = strtolower(trim((string)($o['payment_status'] ?? '')));
        if ($paymentStatus === 'room_charged') return 'Room / Folio';
        if (!empty($o['linked_folio_id'])) return 'Room / Folio';

        $methods = trim((string)($o['payment_methods'] ?? ''));
        if ($methods !== '') return $methods;

        if ($paymentStatus === 'paid' || $paymentStatus === 'part_paid') return 'Direct Payment';
        if (strtolower((string)($o['status'] ?? '')) === 'closed') return 'Closed';
        return 'Not Closed';
    }
}
if (!function_exists('ro_format_dt')) {
    function ro_format_dt($dt, string $fallback = '-'): string {
        $dt = trim((string)$dt);
        if ($dt === '' || strtotime($dt) === false) return $fallback;
        return date('d-M-Y H:i', strtotime($dt));
    }
}


if (!function_exists('ro_fetch_order_for_bill')) {
    function ro_fetch_order_for_bill(PDO $pdo, int $orderId): ?array {
        if ($orderId <= 0) return null;

        $hasOrderTables  = ro_table_exists($pdo, 'restaurant_order_tables');
        $hasPayments     = ro_table_exists($pdo, 'restaurant_payments');
        $hasCloseMethod  = ro_column_exists($pdo, 'restaurant_orders', 'close_method');

        $selectCloseMethod = $hasCloseMethod ? "ro.close_method" : "NULL AS close_method";

        $joinOrderTables = $hasOrderTables
            ? "LEFT JOIN (
                    SELECT
                        rot.restaurant_order_id,
                        GROUP_CONCAT(DISTINCT rt2.table_no ORDER BY rt2.table_no SEPARATOR ', ') AS merged_tables
                    FROM restaurant_order_tables rot
                    LEFT JOIN restaurant_tables rt2 ON rt2.id = rot.table_id
                    GROUP BY rot.restaurant_order_id
                ) mt ON mt.restaurant_order_id = ro.id"
            : "";

        $selectOrderTables = $hasOrderTables ? "mt.merged_tables" : "NULL AS merged_tables";

        $joinPayments = $hasPayments
            ? "LEFT JOIN (
                    SELECT
                        restaurant_order_id,
                        GROUP_CONCAT(DISTINCT payment_method ORDER BY payment_method SEPARATOR ' + ') AS payment_methods,
                        COALESCE(SUM(amount),0) AS paid_amount
                    FROM restaurant_payments
                    WHERE status = 'posted'
                    GROUP BY restaurant_order_id
                ) rp ON rp.restaurant_order_id = ro.id"
            : "";

        $selectPayments = $hasPayments ? "rp.payment_methods, rp.paid_amount" : "NULL AS payment_methods, 0 AS paid_amount";

        $stmt = $pdo->prepare("
            SELECT
                ro.*,
                $selectCloseMethod,
                rt.table_no,
                rt.table_name,
                $selectOrderTables,
                $selectPayments
            FROM restaurant_orders ro
            LEFT JOIN restaurant_tables rt ON rt.id = ro.table_id
            $joinOrderTables
            $joinPayments
            WHERE ro.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $orderId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }
}

if (!function_exists('ro_fetch_order_items_for_bill')) {
    function ro_fetch_order_items_for_bill(PDO $pdo, int $orderId): array {
        if ($orderId <= 0 || !ro_table_exists($pdo, 'restaurant_order_items')) return [];

        $statusSql = ro_column_exists($pdo, 'restaurant_order_items', 'status')
            ? "AND LOWER(COALESCE(status,'active')) NOT IN ('void','cancelled','canceled','deleted')"
            : "";

        $stmt = $pdo->prepare("
            SELECT *
            FROM restaurant_order_items
            WHERE restaurant_order_id = :id
            $statusSql
            ORDER BY id ASC
        ");
        $stmt->execute([':id' => $orderId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}

if (!function_exists('ro_render_signing_bill')) {
    function ro_render_signing_bill(PDO $pdo, int $orderId): void {
        $order = ro_fetch_order_for_bill($pdo, $orderId);
        if (!$order) {
            http_response_code(404);
            echo 'Bill not found.';
            exit;
        }

        $items = ro_fetch_order_items_for_bill($pdo, $orderId);
        $orderNo = trim((string)($order['order_no'] ?? '')) ?: ('#' . $orderId);
        $guestName = trim((string)($order['guest_name'] ?? '')) ?: 'Guest / Walk-in';
        $tableLabel = trim((string)($order['merged_tables'] ?? ''));
        if ($tableLabel === '') $tableLabel = trim((string)($order['table_no'] ?? ''));
        $tableLabel = $tableLabel !== '' ? ('Table ' . $tableLabel) : 'Walk-in';

        $subtotal = 0.00;
        $taxTotal = 0.00;
        foreach ($items as $item) {
            $subtotal += (float)($item['line_total'] ?? 0);
            $taxTotal += (float)($item['tax_amount'] ?? 0);
        }
        if ($subtotal <= 0) $subtotal = (float)($order['total_amount'] ?? 0);
        if ($taxTotal <= 0 && isset($order['tax_total'])) $taxTotal = (float)$order['tax_total'];

        ?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bill for Signing <?php echo h($orderNo); ?></title>
<style>
    body{font-family:Arial,Helvetica,sans-serif;background:#f3f4f6;margin:0;color:#111827}
    .bill-wrap{width:340px;margin:18px auto;background:#fff;padding:14px 14px 18px;border:1px solid #e5e7eb}
    .center{text-align:center}.muted{color:#6b7280;font-size:11px}.line{border-top:1px dashed #9ca3af;margin:8px 0}
    table{width:100%;border-collapse:collapse;font-size:12px}td{padding:3px 0;vertical-align:top}.right{text-align:right}.total{font-weight:bold;font-size:15px}
    .sign-line{border-bottom:1px solid #111827;height:24px;margin-top:2px}.label{font-size:12px;margin-top:8px}.btns{text-align:center;margin:12px}
    .copy-label{font-size:12px;font-weight:bold;letter-spacing:.08em;margin-top:2px}
    @media print{body{background:#fff}.btns{display:none}.bill-wrap{margin:0;border:0;width:300px}}
</style>
</head>
<body>
<div class="btns">
    <button onclick="window.print()">Print Bill for Signing</button>
    <button onclick="window.close()">Close</button>
</div>
<div class="bill-wrap">
    <div class="center">
        <strong>Pioneers Lodge</strong><br>
        <div class="copy-label">BILL FOR SIGNING</div>
        <span class="muted"><?php echo h(date('Y-m-d H:i:s')); ?></span>
    </div>
    <div class="line"></div>
    <table>
        <tr><td>Order</td><td class="right"><?php echo h($orderNo); ?></td></tr>
        <tr><td>Guest</td><td class="right"><?php echo h($guestName); ?></td></tr>
        <tr><td>Table</td><td class="right"><?php echo h($tableLabel); ?></td></tr>
        <?php if (!empty($order['room_no'])): ?><tr><td>Room</td><td class="right"><?php echo h($order['room_no']); ?></td></tr><?php endif; ?>
        <tr><td>Cashier</td><td class="right"><?php echo h($order['cashier_name'] ?? ''); ?></td></tr>
    </table>
    <div class="line"></div>
    <table>
        <?php foreach ($items as $item): ?>
            <?php
                $name = trim((string)($item['item_name'] ?? 'Item'));
                $qty = (float)($item['qty'] ?? 0);
                $unit = (float)($item['unit_price'] ?? 0);
                $line = (float)($item['line_total'] ?? 0);
            ?>
            <tr>
                <td>
                    <?php echo h($name); ?><br>
                    <span class="muted"><?php echo h(rtrim(rtrim(number_format($qty, 2, '.', ''), '0'), '.')); ?> x <?php echo money_fmt($unit); ?></span>
                </td>
                <td class="right"><?php echo money_fmt($line); ?></td>
            </tr>
        <?php endforeach; ?>
    </table>
    <div class="line"></div>
    <table>
        <tr><td>Total Charges</td><td class="right"><?php echo money_fmt($subtotal); ?></td></tr>
        <tr><td>Tax/VAT incl.</td><td class="right"><?php echo money_fmt($taxTotal); ?></td></tr>
        <tr class="total"><td>Total</td><td class="right"><?php echo money_fmt($subtotal); ?></td></tr>
    </table>
    <div class="line"></div>
    <div class="label">Gratuity</div><div class="sign-line"></div>
    <div class="label">Total</div><div class="sign-line"></div>
    <div class="label">Room/Folio</div><div class="sign-line"></div>
    <div class="label">Customer Name</div><div class="sign-line"></div>
    <div class="label">Signature</div><div class="sign-line"></div>
    <div class="line"></div>
    <div class="center muted">Thank you.</div>
</div>
<script>window.addEventListener('load',function(){setTimeout(function(){window.print();},250);});</script>
</body>
</html><?php
        exit;
    }
}

if (isset($_GET['bill_reprint']) && (int)$_GET['bill_reprint'] === 1) {
    ro_render_signing_bill($pdo, (int)($_GET['id'] ?? 0));
}

$orders = [];
$error = '';

try {
    $hasReservations = ro_table_exists($pdo, 'restaurant_reservations');
    $hasOrderTables  = ro_table_exists($pdo, 'restaurant_order_tables');
    $hasPayments     = ro_table_exists($pdo, 'restaurant_payments');
    $hasCloseMethod  = ro_column_exists($pdo, 'restaurant_orders', 'close_method');

    $selectCloseMethod = $hasCloseMethod ? "ro.close_method" : "NULL AS close_method";

    $joinReservations = $hasReservations
        ? "LEFT JOIN restaurant_reservations rr ON rr.restaurant_order_id = ro.id"
        : "";

    $selectReservation = $hasReservations
        ? "rr.meal_period, rr.reservation_date, rr.reservation_time"
        : "NULL AS meal_period, NULL AS reservation_date, NULL AS reservation_time";

    $joinOrderTables = $hasOrderTables
        ? "LEFT JOIN (
                SELECT
                    rot.restaurant_order_id,
                    GROUP_CONCAT(DISTINCT rt2.table_no ORDER BY rt2.table_no SEPARATOR ', ') AS merged_tables,
                    SUM(COALESCE(rt2.seats,0)) AS merged_capacity,
                    COUNT(DISTINCT rot.table_id) AS merged_count
                FROM restaurant_order_tables rot
                LEFT JOIN restaurant_tables rt2 ON rt2.id = rot.table_id
                GROUP BY rot.restaurant_order_id
            ) mt ON mt.restaurant_order_id = ro.id"
        : "";

    $selectOrderTables = $hasOrderTables
        ? "mt.merged_tables, mt.merged_capacity, mt.merged_count"
        : "NULL AS merged_tables, NULL AS merged_capacity, 0 AS merged_count";

    $joinPayments = $hasPayments
        ? "LEFT JOIN (
                SELECT
                    restaurant_order_id,
                    GROUP_CONCAT(DISTINCT payment_method ORDER BY payment_method SEPARATOR ' + ') AS payment_methods,
                    COALESCE(SUM(amount),0) AS paid_amount
                FROM restaurant_payments
                WHERE status = 'posted'
                GROUP BY restaurant_order_id
            ) rp ON rp.restaurant_order_id = ro.id"
        : "";

    $selectPayments = $hasPayments
        ? "rp.payment_methods, rp.paid_amount"
        : "NULL AS payment_methods, 0 AS paid_amount";

    $sql = "
        SELECT
            ro.*,
            $selectCloseMethod,
            rt.table_no,
            rt.table_name,
            $selectReservation,
            $selectOrderTables,
            $selectPayments
        FROM restaurant_orders ro
        LEFT JOIN restaurant_tables rt ON rt.id = ro.table_id
        $joinReservations
        $joinOrderTables
        $joinPayments
        ORDER BY ro.id DESC
        LIMIT 500
    ";

    $stmt = $pdo->query($sql);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $error = $e->getMessage();
}

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

<div class="hero-band compact-restaurant-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">Restaurant Orders</div>
            <div class="hero-subtitle mt-1">Track order name, tables, meal period, close method, payment and status.</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-outline-light btn-sm" href="cashier.php"><i class="bi bi-cash-register me-1"></i>Cashier</a>
            <a class="btn btn-light btn-sm" href="planner.php"><i class="bi bi-grid-3x3-gap me-1"></i>Planner</a>
        </div>
    </div>
</div>

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

<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">Orders</h5>
            <small class="text-muted">Latest 500 restaurant orders</small>
        </div>
        <div class="orders-legend">
            <span class="badge text-bg-success">Open</span>
            <span class="badge text-bg-warning text-dark">Sent</span>
            <span class="badge text-bg-primary">Served</span>
            <span class="badge text-bg-secondary">Closed</span>
            <span class="badge text-bg-danger">Void</span>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive restaurant-orders-wrap">
            <table class="table table-modern align-middle mb-0">
                <thead>
                <tr>
                    <th>Order</th>
                    <th>Order Name / Client</th>
                    <th>Table(s)</th>
                    <th>Meal / Time</th>
                    <th>Type</th>
                    <th>Status</th>
                    <th>Payment</th>
                    <th>Close Method</th>
                    <th class="text-end">Total</th>
                    <th class="text-end">Paid</th>
                    <th>Created</th>
                    <th class="text-end">Action</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$orders): ?>
                    <tr><td colspan="12" class="text-center text-muted py-4">No restaurant orders found.</td></tr>
                <?php else: foreach ($orders as $o): ?>
                    <?php
                        $status = strtolower(trim((string)($o['status'] ?? '')));
                        $paymentStatus = strtolower(trim((string)($o['payment_status'] ?? '')));
                        $orderNo = trim((string)($o['order_no'] ?? '')) ?: ('#' . (int)$o['id']);
                        $orderName = trim((string)($o['guest_name'] ?? ''));
                        if ($orderName === '') $orderName = ($o['order_type'] ?? '') === 'walkin' ? 'Direct Walk-in' : 'Guest / Table Order';

                        $tableLabel = trim((string)($o['merged_tables'] ?? ''));
                        if ($tableLabel === '') {
                            $tableLabel = trim((string)($o['table_no'] ?? ''));
                        }
                        if ($tableLabel === '') {
                            $tableLabel = ($o['order_type'] ?? '') === 'takeaway' ? 'Takeaway' : 'Walk-in';
                        } else {
                            $tableLabel = 'Table ' . $tableLabel;
                        }
                        $mergedCount = (int)($o['merged_count'] ?? 0);
                        $mergedCapacity = (int)($o['merged_capacity'] ?? 0);

                        $meal = trim((string)($o['meal_period'] ?? ''));
                        $mealLabel = $meal !== '' ? ucwords(str_replace('_', ' ', $meal)) : 'Order';
                        $timeSource = !empty($o['reservation_time']) ? $o['reservation_time'] : ($o['opened_at'] ?? $o['created_at'] ?? '');
                        $timeLabel = $timeSource && strtotime((string)$timeSource) !== false ? date('H:i', strtotime((string)$timeSource)) : '-';

                        $closeMethod = ro_close_method_label($o);
                    ?>
                    <tr>
                        <td>
                            <strong><?php echo h($orderNo); ?></strong>
                            <?php if (!empty($o['room_no']) && ($o['order_type'] ?? '') !== 'walkin'): ?>
                                <div class="small text-muted">Room <?php echo h($o['room_no']); ?></div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <strong><?php echo h($orderName); ?></strong>
                            <?php if (!empty($o['cashier_name'])): ?>
                                <div class="small text-muted"><i class="bi bi-person-badge me-1"></i><?php echo h($o['cashier_name']); ?></div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <strong><?php echo h($tableLabel); ?></strong>
                            <?php if ($mergedCount > 1): ?>
                                <div class="small text-primary fw-bold"><i class="bi bi-union me-1"></i>Merged <?php echo (int)$mergedCount; ?> tables<?php echo $mergedCapacity > 0 ? ' • ' . (int)$mergedCapacity . ' seats' : ''; ?></div>
                            <?php elseif (!empty($o['table_name'])): ?>
                                <div class="small text-muted"><?php echo h($o['table_name']); ?></div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge text-bg-light border text-dark"><?php echo h($mealLabel); ?></span>
                            <div class="small text-muted"><i class="bi bi-clock me-1"></i><?php echo h($timeLabel); ?></div>
                        </td>
                        <td><?php echo h(ucwords(str_replace('_', ' ', (string)($o['order_type'] ?? '')))); ?></td>
                        <td><span class="badge text-bg-<?php echo h(ro_status_badge_class($status)); ?> status-pill"><?php echo h(ucwords(str_replace('_', ' ', $status ?: 'unknown'))); ?></span></td>
                        <td><span class="badge text-bg-<?php echo h(ro_payment_badge_class($paymentStatus)); ?> status-pill"><?php echo h(ucwords(str_replace('_', ' ', $paymentStatus ?: 'unpaid'))); ?></span></td>
                        <td><?php echo h($closeMethod); ?></td>
                        <td class="text-end fw-bold"><?php echo money_fmt($o['total_amount'] ?? 0); ?></td>
                        <td class="text-end"><?php echo money_fmt($o['paid_amount'] ?? 0); ?></td>
                        <td><?php echo h(ro_format_dt($o['created_at'] ?? '')); ?></td>
                        <td class="text-end">
                            <div class="btn-group btn-group-sm" role="group">
                                <a class="btn btn-primary" href="order_view.php?id=<?php echo (int)$o['id']; ?>">Open</a>
                                <a class="btn btn-outline-dark" target="_blank" href="restaurant_orders.php?bill_reprint=1&id=<?php echo (int)$o['id']; ?>">
                                    <i class="bi bi-printer me-1"></i>Bill
                                </a>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.compact-restaurant-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 #e5e7eb}
.restaurant-orders-wrap{max-height:calc(100vh - 230px);overflow:auto}
.table-modern thead th{font-size:.70rem;text-transform:uppercase;letter-spacing:.05em;color:#64748b;background:#f8fafc;position:sticky;top:0;z-index:4;white-space:nowrap}
.table-modern td,.table-modern th{padding:.62rem .75rem;border-bottom:1px solid #eef2f7;font-size:.84rem;vertical-align:middle}
.status-pill{min-width:86px;padding:.42rem .55rem}
.orders-legend{display:flex;gap:5px;flex-wrap:wrap}
.btn-group .btn{white-space:nowrap}
</style>

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