<?php
session_start();
require_once '../config.php';
use App\classes\AdminAuth;

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Check if order_id is provided
if (!isset($_GET['order_id']) || !is_numeric($_GET['order_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
    exit;
}

$order_id = intval($_GET['order_id']);

try {
    // Get agent order details
    $order_stmt = $conn->prepare("
        SELECT 
            ao.*,
            a.username as agent_username,
            a.uniqueID as agent_unique_id
        FROM agent_orders ao
        LEFT JOIN agents a ON ao.agent_id = a.id
        WHERE ao.id = ?
    ");
    $order_stmt->bind_param("i", $order_id);
    $order_stmt->execute();
    $order_result = $order_stmt->get_result();
    
    if ($order_result->num_rows === 0) {
        echo json_encode([
            'success' => false, 
            'message' => 'Agent order not found',
            'history' => []
        ]);
        exit;
    }
    
    $order = $order_result->fetch_assoc();
    $order_stmt->close();
    
    // For agent orders, we'll create a simple history based on the order data
    // since they don't have the enhanced status tracking
    $history = [
        [
            'old_status' => null,
            'new_status' => $order['status'],
            'change_reason' => 'Order created',
            'changed_by' => 'system',
            'external_data' => null,
            'created_at' => $order['created_at']
        ]
    ];
    
    // If there are any updates, we could add them here
    // For now, agent orders have basic tracking only
    
    echo json_encode([
        'success' => true,
        'order' => $order,
        'history' => $history
    ]);
    
} catch (Exception $e) {
    error_log("Error getting agent order history: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Database error',
        'history' => []
    ]);
}
?>
