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

$pageTitle = 'Kitchen Production Board';

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

if (!function_exists('kd_flash')) {
    function kd_flash(string $type, string $message): void
    {
        $_SESSION['kitchen_display_flash'][] = [
            'type' => $type,
            'message' => $message,
        ];
    }
}

if (!function_exists('kd_get_flash')) {
    function kd_get_flash(): array
    {
        $items = $_SESSION['kitchen_display_flash'] ?? [];
        unset($_SESSION['kitchen_display_flash']);
        return is_array($items) ? $items : [];
    }
}

if (!function_exists('kd_table_exists')) {
    function kd_table_exists(PDO $pdo, string $table): bool
    {
        static $cache = [];
        if (array_key_exists($table, $cache)) {
            return $cache[$table];
        }

        try {
            $stmt = $pdo->prepare(" 
                SELECT COUNT(*)
                FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = :table_name
            ");
            $stmt->execute([':table_name' => $table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$table] = false;
        }
    }
}

if (!function_exists('kd_column_exists')) {
    function kd_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 = :table_name
                  AND COLUMN_NAME = :column_name
            ");
            $stmt->execute([
                ':table_name' => $table,
                ':column_name' => $column,
            ]);
            return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$key] = false;
        }
    }
}

if (!function_exists('kd_first_existing_column')) {
    function kd_first_existing_column(PDO $pdo, string $table, array $columns): string
    {
        foreach ($columns as $column) {
            if (kd_column_exists($pdo, $table, $column)) {
                return $column;
            }
        }
        return '';
    }
}

if (!function_exists('kd_status_label')) {
    function kd_status_label(string $status): string
    {
        $status = strtolower(trim($status));
        switch ($status) {
            case 'pending': return 'New Ticket';
            case 'printing': return 'In Kitchen';
            case 'failed': return 'Needs Attention';
            case 'printed': return 'Completed';
            default: return ucwords(str_replace('_', ' ', $status !== '' ? $status : 'Unknown'));
        }
    }
}

if (!function_exists('kd_status_class')) {
    function kd_status_class(string $status): string
    {
        $status = strtolower(trim($status));
        if ($status === 'failed') return 'danger';
        if ($status === 'printing') return 'warning';
        if ($status === 'printed') return 'success';
        return 'primary';
    }
}

if (!function_exists('kd_wait_minutes')) {
    function kd_wait_minutes($createdAt): int
    {
        $ts = strtotime((string)$createdAt);
        if (!$ts) return 0;
        return max(0, (int)floor((time() - $ts) / 60));
    }
}

if (!function_exists('kd_wait_class')) {
    function kd_wait_class(int $minutes): string
    {
        if ($minutes >= 20) return 'danger';
        if ($minutes >= 10) return 'warning';
        return 'success';
    }
}

if (!function_exists('kd_clean_payload')) {
    function kd_clean_payload($payload): string
    {
        $payload = trim((string)$payload);
        if ($payload === '') return '';

        $decoded = json_decode($payload, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
            return $payload;
        }

        $lines = [];
        foreach (['order_no', 'table', 'table_no', 'meal_period', 'station'] as $key) {
            if (!empty($decoded[$key]) && is_scalar($decoded[$key])) {
                $label = ucwords(str_replace('_', ' ', $key));
                $lines[] = $label . ': ' . (string)$decoded[$key];
            }
        }

        $items = $decoded['items'] ?? $decoded['lines'] ?? [];
        if (is_array($items) && $items) {
            if ($lines) $lines[] = '';
            foreach ($items as $item) {
                if (!is_array($item)) {
                    $lines[] = '- ' . (string)$item;
                    continue;
                }
                $qty = $item['qty'] ?? $item['quantity'] ?? 1;
                $name = $item['item_name'] ?? $item['name'] ?? $item['description'] ?? 'Item';
                $note = trim((string)($item['notes'] ?? $item['note'] ?? $item['special_instruction'] ?? ''));
                $line = '- ' . $qty . ' x ' . $name;
                if ($note !== '') $line .= ' | ' . $note;
                $lines[] = $line;
            }
        }

        if (!$lines) {
            return json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: $payload;
        }
        return implode("\n", $lines);
    }
}

if (!function_exists('kd_fetch_order_tables')) {
    function kd_fetch_order_tables(PDO $pdo, int $orderId, string $fallbackTableNo = '', string $fallbackTableName = ''): array
    {
        $labels = [];

        try {
            if (kd_table_exists($pdo, 'restaurant_order_tables')) {
                $orderCol = kd_first_existing_column($pdo, 'restaurant_order_tables', ['order_id', 'restaurant_order_id']);
                $tableCol = kd_first_existing_column($pdo, 'restaurant_order_tables', ['table_id', 'restaurant_table_id']);
                if ($orderCol !== '' && $tableCol !== '') {
                    $stmt = $pdo->prepare(" 
                        SELECT rt.table_no, rt.table_name
                        FROM restaurant_order_tables rot
                        INNER JOIN restaurant_tables rt ON rt.id = rot.`$tableCol`
                        WHERE rot.`$orderCol` = :order_id
                        ORDER BY rt.table_no ASC, rt.id ASC
                    ");
                    $stmt->execute([':order_id' => $orderId]);
                    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                        $tableNo = trim((string)($row['table_no'] ?? ''));
                        $tableName = trim((string)($row['table_name'] ?? ''));
                        $label = $tableNo !== '' ? $tableNo : $tableName;
                        if ($label !== '') $labels[$label] = $label;
                    }
                }
            }
        } catch (Throwable $e) {
            $labels = [];
        }

        if (!$labels) {
            $fallback = trim($fallbackTableNo);
            if ($fallback === '') $fallback = trim($fallbackTableName);
            if ($fallback !== '') $labels[$fallback] = $fallback;
        }

        $summary = $labels ? implode(' + ', array_values($labels)) : '-';
        return [
            'labels' => array_values($labels),
            'summary' => $summary,
            'is_merged' => count($labels) > 1,
        ];
    }
}

if (!function_exists('kd_guess_meal_period')) {
    function kd_guess_meal_period(array $job): string
    {
        foreach (['meal_period', 'order_period', 'service_period', 'meal_time'] as $key) {
            $value = trim((string)($job[$key] ?? ''));
            if ($value !== '') return ucwords(str_replace('_', ' ', $value));
        }

        $createdAt = (string)($job['created_at'] ?? '');
        $hour = (int)date('H', strtotime($createdAt) ?: time());
        if ($hour >= 5 && $hour < 11) return 'Breakfast';
        if ($hour >= 11 && $hour < 16) return 'Lunch';
        if ($hour >= 16 && $hour < 22) return 'Dinner';
        return 'Late Service';
    }
}

$errors = [];

try {
    if (!kd_table_exists($pdo, 'restaurant_print_jobs')) {
        $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_print_jobs (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            restaurant_order_id BIGINT UNSIGNED NOT NULL,
            printer_role VARCHAR(60) NOT NULL,
            job_type ENUM('station','master','receipt','void') NOT NULL DEFAULT 'station',
            payload LONGTEXT NOT NULL,
            status ENUM('pending','printing','printed','failed') NOT NULL DEFAULT 'pending',
            error_message TEXT NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            printed_at DATETIME NULL,
            INDEX idx_rest_print_status (status),
            INDEX idx_rest_print_order (restaurant_order_id),
            INDEX idx_rest_print_role (printer_role)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    }

    if (kd_table_exists($pdo, 'restaurant_print_jobs') && !kd_column_exists($pdo, 'restaurant_print_jobs', 'restaurant_order_id')) {
        $pdo->exec("ALTER TABLE restaurant_print_jobs ADD COLUMN restaurant_order_id BIGINT UNSIGNED NULL AFTER id");
    }
    if (kd_table_exists($pdo, 'restaurant_print_jobs') && !kd_column_exists($pdo, 'restaurant_print_jobs', 'printer_role')) {
        $pdo->exec("ALTER TABLE restaurant_print_jobs ADD COLUMN printer_role VARCHAR(60) NULL AFTER restaurant_order_id");
    }
    if (kd_table_exists($pdo, 'restaurant_print_jobs') && !kd_column_exists($pdo, 'restaurant_print_jobs', 'printed_at')) {
        $pdo->exec("ALTER TABLE restaurant_print_jobs ADD COLUMN printed_at DATETIME NULL AFTER created_at");
    }
} catch (Throwable $e) {
    $errors[] = 'Could not prepare kitchen display tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) {
            verify_csrf();
        }

        $action = (string)($_POST['action'] ?? '');
        $jobId = (int)($_POST['job_id'] ?? 0);

        if ($jobId <= 0) {
            throw new RuntimeException('Invalid ticket selected.');
        }

        if ($action === 'mark_printing') {
            $stmt = $pdo->prepare("UPDATE restaurant_print_jobs SET status = 'printing', error_message = NULL WHERE id = :id AND status IN ('pending','failed')");
            $stmt->execute([':id' => $jobId]);
            kd_flash('success', 'Ticket moved to In Kitchen.');
        } elseif ($action === 'mark_printed') {
            $stmt = $pdo->prepare("UPDATE restaurant_print_jobs SET status = 'printed', printed_at = NOW(), error_message = NULL WHERE id = :id");
            $stmt->execute([':id' => $jobId]);
            kd_flash('success', 'Ticket completed and removed from the active kitchen board.');
        } elseif ($action === 'mark_attention') {
            $reason = trim((string)($_POST['error_message'] ?? 'Requires kitchen attention'));
            $stmt = $pdo->prepare("UPDATE restaurant_print_jobs SET status = 'failed', error_message = :msg WHERE id = :id");
            $stmt->execute([
                ':msg' => $reason !== '' ? $reason : 'Requires kitchen attention',
                ':id' => $jobId,
            ]);
            kd_flash('warning', 'Ticket marked as Needs Attention.');
        } elseif ($action === 'reprint_ticket') {
            $stmt = $pdo->prepare("UPDATE restaurant_print_jobs SET status = 'pending', printed_at = NULL, error_message = NULL WHERE id = :id");
            $stmt->execute([':id' => $jobId]);
            kd_flash('success', 'Ticket sent back to New Ticket for reprint/reprocessing.');
        } else {
            throw new RuntimeException('Invalid action.');
        }

        header('Location: kitchen_display.php');
        exit;
    } catch (Throwable $e) {
        kd_flash('danger', $e->getMessage());
        header('Location: kitchen_display.php');
        exit;
    }
}

$jobs = [];
$error = '';

try {
    $mealColumn = kd_first_existing_column($pdo, 'restaurant_orders', ['meal_period', 'order_period', 'service_period', 'meal_time']);
    $mealSelect = $mealColumn !== '' ? "ro.`$mealColumn` AS meal_period," : "NULL AS meal_period,";

    $stmt = $pdo->query(" 
        SELECT
            j.*,
            ro.order_no,
            ro.status AS restaurant_order_status,
            ro.total_amount,
            $mealSelect
            rt.table_no,
            rt.table_name,
            a.area_name
        FROM restaurant_print_jobs j
        LEFT JOIN restaurant_orders ro
            ON ro.id = j.restaurant_order_id
        LEFT JOIN restaurant_tables rt
            ON rt.id = ro.table_id
        LEFT JOIN restaurant_areas a
            ON a.id = rt.area_id
        WHERE LOWER(COALESCE(j.printer_role, '')) IN ('kitchen','food')
          AND j.status IN ('pending','printing','failed')
        ORDER BY
            CASE j.status
                WHEN 'pending' THEN 1
                WHEN 'printing' THEN 2
                WHEN 'failed' THEN 3
                ELSE 9
            END,
            j.created_at ASC,
            j.id ASC
        LIMIT 100
    ");
    $jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($jobs as &$job) {
        $orderId = (int)($job['restaurant_order_id'] ?? 0);
        $tables = kd_fetch_order_tables(
            $pdo,
            $orderId,
            (string)($job['table_no'] ?? ''),
            (string)($job['table_name'] ?? '')
        );
        $job['table_summary'] = $tables['summary'];
        $job['is_merged_table'] = $tables['is_merged'];
        $job['meal_period_label'] = kd_guess_meal_period($job);
        $job['clean_payload'] = kd_clean_payload($job['payload'] ?? '');
        $job['wait_minutes'] = kd_wait_minutes($job['created_at'] ?? '');
    }
    unset($job);
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$flashes = kd_get_flash();

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

<div class="hero-band kitchen-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-display"></i> Production
            </div>
            <div class="hero-title mt-1">Kitchen Production Board</div>
            <div class="hero-subtitle mt-1">New, active, and attention-needed food tickets routed from the Restaurant Planner.</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-outline-light btn-sm" href="planner.php">
                <i class="bi bi-grid-3x3-gap me-1"></i>Planner
            </a>
            <a class="btn btn-outline-light btn-sm" href="printer_jobs.php">
                <i class="bi bi-printer me-1"></i>Print Queue
            </a>
            <button class="btn btn-light btn-sm" onclick="location.reload()">
                <i class="bi bi-arrow-repeat me-1"></i>Refresh
            </button>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <strong>Please fix the following:</strong>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

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

<div class="row g-2 mb-3 kitchen-metrics">
    <?php
        $countNew = 0; $countKitchen = 0; $countAttention = 0;
        foreach ($jobs as $jCount) {
            $sCount = strtolower((string)($jCount['status'] ?? 'pending'));
            if ($sCount === 'printing') $countKitchen++;
            elseif ($sCount === 'failed') $countAttention++;
            else $countNew++;
        }
    ?>
    <div class="col-sm-4"><div class="metric-mini bg-primary-subtle"><span>New Ticket</span><strong><?php echo number_format($countNew); ?></strong></div></div>
    <div class="col-sm-4"><div class="metric-mini bg-warning-subtle"><span>In Kitchen</span><strong><?php echo number_format($countKitchen); ?></strong></div></div>
    <div class="col-sm-4"><div class="metric-mini bg-danger-subtle"><span>Needs Attention</span><strong><?php echo number_format($countAttention); ?></strong></div></div>
</div>

<div class="row g-3">
    <?php if (!$jobs): ?>
        <div class="col-12">
            <div class="alert alert-success kitchen-clear">
                <i class="bi bi-check-circle me-2"></i>Kitchen clear. No active food tickets.
            </div>
        </div>
    <?php else: ?>
        <?php foreach ($jobs as $j): ?>
            <?php
                $status = strtolower((string)($j['status'] ?? 'pending'));
                $statusClass = kd_status_class($status);
                $statusLabel = kd_status_label($status);
                $orderLabel = $j['order_no'] ?: ('Order #' . (int)($j['restaurant_order_id'] ?? 0));
                $tableLabel = trim((string)($j['table_summary'] ?? ''));
                if ($tableLabel === '') $tableLabel = '-';
                $areaLabel = trim((string)($j['area_name'] ?? ''));
                $waitMinutes = (int)($j['wait_minutes'] ?? 0);
                $waitClass = kd_wait_class($waitMinutes);
                $mealPeriod = trim((string)($j['meal_period_label'] ?? ''));
                $payloadText = (string)($j['clean_payload'] ?? $j['payload'] ?? '');
            ?>
            <div class="col-md-6 col-xl-4">
                <div class="card ticket-card h-100 status-<?php echo h($status); ?>">
                    <div class="card-header d-flex justify-content-between align-items-start gap-2">
                        <div>
                            <strong><?php echo h($orderLabel); ?></strong>
                            <div class="small text-muted">
                                Table <?php echo h($tableLabel); ?><?php echo $areaLabel !== '' ? ' • ' . h($areaLabel) : ''; ?>
                            </div>
                        </div>
                        <span class="badge text-bg-<?php echo h($statusClass); ?>">
                            <?php echo h($statusLabel); ?>
                        </span>
                    </div>

                    <div class="card-body">
                        <div class="ticket-badges mb-2">
                            <span class="badge text-bg-<?php echo h($waitClass); ?>">
                                <i class="bi bi-clock me-1"></i>Waiting <?php echo (int)$waitMinutes; ?> mins
                            </span>
                            <?php if ($mealPeriod !== ''): ?>
                                <span class="badge text-bg-light border text-dark">
                                    <i class="bi bi-cup-hot me-1"></i><?php echo h($mealPeriod); ?>
                                </span>
                            <?php endif; ?>
                            <?php if (!empty($j['is_merged_table'])): ?>
                                <span class="badge text-bg-dark">
                                    <i class="bi bi-union me-1"></i>Merged Tables
                                </span>
                            <?php endif; ?>
                        </div>

                        <div class="ticket-meta mb-2">
                            <span><i class="bi bi-calendar-event me-1"></i><?php echo h($j['created_at'] ?? ''); ?></span>
                            <span><i class="bi bi-printer me-1"></i><?php echo h($j['printer_role'] ?? 'kitchen'); ?></span>
                        </div>

                        <?php if (!empty($j['is_merged_table'])): ?>
                            <div class="merged-table-note mb-2">
                                <i class="bi bi-info-circle me-1"></i>Combined table group: <?php echo h($tableLabel); ?>
                            </div>
                        <?php endif; ?>

                        <pre class="ticket-payload"><?php echo h($payloadText); ?></pre>

                        <?php if (!empty($j['error_message'])): ?>
                            <div class="alert alert-warning py-2 small mb-2">
                                <strong>Needs attention:</strong> <?php echo h($j['error_message']); ?>
                            </div>
                        <?php endif; ?>

                        <div class="d-flex flex-wrap gap-2 mt-3">
                            <?php if ($status !== 'printing'): ?>
                                <form method="post">
                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                    <input type="hidden" name="action" value="mark_printing">
                                    <input type="hidden" name="job_id" value="<?php echo (int)$j['id']; ?>">
                                    <button class="btn btn-sm btn-outline-warning">
                                        <i class="bi bi-hourglass-split me-1"></i>In Kitchen
                                    </button>
                                </form>
                            <?php endif; ?>

<button type="button"
        class="btn btn-sm btn-success"
        data-bs-toggle="modal"
        data-bs-target="#completeTicketModal<?php echo (int)$j['id']; ?>">
    <i class="bi bi-check2-circle me-1"></i>Completed
</button>

<div class="modal fade"
     id="completeTicketModal<?php echo (int)$j['id']; ?>"
     tabindex="-1"
     aria-hidden="true">

    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">

            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="bi bi-check-circle me-2"></i>
                    Complete Restaurant Ticket
                </h5>

                <button type="button"
                        class="btn-close btn-close-white"
                        data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">

                <p class="mb-3">
                    Mark this Restaurant Ticket as completed?
                </p>

                <div class="alert alert-info mb-0">
                    <i class="bi bi-info-circle me-1"></i>
                    The ticket will be removed from the active Kitchen Production Board.
                </div>

            </div>

            <div class="modal-footer">

                <button type="button"
                        class="btn btn-outline-secondary"
                        data-bs-dismiss="modal">
                    Cancel
                </button>

                <form method="post" class="d-inline">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>

                    <input type="hidden"
                           name="action"
                           value="mark_printed">

                    <input type="hidden"
                           name="job_id"
                           value="<?php echo (int)$j['id']; ?>">

                    <button type="submit"
                            class="btn btn-success">
                        <i class="bi bi-check2-circle me-1"></i>
                        Yes, Complete Ticket
                    </button>
                </form>

            </div>

        </div>
    </div>

</div>

                            <form method="post">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="reprint_ticket">
                                <input type="hidden" name="job_id" value="<?php echo (int)$j['id']; ?>">
                                <button class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-printer me-1"></i>Reprint Ticket
                                </button>
                            </form>

                            <form method="post" onsubmit="return confirm('Mark this ticket as needing kitchen attention?');">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="mark_attention">
                                <input type="hidden" name="job_id" value="<?php echo (int)$j['id']; ?>">
                                <input type="hidden" name="error_message" value="Requires kitchen attention">
                                <button class="btn btn-sm btn-outline-danger">
                                    <i class="bi bi-exclamation-triangle me-1"></i>Needs Attention
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<style>
.kitchen-hero{padding:12px 16px!important;margin-bottom:10px!important}
.kitchen-hero .hero-title{font-size:1.35rem!important;line-height:1.1!important}
.kitchen-hero .hero-subtitle{font-size:.82rem!important;color:rgba(255,255,255,.78)!important}
.kitchen-metrics .metric-mini{border:1px solid #e5e7eb;border-radius:14px;padding:9px 12px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 8px 20px rgba(15,23,42,.045)}
.kitchen-metrics .metric-mini span{font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;font-weight:800;color:#475569}
.kitchen-metrics .metric-mini strong{font-size:1.15rem;color:#0f172a}
.ticket-card{border-radius:16px;border:1px solid #e5e7eb;box-shadow:0 12px 30px rgba(15,23,42,.06);overflow:hidden}
.ticket-card.status-pending{border-color:#bfdbfe}
.ticket-card.status-printing{border-color:#fde68a}
.ticket-card.status-failed{border-color:#fecaca}
.ticket-card .card-header{background:#ffffff;border-bottom:1px solid #eef2f7}
.ticket-badges{display:flex;flex-wrap:wrap;gap:6px}
.ticket-meta{display:flex;flex-wrap:wrap;gap:10px;color:#64748b;font-size:.78rem;font-weight:700}
.ticket-payload{white-space:pre-wrap;font-family:inherit;background:#f8fafc;border-radius:12px;padding:10px;font-size:.9rem;min-height:120px;border:1px solid #e5e7eb;color:#0f172a}
.kitchen-clear{border-radius:16px;padding:18px;font-weight:700}
.merged-table-note{border:1px solid #e5e7eb;background:#f8fafc;border-radius:12px;padding:8px 10px;font-size:.78rem;font-weight:800;color:#334155}
.ticket-card .btn{border-radius:999px;font-weight:800}
@media(max-width:575.98px){.ticket-card .btn{width:100%}.ticket-card form{width:100%}}
</style>

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