<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class DigiflazzService
{
    protected $username;
    protected $apiKey;
    protected $isProduction;
    protected $baseUrl = 'https://api.digiflazz.com/v1';

    public function __construct()
    {
        $this->username = trim(Setting::where('key', 'digiflazz_username')->first()?->value ?? config('services.digiflazz.username', ''));
        $this->apiKey = trim(Setting::where('key', 'digiflazz_api_key')->first()?->value ?? config('services.digiflazz.api_key', ''));
        
        $isProd = Setting::where('key', 'digiflazz_is_production')->first()?->value ?? config('services.digiflazz.is_production', false);
        $this->isProduction = ($isProd === 'true' || $isProd === true || $isProd === 1 || $isProd === '1');
    }

    /**
     * Cek Saldo Digiflazz (Dengan pencarian otomatis URL yang benar)
     */
    public function checkBalance()
    {
        if (!$this->username || !$this->apiKey) {
            return ['success' => false, 'message' => 'Username atau API Key belum diisi.'];
        }

        $sign = md5($this->username . $this->apiKey . 'depo');
        
        try {
            // Gunakan endpoint dengan tanda strip (-) sesuai dokumentasi resmi terbaru
            $url = 'https://api.digiflazz.com/v1/cek-saldo';
            
            $response = Http::withHeaders([
                'User-Agent' => 'Mozilla/5.0'
            ])->timeout(10)->post($url, [
                'cmd' => 'deposit',
                'username' => $this->username,
                'sign' => $sign
            ]);

            // Jika respons berhasil diterima (Status 200)
            if ($response->successful()) {
                $data = $response->json();
                
                if (isset($data['data']['deposit'])) {
                    return [
                        'success' => true,
                        'balance' => $data['data']['deposit']
                    ];
                }

                $msg = $data['data']['message'] ?? 'Gagal membaca isi saldo.';
                return ['success' => false, 'message' => $msg];
            }

            // Jika status error (seperti 404 atau 500)
            return [
                'success' => false, 
                'message' => 'Server Digiflazz merespon dengan status: ' . $response->status()
            ];

        } catch (\Exception $e) {
            return [
                'success' => false, 
                'message' => 'Koneksi ke Digiflazz gagal: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Ambil Daftar Produk & Harga dari Digiflazz
     */
    public function getPriceList($category = 'Top Up')
    {
        if (!$this->username || !$this->apiKey) return ['success' => false, 'message' => 'Kredensial belum lengkap.'];

        $sign = md5($this->username . $this->apiKey . 'pricelist');

        try {
            $response = Http::withHeaders(['User-Agent' => 'Mozilla/5.0'])
                        ->timeout(30)
                        ->post($this->baseUrl . '/price-list', [
                            'cmd' => 'prepaid',
                            'username' => $this->username,
                            'sign' => $sign
                        ]);
            
            $data = $response->json();

            // Penanganan khusus Kode 83 (Limit 5 Menit)
            if (isset($data['data']['rc']) && $data['data']['rc'] == '83') {
                return [
                    'success' => false, 
                    'message' => 'Batas permintaan tercapai. Harap tunggu 5 menit sebelum mencoba sinkronisasi lagi (Digiflazz Limit).'
                ];
            }

            if (isset($data['data']) && is_array($data['data'])) {
                // Filter berdasarkan kategori jika diinginkan
                $products = collect($data['data']);
                if ($category) {
                    $products = $products->where('category', $category);
                }

                return [
                    'success' => true,
                    'products' => $products->values()->all()
                ];
            }

            return ['success' => false, 'message' => $data['data']['message'] ?? 'Gagal mengambil price list'];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => 'Koneksi gagal: ' . $e->getMessage()];
        }
    }

    /**
     * Buat Transaksi
     */
    public function order($sku, $customerNo, $refId)
    {
        if (!$this->username || !$this->apiKey) return ['success' => false, 'message' => 'Kredensial belum lengkap.'];

        $sign = md5($this->username . $this->apiKey . $refId);

        try {
            $payload = [
                'username' => $this->username,
                'buyer_sku_code' => $sku,
                'customer_no' => $customerNo,
                'ref_id' => $refId,
                'sign' => $sign
            ];

            if (!$this->isProduction) $payload['testing'] = true;

            // Transaksi biasanya stabil di /transaction
            $response = Http::withHeaders(['User-Agent' => 'Mozilla/5.0'])
                        ->timeout(20)
                        ->post($this->baseUrl . '/transaction', $payload);
            
            $data = $response->json();

            if (isset($data['data'])) {
                $status = $data['data']['status'] ?? 'Pending';
                return [
                    'success' => ($status === 'Success' || $status === 'Pending'),
                    'status' => $status,
                    'sn' => $data['data']['sn'] ?? '',
                    'message' => $data['data']['message'] ?? '',
                    'data' => $data['data']
                ];
            }

            return ['success' => false, 'message' => $data['data']['message'] ?? 'Gagal memproses pesanan'];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => 'Koneksi gagal: ' . $e->getMessage()];
        }
    }
}
