<?php
// Include your database connection
require 'config.php'; // This file should set up the $dbh PDO object

// Set CORS headers if needed (optional - adjust for security)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// Define allowed sorting fields
$allowed = [
    'total_margin', 'active_trading', 'total_lots', 'stop_outs',
    'profit_order', 'profitability_score', 'new_users',
    'spread_cost', 'rollover_cost', 'net_deposit',
    'net_withdrawal', 'active_funds'
];

// Get filter from query string, fallback to 'total_margin' if invalid or not set
$filter = isset($_GET['filter']) && in_array($_GET['filter'], $allowed) ? $_GET['filter'] : 'total_margin';

try {
    // Prepare and execute the query using safe ORDER BY (from whitelist)
    $query = "SELECT * FROM broker_rankings ORDER BY $filter DESC LIMIT 50";
    $stmt = $dbh->prepare($query);
    $stmt->execute();
    $brokers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Output JSON result
    echo json_encode([
        'status' => 'success',
        'data' => $brokers
    ]);
} catch (PDOException $e) {
    // Handle DB error
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
    http_response_code(500);
}
?>
