<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include __DIR__ . "/../config.php";

// DEBUG MODE (show exact error)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ==========================================================
// Fetch Top Performing IBs (Commission > $10)
// ==========================================================

$sql = "
    SELECT 
        c.ib_email,
        c.total_commission,
        c.available_commission,
        l.id AS ib_id,
        l.fullname,
        l.first_name,
        l.last_name,
        l.country,
        l.phone,
        l.username,
        l.level
    FROM ib_total_commission AS c
    LEFT JOIN loginusers AS l 
        ON c.ib_email = l.email
    WHERE c.total_commission > 10
    ORDER BY c.total_commission DESC
";

$result = $conn->query($sql);

$topIB = [];

while ($row = $result->fetch_assoc()) {

    $fullName = $row["fullname"];
    if (!$fullName) {
        $fullName = trim($row["first_name"] . " " . $row["last_name"]);
    }

    $topIB[] = [
        "ib_email"             => $row["ib_email"],
        "ib_id"                => $row["ib_id"],
        "full_name"            => $fullName,
        "username"             => $row["username"] ?: "",
        "country"              => $row["country"] ?: "",
        "phone"                => $row["phone"] ?: "",
        "level"                => $row["level"] ?: 0,
        "total_commission"     => (float)$row["total_commission"],
        "available_commission" => (float)$row["available_commission"],
    ];
}

echo json_encode([
    "success" => true,
    "message" => "Top performing IBs fetched successfully.",
    "count"   => count($topIB),
    "data"    => $topIB
]);
