<?php
header('Content-Type: application/json');
session_start();
require_once __DIR__ . '/../db/config.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'User not authenticated']);
    exit;
}

// Check if order_id is provided
if (!isset($_GET['order_id'])) {
    echo json_encode(['error' => 'Order ID not specified']);
    exit;
}

$order_id = $_GET['order_id'];
$user_id = $_SESSION['user_id'];

try {
    $pdo = db();

    // Fetch the order status, ensuring the order belongs to the logged-in user
    $stmt = $pdo->prepare("SELECT status FROM orders WHERE id = ? AND user_id = ?");
    $stmt->execute([$order_id, $user_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($order) {
        echo json_encode(['status' => ucwords($order['status'])]);
    } else {
        echo json_encode(['error' => 'Order not found or permission denied']);
    }
} catch (PDOException $e) {
    echo json_encode(['error' => 'Database error']);
}
?>