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

$order_id = $_GET['order_id'] ?? null;
$token = $_GET['token'] ?? null;
$user_id = $_SESSION['user_id'] ?? null;

if (!$order_id) {
    echo json_encode(['error' => 'Order ID not specified']);
    exit;
}

$status = null;

try {
    $pdo = db();
    
    if ($user_id) {
        $stmt = $pdo->prepare("SELECT status FROM orders WHERE id = ? AND user_id = ?");
        $stmt->execute([$order_id, $user_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) {
            $status = $result['status'];
        }
    } elseif ($token) {
        $stmt = $pdo->prepare("SELECT status FROM orders WHERE id = ? AND guest_token = ?");
        $stmt->execute([$order_id, $token]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) {
            $status = $result['status'];
        }
    }

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

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection error']);
}
