<?php
session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../db/config.php';

// Ensure the user is a logged-in restaurant owner
if (!isset($_SESSION['restaurant_id'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Access denied.']);
    exit;
}

$restaurant_id = $_SESSION['restaurant_id'];
$last_check_timestamp = $_GET['since'] ?? '1970-01-01 00:00:00';

// Fetch new orders since the last check
$stmt = $pdo->prepare("
    SELECT o.id, o.total_price, o.status, o.created_at, u.name as user_name
    FROM orders o
    JOIN users u ON o.user_id = u.id
    WHERE o.restaurant_id = ? AND o.created_at > ?
    ORDER BY o.created_at DESC
");
$stmt->execute([$restaurant_id, $last_check_timestamp]);
$new_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($new_orders);
?>