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

$pageTitle = 'Restaurant Orders';

// Kitchen/thermal PrintNode printer for signing bills. Change this ID if your kitchen printer is different.
if (!defined('RO_KITCHEN_THERMAL_PRINTER_ID')) {
    define('RO_KITCHEN_THERMAL_PRINTER_ID', 75588291);
}

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_signing_bill_printnode_flash')) {
    function ro_signing_bill_printnode_flash(string $type, string $message): void {
        if (session_status() === PHP_SESSION_NONE) @session_start();
        $_SESSION['restaurant_orders_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('ro_signing_bill_get_flash')) {
    function ro_signing_bill_get_flash(): array {
        if (session_status() === PHP_SESSION_NONE) @session_start();
        $flash = $_SESSION['restaurant_orders_flash'] ?? [];
        unset($_SESSION['restaurant_orders_flash']);
        return is_array($flash) ? $flash : [];
    }
}
if (!function_exists('ro_thermal_line')) {
    function ro_thermal_line(string $left, string $right = '', int $width = 42): string {
        $left = trim(preg_replace('/\s+/', ' ', $left));
        $right = trim(preg_replace('/\s+/', ' ', $right));
        if ($right === '') {
            return mb_substr($left, 0, $width) . "\n";
        }
        $space = $width - mb_strlen($left) - mb_strlen($right);
        if ($space < 1) {
            $left = mb_substr($left, 0, max(1, $width - mb_strlen($right) - 1));
            $space = $width - mb_strlen($left) - mb_strlen($right);
        }
        return $left . str_repeat(' ', max(1, $space)) . $right . "\n";
    }
}
if (!function_exists('ro_thermal_hr')) {
    function ro_thermal_hr(int $width = 42): string { return str_repeat('-', $width) . "\n"; }
}
if (!function_exists('ro_printnode_send_raw')) {
    function ro_printnode_send_raw(int $printerId, string $rawBytes, string $title): array {
        $helper = __DIR__ . '/../payments/printnode_print.php';
        if (is_file($helper)) {
            require_once $helper;
        }
        if (function_exists('printnode_send_raw')) {
            return printnode_send_raw($printerId, $rawBytes, $title);
        }
        if (!defined('PRINTNODE_API_KEY') || trim((string)PRINTNODE_API_KEY) === '') {
            throw new RuntimeException('PrintNode API key is not configured. Add it in modules/payments/printnode_print.php or define PRINTNODE_API_KEY.');
        }
        if (!function_exists('curl_init')) {
            throw new RuntimeException('PHP cURL extension is required for PrintNode printing.');
        }
        $payload = json_encode([
            'printerId' => $printerId,
            'title' => $title,
            'contentType' => 'raw_base64',
            'content' => base64_encode($rawBytes),
            'source' => 'Restaurant Orders Signing Bill',
        ]);
        $ch = curl_init('https://api.printnode.com/printjobs');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_USERPWD => PRINTNODE_API_KEY . ':',
            CURLOPT_TIMEOUT => 20,
        ]);
        $response = curl_exec($ch);
        $err = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($response === false || $code < 200 || $code >= 300) {
            throw new RuntimeException('PrintNode failed: ' . ($err ?: ('HTTP ' . $code . ' ' . (string)$response)));
        }
        return ['ok' => true, 'job_id' => $response, 'error' => null, 'response' => $response];
    }
}



if (!function_exists('ro_resolve_actual_room_no')) {
    function ro_resolve_actual_room_no(PDO $pdo, array $order): string {
        $fallback = trim((string)($order['room_no'] ?? ''));
        $folioId = (int)($order['linked_folio_id'] ?? 0);
        if ($folioId <= 0 || !ro_table_exists($pdo, 'folios')) return $fallback;

        $folioRoomingCol = ro_column_exists($pdo, 'folios', 'rooming_id') ? 'rooming_id' : (ro_column_exists($pdo, 'folios', 'order_rooming_id') ? 'order_rooming_id' : null);
        $folioRoomNoCol  = ro_column_exists($pdo, 'folios', 'room_no') ? 'room_no' : null;
        $hasRooming      = ro_table_exists($pdo, 'order_rooming');
        $hasRooms        = ro_table_exists($pdo, 'rooms');

        $select = [];
        $joins = '';
        if ($folioRoomNoCol) $select[] = "NULLIF(TRIM(CAST(f.`{$folioRoomNoCol}` AS CHAR)), '')";
        if ($hasRooming && $folioRoomingCol) {
            $joins .= " LEFT JOIN order_rooming rmg ON rmg.id = f.`{$folioRoomingCol}`";
            if (ro_column_exists($pdo, 'order_rooming', 'room_no')) $select[] = "NULLIF(TRIM(CAST(rmg.room_no AS CHAR)), '')";
            if ($hasRooms && ro_column_exists($pdo, 'order_rooming', 'room_id')) {
                $joins .= " LEFT JOIN rooms rm ON rm.id = rmg.room_id";
                if (ro_column_exists($pdo, 'rooms', 'room_no')) $select[] = "NULLIF(TRIM(CAST(rm.room_no AS CHAR)), '')";
            }
        }
        if (!$select) return $fallback;

        try {
            $sql = "SELECT COALESCE(" . implode(', ', $select) . ") AS actual_room_no FROM folios f {$joins} WHERE f.id = :folio_id LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':folio_id' => $folioId]);
            $actual = trim((string)$stmt->fetchColumn());
            return $actual !== '' ? $actual : $fallback;
        } catch (Throwable $e) {
            return $fallback;
        }
    }
}

if (!function_exists('ro_apply_actual_room_no')) {
    function ro_apply_actual_room_no(PDO $pdo, array $order): array {
        $actual = ro_resolve_actual_room_no($pdo, $order);
        if ($actual !== '') {
            $order['actual_room_no'] = $actual;
            $order['room_no'] = $actual;
        } else {
            $order['actual_room_no'] = trim((string)($order['room_no'] ?? ''));
        }
        return $order;
    }
}

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 ? ro_apply_actual_room_no($pdo, $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_fetch_room_orders_for_signing_bill')) {
    function ro_fetch_room_orders_for_signing_bill(PDO $pdo, int $orderId, bool $combineRoom): array {
        $main = ro_fetch_order_for_bill($pdo, $orderId);
        if (!$main) return [];
        if (!$combineRoom) return [$main];

        $roomNo = trim((string)($main['actual_room_no'] ?? $main['room_no'] ?? ''));
        if ($roomNo === '') return [$main];

        /*
           Combine only live/signable orders for the same room.
           The selected order is always included. Other same-room orders are included only
           when they are not void/closed/paid/room-charged, to avoid reprinting old settled bills.
        */
        $linkedOrderId = (int)($main['linked_order_id'] ?? 0);
        /*
           PDO HY093 fix:
           Some MySQL PDO configurations do not allow the same named placeholder
           to be reused multiple times in one prepared statement. Keep every
           placeholder name unique, especially for Print Bill / combined room bill.
        */
        $params = [':selected_order_id_scope' => $orderId];
        $scopeSql = "ro.id = :selected_order_id_scope OR TRIM(COALESCE(ro.room_no,'')) = :room_no";
        $params[':room_no'] = $roomNo;
        if ($linkedOrderId > 0) {
            $scopeSql .= " OR ro.linked_order_id = :linked_order_id";
            $params[':linked_order_id'] = $linkedOrderId;
        }

        $stmt = $pdo->prepare("
            SELECT ro.*
            FROM restaurant_orders ro
            WHERE ({$scopeSql})
              AND (
                    ro.id = :selected_order_id_include
                    OR (
                        LOWER(COALESCE(ro.status,'')) NOT IN ('void','cancelled','canceled','deleted','closed')
                        AND LOWER(COALESCE(ro.payment_status,'')) NOT IN ('paid','room_charged','void')
                    )
              )
            ORDER BY ro.id ASC
        ");
        $params[':selected_order_id_include'] = $orderId;
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        if (!$rows) return [$main];
        $out = [];
        foreach ($rows as $row) {
            $row = ro_apply_actual_room_no($pdo, $row);
            if (trim((string)($row['actual_room_no'] ?? $row['room_no'] ?? '')) === $roomNo) {
                $out[] = $row;
            }
        }
        return $out ?: [$main];
    }
}

if (!function_exists('ro_fetch_combined_items_for_signing_bill')) {
    function ro_fetch_combined_items_for_signing_bill(PDO $pdo, array $orders): array {
        if (!$orders || !ro_table_exists($pdo, 'restaurant_order_items')) return [];
        $ids = [];
        foreach ($orders as $o) {
            $id = (int)($o['id'] ?? 0);
            if ($id > 0) $ids[] = $id;
        }
        $ids = array_values(array_unique($ids));
        if (!$ids) return [];

        $ph = [];
        $params = [];
        foreach ($ids as $i => $id) {
            $key = ':id' . $i;
            $ph[] = $key;
            $params[$key] = $id;
        }
        $statusSql = ro_column_exists($pdo, 'restaurant_order_items', 'status')
            ? "AND LOWER(COALESCE(status,'active')) NOT IN ('void','cancelled','canceled','deleted')"
            : "";

        $stmt = $pdo->prepare("
            SELECT
                item_name,
                unit_price,
                tax_rate,
                SUM(COALESCE(qty,0)) AS qty,
                SUM(COALESCE(line_total,0)) AS line_total,
                SUM(COALESCE(tax_amount,0)) AS tax_amount,
                GROUP_CONCAT(DISTINCT restaurant_order_id ORDER BY restaurant_order_id SEPARATOR ',') AS source_order_ids
            FROM restaurant_order_items
            WHERE restaurant_order_id IN (" . implode(',', $ph) . ")
            $statusSql
            GROUP BY item_name, unit_price, tax_rate
            ORDER BY item_name ASC
        ");
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}

if (!function_exists('ro_combined_order_numbers')) {
    function ro_combined_order_numbers(array $orders): string {
        $out = [];
        foreach ($orders as $o) {
            $v = trim((string)($o['order_no'] ?? ''));
            if ($v === '') $v = '#' . (int)($o['id'] ?? 0);
            if ($v !== '#0') $out[] = $v;
        }
        return implode(', ', array_unique($out));
    }
}


if (!function_exists('ro_fetch_items_by_order_for_signing_bill')) {
    function ro_fetch_items_by_order_for_signing_bill(PDO $pdo, array $orders): array {
        $out = [];
        foreach ($orders as $order) {
            $orderId = (int)($order['id'] ?? 0);
            if ($orderId <= 0) continue;
            $out[$orderId] = ro_fetch_order_items_for_bill($pdo, $orderId);
        }
        return $out;
    }
}

if (!function_exists('ro_order_bill_total')) {
    function ro_order_bill_total(array $items, array $order): array {
        $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'];
        return ['subtotal' => $subtotal, 'tax_total' => $taxTotal];
    }
}

if (!function_exists('ro_build_thermal_signing_bill')) {
    function ro_build_thermal_signing_bill(PDO $pdo, int $orderId, bool $combineRoom = false): string {
        $orders = ro_fetch_room_orders_for_signing_bill($pdo, $orderId, $combineRoom);
        if (!$orders) throw new RuntimeException('Bill not found.');
        $main = $orders[0];
        $itemsByOrder = ro_fetch_items_by_order_for_signing_bill($pdo, $orders);
        $width = 42;

        $guestName = trim((string)($main['guest_name'] ?? '')) ?: 'Guest / Walk-in';
        $roomNo = trim((string)($main['actual_room_no'] ?? $main['room_no'] ?? ''));
        $tableLabel = trim((string)($main['merged_tables'] ?? ''));
        if ($tableLabel === '') $tableLabel = trim((string)($main['table_no'] ?? ''));
        $tableLabel = $tableLabel !== '' ? ('Table ' . $tableLabel) : 'Walk-in';
        $orderNos = ro_combined_order_numbers($orders);

        $grandSubtotal = 0.00;
        $grandTax = 0.00;
        foreach ($orders as $order) {
            $oid = (int)($order['id'] ?? 0);
            $tot = ro_order_bill_total($itemsByOrder[$oid] ?? [], $order);
            $grandSubtotal += (float)$tot['subtotal'];
            $grandTax += (float)$tot['tax_total'];
        }

        $out = '';
        $out .= str_pad('PIONEERS LODGE', $width, ' ', STR_PAD_BOTH) . "\n";
        $out .= str_pad($combineRoom ? 'ROOM BILL FOR SIGNING' : 'BILL FOR SIGNING', $width, ' ', STR_PAD_BOTH) . "\n";
        $out .= str_pad(date('Y-m-d H:i:s'), $width, ' ', STR_PAD_BOTH) . "\n";
        $out .= ro_thermal_hr($width);
        $out .= ro_thermal_line('Order(s)', $orderNos, $width);
        $out .= ro_thermal_line('Guest', $guestName, $width);
        if ($roomNo !== '') $out .= ro_thermal_line('Room', $roomNo, $width);
        $out .= ro_thermal_line('Table', $tableLabel, $width);
        if (count($orders) > 1) $out .= ro_thermal_line('Split bills', (string)count($orders), $width);
        $out .= ro_thermal_hr($width);

        foreach ($orders as $idx => $order) {
            $oid = (int)($order['id'] ?? 0);
            $orderNo = trim((string)($order['order_no'] ?? '')) ?: ('#' . $oid);
            $billName = trim((string)($order['guest_name'] ?? '')) ?: 'Guest / Walk-in';
            $items = $itemsByOrder[$oid] ?? [];
            $tot = ro_order_bill_total($items, $order);

            if (count($orders) > 1) {
                if ($idx > 0) $out .= "\n";
                $out .= ro_thermal_line('BILL ' . ($idx + 1), $orderNo, $width);
                $out .= ro_thermal_line('Name', $billName, $width);
                $out .= ro_thermal_hr($width);
            }

            foreach ($items as $item) {
                $name = trim((string)($item['item_name'] ?? 'Item')) ?: 'Item';
                $qty = rtrim(rtrim(number_format((float)($item['qty'] ?? 0), 2, '.', ''), '0'), '.');
                $unit = money_fmt((float)($item['unit_price'] ?? 0));
                $line = money_fmt((float)($item['line_total'] ?? 0));
                $out .= ro_thermal_line($name, $line, $width);
                $out .= ro_thermal_line('  ' . $qty . ' x ' . $unit, '', $width);
            }
            if (count($orders) > 1) {
                $out .= ro_thermal_hr($width);
                $out .= ro_thermal_line('Bill Total', money_fmt($tot['subtotal']), $width);
                $out .= ro_thermal_line('VAT incl.', money_fmt($tot['tax_total']), $width);
                $out .= ro_thermal_hr($width);
            }
        }

        $out .= ro_thermal_hr($width);
        $out .= ro_thermal_line('Total Charges', money_fmt($grandSubtotal), $width);
        $out .= ro_thermal_line('Tax/VAT incl.', money_fmt($grandTax), $width);
        $out .= ro_thermal_line('TOTAL', money_fmt($grandSubtotal), $width);
        $out .= ro_thermal_hr($width);
        $out .= "Gratuity: __________________________\n\n";
        $out .= "Total:     __________________________\n\n";
        $out .= "Room/Folio:__________________________\n\n";
        $out .= "Name:      __________________________\n\n";
        $out .= "Signature: __________________________\n\n";
        $out .= ro_thermal_hr($width);
        $out .= str_pad('Thank you.', $width, ' ', STR_PAD_BOTH) . "\n\n\n";
        return $out;
    }
}

if (!function_exists('ro_printnode_signing_bill')) {
    function ro_printnode_signing_bill(PDO $pdo, int $orderId, bool $combineRoom = false): array {
        $text = ro_build_thermal_signing_bill($pdo, $orderId, $combineRoom);
        $raw = "\x1B\x40" . $text . "\x1D\x56\x42\x00";
        return ro_printnode_send_raw((int)RO_KITCHEN_THERMAL_PRINTER_ID, $raw, ($combineRoom ? 'Room Signing Bill ' : 'Signing Bill ') . '#' . $orderId);
    }
}

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

        $order = $orders[0];
        $itemsByOrder = ro_fetch_items_by_order_for_signing_bill($pdo, $orders);
        $orderNo = ro_combined_order_numbers($orders);
        $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';

        $grandSubtotal = 0.00;
        $grandTax = 0.00;
        foreach ($orders as $o) {
            $oid = (int)($o['id'] ?? 0);
            $tot = ro_order_bill_total($itemsByOrder[$oid] ?? [], $o);
            $grandSubtotal += (float)$tot['subtotal'];
            $grandTax += (float)$tot['tax_total'];
        }

        ?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $combineRoom ? 'Combined Room Bill' : '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}
    .split-title{font-size:12px;font-weight:bold;background:#f3f4f6;padding:4px;margin:8px 0 3px}
    .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">
    <a href="restaurant_orders.php?bill_reprint=1&printnode=1<?php echo $combineRoom ? '&combine_room=1' : ''; ?>&id=<?php echo (int)$orderId; ?>">Send Direct to Kitchen Printer</a>
    <button onclick="window.close()">Close</button>
</div>
<div class="bill-wrap">
    <div class="center">
        <strong>Pioneers Lodge</strong><br>
        <div class="copy-label"><?php echo $combineRoom ? 'COMBINED ROOM BILL FOR SIGNING' : '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(s)</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 $actualBillRoom = trim((string)($order['actual_room_no'] ?? $order['room_no'] ?? '')); ?>
        <?php if ($actualBillRoom !== ''): ?><tr><td>Room</td><td class="right"><?php echo h($actualBillRoom); ?></td></tr><?php endif; ?>
        <?php if (count($orders) > 1): ?><tr><td>Split Bills</td><td class="right"><?php echo count($orders); ?></td></tr><?php endif; ?>
        <tr><td>Cashier</td><td class="right"><?php echo h($order['cashier_name'] ?? ''); ?></td></tr>
    </table>
    <div class="line"></div>
    <?php foreach ($orders as $idx => $o): ?>
        <?php
            $oid = (int)($o['id'] ?? 0);
            $items = $itemsByOrder[$oid] ?? [];
            $tot = ro_order_bill_total($items, $o);
            $splitNo = trim((string)($o['order_no'] ?? '')) ?: ('#' . $oid);
        ?>
        <?php if (count($orders) > 1): ?><div class="split-title">BILL <?php echo $idx + 1; ?>: <?php echo h($splitNo); ?></div><?php endif; ?>
        <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>
        <?php if (count($orders) > 1): ?>
            <table><tr><td>Bill Total</td><td class="right"><?php echo money_fmt($tot['subtotal']); ?></td></tr></table>
            <div class="line"></div>
        <?php endif; ?>
    <?php endforeach; ?>
    <table>
        <tr><td>Total Charges</td><td class="right"><?php echo money_fmt($grandSubtotal); ?></td></tr>
        <tr><td>Tax/VAT incl.</td><td class="right"><?php echo money_fmt($grandTax); ?></td></tr>
        <tr class="total"><td>Total</td><td class="right"><?php echo money_fmt($grandSubtotal); ?></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>
</body>
</html><?php
        exit;
    }
}

if (isset($_GET['bill_reprint']) && (int)$_GET['bill_reprint'] === 1) {
    $billOrderId = (int)($_GET['id'] ?? 0);
    $combineRoom = (isset($_GET['combine_room']) && (int)$_GET['combine_room'] === 1);
    $toPrintNode = (isset($_GET['printnode']) && (int)$_GET['printnode'] === 1);

    if ($toPrintNode) {
        try {
            ro_printnode_signing_bill($pdo, $billOrderId, $combineRoom);
            ro_signing_bill_printnode_flash('success', ($combineRoom ? 'Room bill' : 'Bill') . ' sent to kitchen thermal printer ' . RO_KITCHEN_THERMAL_PRINTER_ID . '.');
        } catch (Throwable $e) {
            ro_signing_bill_printnode_flash('danger', 'Kitchen thermal print failed: ' . $e->getMessage());
        }
        header('Location: restaurant_orders.php');
        exit;
    }

    ro_render_signing_bill($pdo, $billOrderId, $combineRoom);
}

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

$filterQ             = trim((string)($_GET['q'] ?? ''));
$filterStatus        = trim((string)($_GET['status'] ?? ''));
$filterPaymentStatus = trim((string)($_GET['payment_status'] ?? ''));
$filterOrderType     = trim((string)($_GET['order_type'] ?? ''));
$filterDateFrom      = trim((string)($_GET['date_from'] ?? ''));
$filterDateTo        = trim((string)($_GET['date_to'] ?? ''));
$hasActiveFilters    = ($filterQ !== '' || $filterStatus !== '' || $filterPaymentStatus !== '' || $filterOrderType !== '' || $filterDateFrom !== '' || $filterDateTo !== '');

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";

    $whereClauses = [];
    $whereParams  = [];

    if ($filterQ !== '') {
        $searchCols = ['ro.order_no'];
        if (ro_column_exists($pdo, 'restaurant_orders', 'guest_name')) $searchCols[] = 'ro.guest_name';
        if (ro_column_exists($pdo, 'restaurant_orders', 'cashier_name')) $searchCols[] = 'ro.cashier_name';
        if (ro_column_exists($pdo, 'restaurant_orders', 'room_no')) $searchCols[] = 'ro.room_no';
        if (ro_column_exists($pdo, 'restaurant_orders', 'group_name')) $searchCols[] = 'ro.group_name';
        if ($hasOrderTables) $searchCols[] = 'mt.merged_tables';
        $searchCols[] = 'rt.table_no';

        $orParts = [];
        foreach ($searchCols as $idx => $col) {
            $key = ':q' . $idx;
            $orParts[] = "$col LIKE $key";
            $whereParams[$key] = '%' . $filterQ . '%';
        }
        $whereClauses[] = '(' . implode(' OR ', $orParts) . ')';
    }

    if ($filterStatus !== '' && ro_column_exists($pdo, 'restaurant_orders', 'status')) {
        $whereClauses[] = 'LOWER(ro.status) = :f_status';
        $whereParams[':f_status'] = strtolower($filterStatus);
    }

    if ($filterPaymentStatus !== '' && ro_column_exists($pdo, 'restaurant_orders', 'payment_status')) {
        $whereClauses[] = 'LOWER(ro.payment_status) = :f_payment_status';
        $whereParams[':f_payment_status'] = strtolower($filterPaymentStatus);
    }

    if ($filterOrderType !== '' && ro_column_exists($pdo, 'restaurant_orders', 'order_type')) {
        $whereClauses[] = 'LOWER(ro.order_type) = :f_order_type';
        $whereParams[':f_order_type'] = strtolower($filterOrderType);
    }

    $dateCol = ro_column_exists($pdo, 'restaurant_orders', 'opened_at') ? 'ro.opened_at' : (ro_column_exists($pdo, 'restaurant_orders', 'created_at') ? 'ro.created_at' : '');
    if ($dateCol !== '' && $filterDateFrom !== '' && strtotime($filterDateFrom) !== false) {
        $whereClauses[] = "DATE($dateCol) >= :f_date_from";
        $whereParams[':f_date_from'] = date('Y-m-d', strtotime($filterDateFrom));
    }
    if ($dateCol !== '' && $filterDateTo !== '' && strtotime($filterDateTo) !== false) {
        $whereClauses[] = "DATE($dateCol) <= :f_date_to";
        $whereParams[':f_date_to'] = date('Y-m-d', strtotime($filterDateTo));
    }

    $whereSql = $whereClauses ? ('WHERE ' . implode(' AND ', $whereClauses)) : '';

    $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
        $whereSql
        ORDER BY ro.id DESC
        LIMIT 500
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($whereParams);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($orders as $idx => $orderRow) {
        $orders[$idx] = ro_apply_actual_room_no($pdo, $orderRow);
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

require_once __DIR__ . '/../../includes/header.php';
$roFlash = ro_signing_bill_get_flash();
?>

<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 foreach ($roFlash as $f): ?>
    <div class="alert alert-<?php echo h(($f['type'] ?? '') === 'success' ? 'success' : (($f['type'] ?? '') === 'danger' ? 'danger' : 'info')); ?> py-2"><?php echo h($f['message'] ?? ''); ?></div>
<?php endforeach; ?>

<?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"><?php echo $hasActiveFilters ? 'Filtered results (max 500)' : '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 border-bottom py-3">
        <form method="get" class="row g-2 align-items-end" id="orderFilterForm">
            <div class="col-lg-3 col-md-6">
                <label class="form-label small mb-1">Search</label>
                <input type="text" name="q" id="orderSearchInput" class="form-control form-control-sm"
                       placeholder="Order no, guest, cashier, room, table..."
                       value="<?php echo h($filterQ); ?>" autocomplete="off">
            </div>
            <div class="col-lg-2 col-md-6">
                <label class="form-label small mb-1">Status</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">All statuses</option>
                    <?php foreach (['open','sent','preparing','served','bill_requested','closed','void'] as $st): ?>
                        <option value="<?php echo h($st); ?>" <?php echo $filterStatus === $st ? 'selected' : ''; ?>><?php echo h(ucwords(str_replace('_',' ',$st))); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-2 col-md-6">
                <label class="form-label small mb-1">Payment</label>
                <select name="payment_status" class="form-select form-select-sm">
                    <option value="">All payments</option>
                    <?php foreach (['unpaid','part_paid','paid','room_charged','void'] as $ps): ?>
                        <option value="<?php echo h($ps); ?>" <?php echo $filterPaymentStatus === $ps ? 'selected' : ''; ?>><?php echo h(ucwords(str_replace('_',' ',$ps))); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-2 col-md-6">
                <label class="form-label small mb-1">Type</label>
                <select name="order_type" class="form-select form-select-sm">
                    <option value="">All types</option>
                    <?php foreach (['table','room','group','walkin','takeaway'] as $ot): ?>
                        <option value="<?php echo h($ot); ?>" <?php echo $filterOrderType === $ot ? 'selected' : ''; ?>><?php echo h(ucwords($ot)); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-1 col-md-6">
                <label class="form-label small mb-1">From</label>
                <input type="date" name="date_from" class="form-control form-control-sm" value="<?php echo h($filterDateFrom); ?>">
            </div>
            <div class="col-lg-1 col-md-6">
                <label class="form-label small mb-1">To</label>
                <input type="date" name="date_to" class="form-control form-control-sm" value="<?php echo h($filterDateTo); ?>">
            </div>
            <div class="col-lg-1 col-md-12 d-flex gap-1">
                <button type="submit" class="btn btn-primary btn-sm flex-fill"><i class="bi bi-search"></i></button>
                <?php if ($hasActiveFilters): ?>
                    <a href="orders.php" class="btn btn-outline-secondary btn-sm" title="Clear filters"><i class="bi bi-x-lg"></i></a>
                <?php endif; ?>
            </div>
        </form>
        <?php if ($hasActiveFilters): ?>
            <div class="small text-muted mt-2">
                <i class="bi bi-funnel-fill me-1"></i>Showing <?php echo count($orders); ?> filtered result<?php echo count($orders) === 1 ? '' : 's'; ?>
                <a href="orders.php" class="ms-1">clear</a>
            </div>
        <?php endif; ?>
    </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);
                        $rowSearchBlob = strtolower($orderNo . ' ' . $orderName . ' ' . ($o['cashier_name'] ?? '') . ' ' . $tableLabel . ' ' . ($o['room_no'] ?? ''));
                    ?>
                    <tr data-search="<?php echo h($rowSearchBlob); ?>">
                        <td>
                            <strong><?php echo h($orderNo); ?></strong>
                            <?php $actualRowRoom = trim((string)($o['actual_room_no'] ?? $o['room_no'] ?? '')); ?>
                            <?php if ($actualRowRoom !== '' && ($o['order_type'] ?? '') !== 'walkin'): ?>
                                <div class="small text-muted">Room <?php echo h($actualRowRoom); ?></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-primary" href="planner.php?restaurant_order_id=<?php echo (int)$o['id']; ?>" title="Open this bill in the POS screen - use this to void/correct a payment">
                                    <i class="bi bi-credit-card me-1"></i>Payments
                                </a>
                                <?php $actualActionRoom = trim((string)($o['actual_room_no'] ?? $o['room_no'] ?? '')); ?>
                                <?php if ($actualActionRoom !== ''): ?>
                                    <a class="btn btn-outline-success" href="restaurant_orders.php?bill_reprint=1&combine_room=1&printnode=1&id=<?php echo (int)$o['id']; ?>" title="Print split room signing bills directly to kitchen thermal printer">
                                        Print Room Bill
                                    </a>
                                <?php else: ?>
                                    <a class="btn btn-outline-success" href="restaurant_orders.php?bill_reprint=1&printnode=1&id=<?php echo (int)$o['id']; ?>" title="Print signing bill directly to kitchen thermal printer">
                                        Print Bill
                                    </a>
                                <?php endif; ?>
                            </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>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var searchInput = document.getElementById('orderSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', function () {
            var term = searchInput.value.trim().toLowerCase();
            document.querySelectorAll('.restaurant-orders-wrap tbody tr[data-search]').forEach(function (row) {
                var match = term === '' || row.getAttribute('data-search').indexOf(term) !== -1;
                row.style.display = match ? '' : 'none';
            });
        });
    }
});
</script>

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