<?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 {
    // Check if order_status_history table exists
    $result = mysqli_query($conn, "SHOW TABLES LIKE 'order_status_history'");
    if (!$result || mysqli_num_rows($result) === 0) {
        echo json_encode([
            'success' => false, 
            'message' => 'Status tracking not set up',
            'history' => []
        ]);
        exit;
    }
    
    // Get order details
    $order_stmt = $conn->prepare("
        SELECT 
            o.*,
            a.username as agent_username,
            a.uniqueID as agent_unique_id
        FROM orders o
        LEFT JOIN agents a ON o.user_id = a.id
        WHERE o.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' => 'Order not found',
            'history' => []
        ]);
        exit;
    }
    
    $order = $order_result->fetch_assoc();
    $order_stmt->close();
    
    // Get status history
    $history_stmt = $conn->prepare("
        SELECT 
            old_status,
            new_status,
            change_reason,
            changed_by,
            external_data,
            created_at
        FROM order_status_history 
        WHERE order_id = ? 
        ORDER BY created_at ASC
    ");
    $history_stmt->bind_param("i", $order_id);
    $history_stmt->execute();
    $history_result = $history_stmt->get_result();
    
    $history = [];
    while ($row = $history_result->fetch_assoc()) {
        $history[] = [
            'old_status' => $row['old_status'],
            'new_status' => $row['new_status'],
            'change_reason' => $row['change_reason'],
            'changed_by' => $row['changed_by'],
            'external_data' => $row['external_data'] ? json_decode($row['external_data'], true) : null,
            'created_at' => $row['created_at']
        ];
    }
    $history_stmt->close();
    
    echo json_encode([
        'success' => true,
        'order' => $order,
        'history' => $history
    ]);
    
} catch (Exception $e) {
    error_log("Error getting order history: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Database error',
        'history' => []
    ]);
}
?>
