<?php
include 'config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = '';

    if (isset($_GET['username'])) {
        $username = trim($_GET['username']);
    } elseif (isset($_POST['username'])) {
        $username = trim($_POST['username']);
    }

    if (empty($username)) {
        echo json_encode([
            "status" => "error",
            "message" => "Username is required"
        ]);
        $conn->close();
        exit;
    }

    $stmt = $conn->prepare("SELECT total_refer, refer_earn FROM users WHERE username = ? LIMIT 1");
    if (!$stmt) {
        echo json_encode([
            "status" => "error",
            "message" => "Database prepare failed"
        ]);
        $conn->close();
        exit;
    }

    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();

        echo json_encode([
            "status" => "success",
            "message" => "Data found",
            "totalRefer" => $row["total_refer"],
            "totalEran" => $row["refer_earn"],
            "data" => [
                "total_refer" => $row["total_refer"],
                "refer_earn" => $row["refer_earn"]
            ]
        ]);
    } else {
        echo json_encode([
            "status" => "error",
            "message" => "User not found",
            "totalRefer" => 0,
            "totalEran" => 0
        ]);
    }

    $stmt->close();
    $conn->close();

} else {
    echo json_encode([
        "status" => "error",
        "message" => "Invalid Request Method"
    ]);
}
?>