<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class NicknameCheckService
{
    private $apiKey;
    private $apiId;
    private $apiUrl;

    private $gameCodeMap = [
        'mobile-legends' => 'mobile-legends',
        'ml' => 'mobile-legends',
        'mla' => 'mobile-legends',
        'mlb' => 'mobile-legends',
        'free-fire' => 'free-fire',
        'ff' => 'free-fire',
        'free-fire-max' => 'free-fire-max',
        'ffm' => 'free-fire-max',
        'genshin-impact' => 'genshin-impact',
        'gi' => 'genshin-impact',
        'pubg-mobile' => 'pubg-mobile',
        'pubg' => 'pubg-mobile',
    ];

    public function __construct()
    {
        $this->apiKey = env('VIPRESELLER_API_KEY');
        $this->apiId = env('VIPRESELLER_API_ID');
        $this->apiUrl = env('VIPRESELLER_API_URL', 'https://vip-reseller.co.id/api');
    }

    private function normalizeGameCode($gameCode)
    {
        $code = strtolower(trim($gameCode));
        
        if (isset($this->gameCodeMap[$code])) {
            return $this->gameCodeMap[$code];
        }
        
        if (preg_match('/^([a-z\-]+)/', $code, $matches)) {
            $prefix = $matches[1];
            if (isset($this->gameCodeMap[$prefix])) {
                return $this->gameCodeMap[$prefix];
            }
        }
        
        return $code;
    }

    public function supportsNicknameCheck($gameCode)
    {
        $normalized = $this->normalizeGameCode($gameCode);
        
        $supported = [
            'mobile-legends',
            'free-fire',
            'free-fire-max',
            'genshin-impact',
            'pubg-mobile',
        ];
        
        return in_array($normalized, $supported);
    }

    public function checkNickname($gameCode, $userId, $zoneId = null, $server = null)
    {
        try {
            $normalized = $this->normalizeGameCode($gameCode);
            
            Log::info('🎮 Nickname Check Request', [
                'original_code' => $gameCode,
                'normalized_code' => $normalized,
                'user_id' => $userId,
                'zone_id' => $zoneId,
                'server' => $server,
            ]);
            
            $sign = md5($this->apiId . $this->apiKey);
            
            $data = [
                'key' => $this->apiKey,
                'sign' => $sign,
                'type' => 'get-nickname',
                'code' => $normalized,
                'target' => trim($userId),
            ];
            
            // ✅ FIX: Handle additional_target properly
            $additionalTarget = null;
            
            if (!empty($server) && is_string($server)) {
                $additionalTarget = trim($server);
            } elseif (!empty($zoneId) && is_string($zoneId)) {
                $additionalTarget = trim($zoneId);
            }
            
            if ($additionalTarget) {
                $data['additional_target'] = $additionalTarget;
            }
            
            Log::info('📤 Sending to VIP Reseller:', $data);
            
            $response = Http::asForm()
                ->timeout(15)
                ->post($this->apiUrl . '/game-feature', $data);
            
            if (!$response->successful()) {
                Log::error('❌ VIP API HTTP Error', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                
                return [
                    'success' => false,
                    'message' => 'Gagal terhubung ke server',
                ];
            }
            
            $rawBody = $response->body();
            
            Log::info('📥 VIP API Raw Body:', [
                'body' => substr($rawBody, 0, 500),
            ]);
            
            try {
                $resultRaw = json_decode($rawBody, true);
                
                if (json_last_error() !== JSON_ERROR_NONE) {
                    throw new \Exception('JSON Parse Error: ' . json_last_error_msg());
                }
                
            } catch (\Exception $e) {
                Log::error('❌ JSON Parse Failed:', [
                    'error' => $e->getMessage(),
                ]);
                
                return [
                    'success' => false,
                    'message' => 'Response tidak valid',
                ];
            }
            
            $result = $this->extractResult($resultRaw);
            
            Log::info('🎯 Extracted Result:', $result);
            
            if (isset($result['result']) && $result['result'] === true) {
                $nickname = $result['data'] ?? 'Unknown';
                
                Log::info('✅ Nickname Found:', ['nickname' => $nickname]);
                
                return [
                    'success' => true,
                    'nickname' => $nickname,
                    'user_id' => $userId,
                    'zone_id' => $zoneId,
                ];
            }
            
            $errorMessage = $result['message'] ?? 'ID tidak ditemukan';
            
            Log::warning('⚠️ Nickname Check Failed:', ['message' => $errorMessage]);
            
            return [
                'success' => false,
                'message' => $errorMessage,
            ];
            
        } catch (\Exception $e) {
            Log::error('❌ Exception:', [
                'error' => $e->getMessage(),
                'line' => $e->getLine(),
            ]);
            
            return [
                'success' => false,
                'message' => 'Sistem error',
            ];
        }
    }

    private function extractResult($data)
    {
        if (is_array($data) && isset($data['result'])) {
            return $data;
        }
        
        if (is_array($data) && isset($data[0]) && is_array($data[0]) && isset($data[0]['result'])) {
            return $data[0];
        }
        
        if (is_array($data) && isset($data[0]) && is_array($data[0]) && isset($data[0][0]) && is_array($data[0][0])) {
            return $data[0][0];
        }
        
        return $data;
    }
}