<?php
error_reporting(0);
$db = new SQLite3('./.db.db');

if (isset($_GET['username'])){
    $username=$_GET['username'];
    $password=$_GET['password'];
    $getaction=$_GET['action'];
} else if (isset($_POST['username'])){
    $username=$_POST['username'];
    $password=$_POST['password'];
    $getaction=$_POST['action'];
}

if ($getaction !== null) {
    echo "The \$getaction variable is not null.";
    $maincall = "/player_api.php?username={$username}&password={$password}&action={$getaction}";
} else {
    $maincall = "/player_api.php?username={$username}&password={$password}";
}

function call_api($api_link){
    $returnData = "0";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_link);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    $result = json_decode(curl_exec($ch));
    if (!empty($result)) {
        $returndata = $result;
        return ["result" => "success", "data" => $returndata];
    }
}

$res = $db->query('SELECT * FROM dns');
$activeDnsFound = false;

while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
    $dns = $row['url'];
    $api_link = $dns . $maincall;
    $api_req = call_api($api_link);
    $result = $api_req;
    if ($result["result"] == "success") {
        if (isset($result["data"]->user_info->auth)) {
            if ($result["data"]->user_info->auth != 0) {
                if ($result["data"]->user_info->status == "Active") {
                    $response = [
                        "status" => "success",
                        "data" => $dns
                    ];
                    echo json_encode($response);
                    $activeDnsFound = true;
                    break; // Exit the loop when an active DNS is found
                }
            } else {
                /*echo "Error for DNS: $dns";*/
            }
        }
    } else {
       /* echo "Error for DNS: $dns";*/
    }
}

// If no "Active" status DNS is found, echo an appropriate message
if (!$activeDnsFound) {
    $response_error = [
                        "status" => "unsuccess",
                        "data" => "Invalid username/password or account has expired."
                    ];
                    echo json_encode($response_error);
}
?>

