<?php

namespace App\Services;

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

class PGAVipService
{
    private $baseUrl;
    private $uuid;
    private $username;

    public function __construct()
    {
        $this->baseUrl = config('services.pga_vip.base_url');
        $this->uuid = config('services.pga_vip.uuid');
        $this->username = config('services.pga_vip.username');

        // Debug sementara
        Log::info('🧪 PGA CONFIG LOADED', [
            'base_url' => $this->baseUrl,
            'uuid' => $this->uuid,
            'username' => $this->username,
        ]);
    }

    public function generateQR($amount, $customRef = null, $expire = 1200)
    {
        $feePercent = 0.03;

        $amount = (int) $amount;
        $fee = ceil($amount * $feePercent);
        $total = $amount + $fee;

        $trx_id = $customRef ?? (
            'VIP' . time() . strtoupper(bin2hex(random_bytes(4)))
        );

        $payload = [
            'username'   => $this->username,
            'amount'     => $total,
            'uuid'       => $this->uuid,
            'expire'     => $expire,
            'custom_ref' => $trx_id,
        ];

        try {

            // Generate QR
            $response = Http::timeout(10)
                ->connectTimeout(3)
                ->retry(1, 200)
                ->asForm()
                ->post($this->baseUrl . '/generate', $payload);

            $json = $response->json();

            Log::info('🧠 PGA RAW JSON', [
                'raw' => $response->body()
            ]);

            Log::info('🟦 PGA Generate QR Payload', $payload);

            Log::info('🟩 PGA Generate QR Response', $json);

            if (!isset($json['status']) || $json['status'] !== true) {

                return [
                    'status' => false,
                    'error' => $json['error'] ?? 'Gagal generate QR',
                    'payload' => $payload,
                ];
            }

            // Ambil data QR
            $data = $json['data'] ?? null;

            $qrString = null;
            $qrImageBase64 = null;

            // Jika string langsung
            if (is_string($data) && str_starts_with($data, '000201')) {

                $qrString = $data;
            }

            // Jika array
            elseif (is_array($data)) {

                $qrString = $data['qris_content']
                    ?? $data['data']
                    ?? null;

                $qrImageBase64 = $data['qris_image'] ?? null;
            }

            // Jika object
            elseif (is_object($data)) {

                $qrString = $data->qris_content ?? null;
                $qrImageBase64 = $data->qris_image ?? null;
            }

            // Fallback fetch QR
            if (empty($qrString) && empty($qrImageBase64)) {

                try {

                    $qrFetch = Http::timeout(10)
                        ->connectTimeout(3)
                        ->retry(1, 200)
                        ->asForm()
                        ->post($this->baseUrl . '/qris', [
                            'uuid' => $this->uuid,
                            'custom_ref' => $trx_id,
                        ])
                        ->json();

                    $qrData = $qrFetch['data'] ?? null;

                    if (is_array($qrData)) {

                        $qrString = $qrData['qris_content']
                            ?? $qrData['data']
                            ?? null;

                        $qrImageBase64 = $qrData['qris_image'] ?? null;
                    }

                    elseif (is_string($qrData)) {

                        $qrString = $qrData;
                    }

                } catch (\Throwable $e) {

                    Log::error('❌ PGA QR FETCH ERROR', [
                        'message' => $e->getMessage()
                    ]);

                    return [
                        'status' => false,
                        'error' => $e->getMessage()
                    ];
                }
            }

            // Tentukan QR final
            if ($qrImageBase64) {

                $qrUrl = 'data:image/png;base64,' . $qrImageBase64;
            }

            elseif ($qrString) {

                $qrUrl =
                    'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' .
                    urlencode($qrString);
            }

            else {

                Log::warning('⚠️ QRIS kosong walau status true', [
                    'response' => $json
                ]);

                return [
                    'status' => false,
                    'error' => 'QRIS kosong'
                ];
            }

            Log::info('🧩 PGA QRIS String Final', [
                'qr' => substr($qrString, 0, 80)
            ]);

            return [
                'status' => true,
                'trx_id' => $trx_id,
                'fee' => $fee,
                'total' => $total,
                'qr_string' => $qrString,
                'qr_url' => $qrUrl,
            ];

        } catch (\Throwable $e) {

            Log::error('❌ PGA Generate Error', [
                'message' => $e->getMessage()
            ]);

            return [
                'status' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    public function checkStatus($trxId)
    {
        try {

            $resp = Http::timeout(8)
                ->connectTimeout(3)
                ->retry(1, 200)
                ->asForm()
                ->post(
                    $this->baseUrl . "/checkstatus/v2/{$trxId}",
                    [
                        'uuid' => $this->uuid,
                    ]
                );

            return $resp->json();

        } catch (\Throwable $e) {

            return [
                'status' => false,
                'error' => $e->getMessage()
            ];
        }
    }
}