<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';

$auth = new Auth();
$auth->requireRole(['kitchen_staff', 'restaurant_admin', 'restaurant_manager']);

$csrf = new CSRF();
$csrfToken = $csrf->getToken();

$restaurantId = $auth->restaurantId();
$restaurantName = APP_NAME;

$db = Database::getInstance();
if ($restaurantId) {
    $stmt = $db->query("SELECT name, logo FROM restaurants WHERE id = ?", [$restaurantId]);
    $restaurant = $stmt->fetch();
    if ($restaurant) {
        $restaurantName = $restaurant['name'];
    }
    $settingsStmt = $db->query("SELECT * FROM restaurant_settings WHERE restaurant_id = ? LIMIT 1", [$restaurantId]);
    $settings = $settingsStmt->fetch() ?: [];
}

$baseUrl = getBaseUrl();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo sanitize($csrfToken); ?>">
    <title>Kitchen Display - <?php echo sanitize($restaurantName); ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="<?php echo $baseUrl; ?>/assets/css/kitchen.css" rel="stylesheet">
    <script>
        var KDS_CONFIG = {
            baseUrl: '<?php echo $baseUrl; ?>',
            ajaxOrders: '<?php echo $baseUrl; ?>/ajax/kitchen_orders.php',
            ajaxAction: '<?php echo $baseUrl; ?>/ajax/kitchen_action.php',
            printUrl: '<?php echo $baseUrl; ?>/ajax/print_order.php',
            csrfToken: '<?php echo sanitize($csrfToken); ?>',
            restaurantId: <?php echo (int) $restaurantId; ?>,
            soundEnabled: <?php echo (isset($settings) && isset($settings['sound_notification'])) ? (int) $settings['sound_notification'] : 1; ?>,
            refreshInterval: <?php echo (isset($settings) && isset($settings['refresh_interval'])) ? (int) $settings['refresh_interval'] * 1000 : 10000; ?>
        };
    </script>
</head>
<body>
