<?php

namespace App\Services;

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

class VipResellerPpobService
{
    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');
    }

    /**
     * Generate signature for VIP Reseller API
     */
    private function generateSignature()
    {
        return md5($this->apiId . $this->apiKey);
    }

    /**
     * Fetch all PPOB products (pulsa, data, token listrik, etc)
     */
    public function fetchPpobProducts($filterType = null)
    {
        try {
            $signature = $this->generateSignature();

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

            // Add optional filter
            if ($filterType) {
                $params['filter_type'] = $filterType; // pulsa, data, token, etc
            }

            Log::info('🔍 Calling VIP Reseller PPOB API...', [
                'url' => $this->apiUrl . '/prepaid',
            ]);

            // IMPORTANT: Use asForm() for form-data
            $response = Http::asForm()->timeout(60)->post($this->apiUrl . '/prepaid', $params);

            if ($response->successful()) {
                $data = $response->json();
                
                if ($data['result'] ?? false) {
                    Log::info('✅ VIP Reseller PPOB API Success', [
                        'total_products' => count($data['data'] ?? [])
                    ]);
                    return $data['data'] ?? [];
                }

                Log::error('VIP Reseller PPOB API Error', ['response' => $data]);
                return [];
            }

            Log::error('VIP Reseller PPOB HTTP Error', [
                'status' => $response->status(),
                'body' => $response->body()
            ]);
            return [];

        } catch (\Exception $e) {
            Log::error('VIP Reseller PPOB Exception: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * Get available PPOB operators
     */
    public function getAvailableOperators()
    {
        $products = $this->fetchPpobProducts();
        
        // Group by operator
        $operators = collect($products)
            ->groupBy('brand')
            ->map(function($items, $brand) {
                return [
                    'brand' => $brand,
                    'total_products' => count($items),
                ];
            })
            ->values();
        
        return $operators;
    }

    /**
     * Create PPOB transaction (order)
     */
    public function createOrder($serviceCode, $phoneNumber)
    {
        try {
            $signature = $this->generateSignature();

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

            Log::info('📦 Creating VIP Reseller PPOB order...', [
                'service' => $serviceCode,
                'phone' => $phoneNumber,
            ]);

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

            if ($response->successful()) {
                $data = $response->json();
                
                Log::info('VIP Reseller PPOB 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 PPOB Order Exception: ' . $e->getMessage());
            
            return [
                'success' => false,
                'message' => 'Exception: ' . $e->getMessage(),
            ];
        }
    }

    /**
     * Check order status
     */
    public function checkOrderStatus($trxId)
    {
        try {
            $signature = $this->generateSignature();

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

            $response = Http::asForm()->timeout(30)->post($this->apiUrl . '/prepaid', $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 PPOB Status Check Exception: ' . $e->getMessage());
            return ['success' => false];
        }
    }
}
