<?php
header('Content-Type: application/json');

if (!isset($_POST['id'])) {
    echo json_encode([
        "success" => false,
        "message" => "User ID tidak dikirim"
    ]);
    exit;
}

$id = $_POST['id'];

$url = "https://api.jlks.eu.cc/nickname/ff?id=" . urlencode($id);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr  = curl_error($ch);

curl_close($ch);

if ($response === false) {

    $message = 'API tidak merespon';

    if (stripos($curlErr, 'Could not resolve host') !== false) {
        $message = 'Domain API tidak ditemukan';
    } elseif (stripos($curlErr, 'Connection timed out') !== false) {
        $message = 'Koneksi ke API timeout';
    } elseif (stripos($curlErr, 'Failed to connect') !== false) {
        $message = 'Gagal terhubung ke server API';
    }

    echo json_encode([
        'success' => false,
        'message' => $message,
        'error'   => $curlErr
    ]);

    exit;
}

if ($httpCode !== 200) {
    echo json_encode([
        'success' => false,
        'message' => 'API error',
        'http_code' => $httpCode
    ]);

    exit;
}

$datas = json_decode($response, true);

if($datas['success'] == 1) {
    if(isset($datas['name'])) {
        echo json_encode([
            'message' => 'User ID ditemukan',
            'success' => true,
            'user_id'  => $id,
            'nickname' => $datas['name']
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'message' => 'Player ID tidak ditemukan',
            'user_id'  => $id,
            'nickname' => 'UNKNOWN'
        ]);

        exit;
    }
}