<?php
require'../config.php';
if(isset($_POST['no']) && isset($_POST['key']) && isset($_POST['name']))
{
    $userid = $_POST['no'];
    $zoneid = $_POST['server'];
    $game = $_POST['name'];
    $key = $_POST['key'];
    $r_api = $db->query("SELECT * FROM users WHERE api_key='$key'")->fetch_assoc();
    $user = $r_api['username'];
    if($r_api['api_key'] == false) die(json_encode([
        'result' => 404,
        'message' => 'Invalid Api Key'
        ], JSON_PRETTY_PRINT));
    
    if($r_api['saldo'] < $value_succ) die(json_encode([
            'result' => 404,
            'message' => 'Saldo Kamu Tidak Mencukupi '.$r_api['saldo']
        ],JSON_PRETTY_PRINT));
    
    if(check_ip($client_ip, $r_api['ip_static']) == false) die(json_encode([
        'result' => 404,
        'message' => 'IP Anda '.$client_ip.' Tidak Dikenali'
        ],JSON_PRETTY_PRINT));
    
    if($user == false) die(json_encode([
        'result' => 404,
        'message' => 'Username Not Found'
        ],JSON_PRETTY_PRINT));
    
    if(isset($_POST['server'])){
        $url = 'https://api.lookitstore.id/'.$game.'?no='.$userid.'&server='.$zoneid;
    }else{
        $url = 'https://api.lookitstore.id/'.$game.'?no='.$userid;
    }
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
));

    $resp = curl_exec($curl);
    $print = json_decode($resp, true);
    if($print['result'] == 200) {
        $value_succ = '30';
        $db->query("UPDATE users SET saldo=saldo-$value_succ WHERE api_key='$key' AND username='$user'");
        die(json_encode([
            'result' => 200,
            'data' => [
                'nickname' => $print['data']['nickname'],
            ],
            'message' => 'Nickname Berhasil Didapatkan'
            ],JSON_PRETTY_PRINT));
    } else {
        $value_fail = '15';
        $db->query("UPDATE users SET saldo=saldo-$value_fail WHERE api_key='$key' AND username='$user'");
        die(json_encode([
            'result' => 400,
            'message' => 'Invalid ID'
            ],JSON_PRETTY_PRINT));
    }
} else {
    die(json_encode([
        'result' => 400,
        'message' => 'Missing Parameter'
        ],JSON_PRETTY_PRINT));
}