<?php

namespace App\Services;

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

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

    public function __construct()
    {
        $this->apiKey = config('services.vipreseller.api_key');
        $this->apiId = config('services.vipreseller.api_id');
        $this->apiUrl = config('services.vipreseller.api_url');
    }

    private function generateSignature()
    {
        return md5($this->apiId . $this->apiKey);
    }

    public function fetchGameProducts($filterGame = null, $filterStatus = 'available')
    {
        for ($attempt = 1; $attempt <= 3; $attempt++) {
            try {
                $signature = $this->generateSignature();

                $params = [
                    'key' => $this->apiKey,
                    'sign' => $signature,
                    'type' => 'services',
                ];

                if ($filterGame) {
                    $params['filter_game'] = $filterGame;
                }

                if ($filterStatus) {
                    $params['filter_status'] = $filterStatus;
                }

                Log::info("🔍 VIP Reseller API Attempt #{$attempt}");

                $response = Http::asForm()
                    ->timeout(60)
                    ->post($this->apiUrl . '/game-feature', $params);

                if ($response->successful()) {
                    $data = $response->json();

                    if (($data['result'] ?? false) && !empty($data['data'])) {
                        Log::info('✅ VIP Reseller API Success', [
                            'total_products' => count($data['data'])
                        ]);
                        return $data['data'];
                    }

                    Log::warning('⚠️ VIP Reseller API returned empty or false result', [
                        'response' => $data
                    ]);
                } else {
                    Log::warning('⚠️ VIP Reseller HTTP Error', [
                        'status' => $response->status()
                    ]);
                }

            } catch (\Exception $e) {
                Log::warning('⚠️ VIP Reseller Exception', [
                    'message' => $e->getMessage()
                ]);
            }

            sleep(2);
        }

        Log::error('❌ VIP Reseller API failed after 3 attempts');
        return [];
    }

    public function getAvailableGames()
    {
        $products = $this->fetchGameProducts();
        
        $games = collect($products)->pluck('game')->unique()->filter()->values();
        
        return $games;
    }

    public function createOrder($code, $target, $serverOrZone = null)
    {
        try {
            $signature = $this->generateSignature();

            $params = [
                'key' => $this->apiKey,
                'sign' => $signature,
                'type' => 'order',
                'service' => $code,
                'data_no' => $target,
            ];

            if ($serverOrZone) {
                $params['data_zone'] = $serverOrZone;
            }

            Log::info('📦 Creating VIP Reseller order...', [
                'code' => $code,
                'target' => $target,
            ]);

            $response = Http::timeout(30)->post($this->apiUrl . '/game-feature', $params);

            if ($response->successful()) {
                $data = $response->json();
                
                Log::info('VIP Reseller Order Response', ['data' => $data]);
                
                return [
                    'success' => $data['result'] ?? false,
                    'data' => $data['data'] ?? null,
                    'message' => $data['message'] ?? 'Order created',
                ];
            }

            return [
                'success' => false,
                'message' => 'HTTP Error: ' . $response->status(),
            ];

        } catch (\Exception $e) {
            Log::error('VIP Reseller Order Exception: ' . $e->getMessage());
            
            return [
                'success' => false,
                'message' => 'Exception: ' . $e->getMessage(),
            ];
        }
    }

    public function checkOrderStatus($trxId)
    {
        try {
            $signature = $this->generateSignature();

            $params = [
                'key' => $this->apiKey,
                'sign' => $signature,
                'type' => 'status',
                'trxid' => $trxId,
            ];

            $response = Http::timeout(30)->post($this->apiUrl . '/game-feature', $params);

            if ($response->successful()) {
                $data = $response->json();
                
                return [
                    'success' => $data['result'] ?? false,
                    'data' => $data['data'] ?? null,
                ];
            }

            return ['success' => false];

        } catch (\Exception $e) {
            Log::error('VIP Reseller Status Check Exception: ' . $e->getMessage());
            return ['success' => false];
        }
    }
}