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

ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);

include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);

$email = $input['email'] ?? null;

if (!$email) {
    echo json_encode(["success" => false, "message" => "Email is required"]);
    exit;
}

try {
    // Fetch rewards for the user including new fields
    $stmt = $conn->prepare("
        SELECT 
            id, user_email, account_name, account_type, trade_start, trade_end, trade_id, lots_done, reward_amount, created_at 
        FROM lots_reward_users 
        WHERE user_email = ? 
        ORDER BY created_at DESC
    ");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    $rewards = [];
    while ($row = $result->fetch_assoc()) {
        $rewards[] = [
            "id" => $row["id"],
            "email" => $row["user_email"],
            "account_name" => $row["account_name"],
            "account_type" => $row["account_type"],
            "trade_start" => $row["trade_start"],
            "trade_end" => $row["trade_end"],
            "trade_id" => $row["trade_id"],
            "lots_done" => round($row["lots_done"], 2),
            "reward_amount" => round($row["reward_amount"], 2),
            "created_at" => $row["created_at"]
        ];
    }

    if (count($rewards) > 0) {
        echo json_encode([
            "success" => true,
            "email" => $email,
            "total_rewards" => count($rewards),
            "rewards" => $rewards
        ]);
    } else {
        echo json_encode([
            "success" => true,
            "email" => $email,
            "total_rewards" => 0,
            "rewards" => [],
            "message" => "No rewards found for this user"
        ]);
    }

} catch (Throwable $e) {
    echo json_encode([
        "success" => false,
        "error" => "Exception occurred",
        "message" => $e->getMessage(),
        "line" => $e->getLine()
    ]);
}
?>
