<?php
session_start();
require_once '../db/config.php';

if (!isset($_SESSION['restaurant_user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$order_id = $data['order_id'] ?? null;
$status = $data['status'] ?? null;
$restaurant_id = $_SESSION['restaurant_id'];

if (!$order_id || !$status) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing order_id or status']);
    exit;
}

// Verify the order belongs to the restaurant
$stmt = $pdo->prepare('SELECT id FROM orders WHERE id = ? AND restaurant_id = ?');
$stmt->execute([$order_id, $restaurant_id]);
$order = $stmt->fetch();

if (!$order) {
    http_response_code(404);
    echo json_encode(['error' => 'Order not found or access denied']);
    exit;
}

// Update the order status
$stmt = $pdo->prepare('UPDATE orders SET status = ? WHERE id = ?');
$success = $stmt->execute([$status, $order_id]);

if ($success) {
    echo json_encode(['success' => true, 'message' => 'Order status updated successfully.']);
} else {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to update order status']);
}
?>