<?php
header("Content-Type: application/json; charset=UTF-8");
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 config (DB connection)
require_once __DIR__ . "/config.php";

// Fetch data
$sql = "SELECT id, ib_email, total_commission, available_commission, updated_at 
        FROM ib_total_commission 
        ORDER BY id DESC";

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

if (!$result) {
    echo json_encode([
        "status" => false,
        "message" => "Database query failed",
        "error" => $conn->error
    ]);
    exit;
}

$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = [
        "id" => (int)$row["id"],
        "ib_email" => $row["ib_email"],
        "total_commission" => $row["total_commission"],
        "available_commission" => $row["available_commission"],
        "updated_at" => $row["updated_at"]
    ];
}

echo json_encode([
    "status" => true,
    "message" => "IB Commission history fetched successfully",
    "data" => $data
], JSON_PRETTY_PRINT);

$conn->close();
?>
