<?php
// ajax/check-player-id.php
require_once '../common/config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $playerId = sanitize($_POST['player_id'] ?? '');
    $gameId = (int)($_POST['game_id'] ?? 0);
    
    if (empty($playerId)) {
        echo json_encode(['status' => 'error', 'message' => 'Please enter Player ID']);
        exit;
    }

    $gameStmt = $pdo->prepare("SELECT id, name, slug, type FROM games WHERE id=? AND status='active'");
    $gameStmt->execute([$gameId]);
    $game = $gameStmt->fetch();
    $identity = strtolower(($game['slug'] ?? '') . ' ' . ($game['name'] ?? ''));
    $isFreeFire = ($game && ($game['type'] ?? '') === 'uid' && preg_match('/free\s*fire|(^|[-\s])ff([-\s]|$)|uid-topup-bd|weekly-monthly|weekly-lite|level-up-pass-bd/i', $identity));
    if (!$isFreeFire) {
        echo json_encode(['status' => 'error', 'message' => 'এই প্রোডাক্টে Player Name Check প্রযোজ্য নয়।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (!preg_match('/^[A-Za-z0-9_\-]{5,30}$/', $playerId)) {
        echo json_encode(['status' => 'error', 'message' => 'সঠিক Player ID দিন।'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $template = trim((string)getSetting($pdo, 'player_name_api_url', 'http://ixbd.qd.je/ff.php?uid={uid}'));
    if (!preg_match('#^https?://#i', $template)) {
        echo json_encode(['status' => 'error', 'message' => 'Player Name API সেটিং সঠিক নয়।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $hasUidPlaceholder = strpos($template, '{uid}') !== false;
    $url = $hasUidPlaceholder ? str_replace('{uid}', rawurlencode($playerId), $template) : $template;
    $body = false;
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        $headers = ['Accept: application/json', 'User-Agent: MangoTopUp/1.0', 'Origin: https://mangotopup.com', 'Referer: https://mangotopup.com/'];
        $options = [CURLOPT_RETURNTRANSFER=>true, CURLOPT_FOLLOWLOCATION=>true, CURLOPT_CONNECTTIMEOUT=>5, CURLOPT_TIMEOUT=>10, CURLOPT_HTTPHEADER=>$headers, CURLOPT_USERAGENT=>'MangoTopUp/1.0'];
        if (!$hasUidPlaceholder) {
            $options[CURLOPT_POST] = true;
            $options[CURLOPT_POSTFIELDS] = json_encode(['playerid'=>$playerId]);
            $headers[] = 'Content-Type: application/json';
            $options[CURLOPT_HTTPHEADER] = $headers;
        }
        curl_setopt_array($ch, $options);
        $body = curl_exec($ch);
        curl_close($ch);
    } else {
        $context = ['timeout'=>10, 'header'=>"Accept: application/json\r\nUser-Agent: MangoTopUp/1.0\r\nOrigin: https://mangotopup.com\r\nReferer: https://mangotopup.com/\r\n"];
        if (!$hasUidPlaceholder) { $context['method']='POST'; $context['header'] .= "Content-Type: application/json\r\n"; $context['content']=json_encode(['playerid'=>$playerId]); }
        $body = @file_get_contents($url, false, stream_context_create(['http'=>$context]));
    }
    $data = is_string($body) ? json_decode($body, true) : null;
    $name = $data['data']['username'] ?? $data['username'] ?? $data['data']['name'] ?? $data['name'] ?? '';
    if (($data['status'] ?? true) && is_string($name) && trim($name) !== '') {
        echo json_encode(['status'=>'success','player_name'=>trim($name),'message'=>'Player Name পাওয়া গেছে।'], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(['status'=>'error','message'=>'এই Player ID-এর নাম পাওয়া যায়নি।'], JSON_UNESCAPED_UNICODE);
    }
}
?>
