<?php

namespace App\Services;

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

class PaymentService
{
    protected $serverKey;
    protected $isProduction;
    protected $snapUrl;
    protected $orderService;

    public function __construct(OrderService $orderService)
    {
        $this->orderService = $orderService;
        $this->serverKey = config('services.midtrans.server_key') ?: env('MIDTRANS_SERVER_KEY', 'SB-Mid-server-placeholder');
        
        $isProd = config('services.midtrans.is_production');
        $this->isProduction = $isProd !== null ? $isProd : env('MIDTRANS_IS_PRODUCTION', false);
        
        $this->snapUrl = $this->isProduction 
            ? 'https://app.midtrans.com/snap/v1/transactions' 
            : 'https://app.sandbox.midtrans.com/snap/v1/transactions';
    }

    public function getSnapToken(Order $order, ?array $customerDetails = null): array
    {
        // Throw exception in development if key is placeholder
        if ($this->serverKey === 'SB-Mid-server-placeholder' || empty($this->serverKey)) {
            throw new \Exception('Koneksi Midtrans gagal: API key belum dikonfigurasi.');
        }

        $authHeader = base64_encode($this->serverKey . ':');

        $items = [];
        $grossAmount = (int)$order->total;
        $merchantOrderId = $order->invoice_number;

        if ($order->payment_type === 'dp' && $order->dp_status === 'unpaid') {
            $grossAmount = (int)$order->dp_amount;
            $items[] = [
                'id' => 'dp_payment',
                'price' => $grossAmount,
                'quantity' => 1,
                'name' => 'Uang Muka (DP) ' . (int)\App\Models\Setting::get('dp_percentage', 50) . '%'
            ];
        } elseif ($order->payment_type === 'dp' && $order->dp_status === 'paid') {
            $grossAmount = (int)$order->remaining_payment;
            $merchantOrderId = $order->invoice_number . '-REMAINING';
            $items[] = [
                'id' => 'remaining_payment',
                'price' => $grossAmount,
                'quantity' => 1,
                'name' => 'Pelunasan Sisa Pembayaran'
            ];
        } else {
            foreach ($order->items as $item) {
                $items[] = [
                    'id' => $item->product_id,
                    'price' => (int)$item->price,
                    'quantity' => $item->qty,
                    'name' => substr($item->product->name, 0, 50)
                ];
            }

            if ($order->shipping_cost > 0) {
                $items[] = [
                    'id' => 'shipping',
                    'price' => (int)$order->shipping_cost,
                    'quantity' => 1,
                    'name' => 'Shipping Cost'
                ];
            }

            if ($order->discount_amount > 0) {
                $items[] = [
                    'id' => 'discount',
                    'price' => -(int)$order->discount_amount,
                    'quantity' => 1,
                    'name' => 'Discount / Voucher'
                ];
            }
        }

        $payload = [
            'transaction_details' => [
                'order_id' => $merchantOrderId,
                'gross_amount' => $grossAmount,
            ],
            'item_details' => $items,
            'customer_details' => [
                'first_name' => $customerDetails['name'] ?? $order->user->name,
                'email' => $customerDetails['email'] ?? $order->user->email,
                'phone' => $customerDetails['phone'] ?? ($order->user->phone ?? ''),
            ]
        ];

        try {
            $response = Http::withoutVerifying()->withHeaders([
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'Authorization' => 'Basic ' . $authHeader,
            ])->post($this->snapUrl, $payload);

            if ($response->successful()) {
                $data = $response->json();
                return [
                    'token' => $data['token'],
                    'redirect_url' => $data['redirect_url'],
                    'mode' => 'midtrans'
                ];
            } else {
                Log::error('Midtrans API Error: ' . $response->body());
                throw new \Exception('Failed to get payment token from Midtrans.');
            }
        } catch (\Exception $e) {
            Log::error('Midtrans Connection Exception: ' . $e->getMessage());
            throw new \Exception('Gagal terhubung dengan gerbang pembayaran Midtrans. ' . $e->getMessage());
        }
    }

    public function handleWebhook(array $notification): bool
    {
        Log::info('Midtrans Webhook received:', $notification);

        $orderId = $notification['order_id'] ?? null;
        $transactionStatus = $notification['transaction_status'] ?? null;
        $paymentType = $notification['payment_type'] ?? '';
        $transactionId = $notification['transaction_id'] ?? null;

        $isRemaining = false;
        if ($orderId && str_ends_with($orderId, '-REMAINING')) {
            $isRemaining = true;
            $orderId = substr($orderId, 0, -10);
        }

        if (!$orderId) {
            return false;
        }

        $order = Order::where('invoice_number', $orderId)->first();
        if (!$order) {
            Log::warning("Order not found for invoice: {$orderId}");
            return false;
        }

        $statusMap = [
            'capture' => 'processing',
            'settlement' => 'processing',
            'pending' => 'waiting_payment',
            'deny' => 'cancelled',
            'expire' => 'cancelled',
            'cancel' => 'cancelled',
        ];

        $newStatus = $statusMap[$transactionStatus] ?? 'pending';

        if ($transactionStatus == 'capture') {
            if (isset($notification['fraud_status']) && $notification['fraud_status'] == 'challenge') {
                $newStatus = 'pending'; // Requires manual challenge approval
            }
        }

        $paymentDetails = [
            'payment_method' => $paymentType,
            'transaction_id' => $transactionId,
            'status' => $transactionStatus,
            'raw_response' => $notification
        ];

        if ($newStatus === 'processing' || $newStatus === 'paid' || $newStatus === 'settlement') {
            $newStatus = 'paid';
        }

        $this->orderService->updateStatus($order, $newStatus, null, $paymentDetails, $isRemaining);
        return true;
    }

    public function getDuitkuInvoice(Order $order, ?array $customerDetails = null, ?string $method = null): array
    {
        $merchantCode = \App\Models\Setting::get('duitku_merchant_code') ?: env('DUITKU_MERCHANT_CODE', '');
        $apiKey = \App\Models\Setting::get('duitku_api_key') ?: env('DUITKU_API_KEY', '');
        $isProduction = (\App\Models\Setting::get('duitku_is_production') ?: env('DUITKU_IS_PRODUCTION', 'false')) === 'true';

        if (empty($merchantCode) || empty($apiKey)) {
            throw new \Exception('Koneksi Duitku gagal: Merchant Code atau API Key belum dikonfigurasi.');
        }

        $paymentAmount = (int)$order->total;
        $merchantOrderId = $order->invoice_number;
        $productDetails = 'Pembayaran Order ' . $order->invoice_number;
        
        $itemDetails = [];

        if ($order->payment_type === 'dp' && $order->dp_status === 'unpaid') {
            $paymentAmount = (int)$order->dp_amount;
            $productDetails = 'DP Order ' . $order->invoice_number;
            $itemDetails[] = [
                'name' => 'Uang Muka (DP) ' . (int)\App\Models\Setting::get('dp_percentage', 50) . '%',
                'price' => $paymentAmount,
                'quantity' => 1
            ];
        } elseif ($order->payment_type === 'dp' && $order->dp_status === 'paid') {
            $paymentAmount = (int)$order->remaining_payment;
            $merchantOrderId = $order->invoice_number . '-REMAINING';
            $productDetails = 'Pelunasan Order ' . $order->invoice_number;
            $itemDetails[] = [
                'name' => 'Pelunasan Sisa Pembayaran',
                'price' => $paymentAmount,
                'quantity' => 1
            ];
        } else {
            foreach ($order->items as $item) {
                $price = $item->product->final_price;
                $itemDetails[] = [
                    'name' => substr($item->product->name, 0, 50),
                    'price' => (int)$price,
                    'quantity' => $item->qty
                ];
            }

            if ($order->shipping_cost > 0) {
                $itemDetails[] = [
                    'name' => 'Ongkos Kirim',
                    'price' => (int)$order->shipping_cost,
                    'quantity' => 1
                ];
            }

            if ($order->discount_amount > 0) {
                $itemDetails[] = [
                    'name' => 'Diskon / Voucher',
                    'price' => -(int)$order->discount_amount,
                    'quantity' => 1
                ];
            }
        }

        $email = $customerDetails['email'] ?? $order->user->email;
        $customerVaName = $customerDetails['name'] ?? $order->user->name;
        
        $signature = md5($merchantCode . $paymentAmount . $merchantOrderId . $apiKey);

        $callbackUrl = route('payment.duitku-callback');
        $returnUrl = route('dashboard.orders');

        $payload = [
            'merchantCode' => $merchantCode,
            'paymentAmount' => $paymentAmount,
            'paymentMethod' => $method ?: '',
            'merchantOrderId' => $merchantOrderId,
            'productDetails' => $productDetails,
            'email' => $email,
            'customerVaName' => $customerVaName,
            'callbackUrl' => $callbackUrl,
            'returnUrl' => $returnUrl,
            'expiryPeriod' => 60,
            'signature' => $signature,
            'itemDetails' => $itemDetails
        ];

        $url = $isProduction 
            ? 'https://api-prod.duitku.com/api/merchant/createInvoice'
            : 'https://api-sandbox.duitku.com/api/merchant/createInvoice';

        try {
            $response = Http::withoutVerifying()->withHeaders([
                'Content-Type' => 'application/json',
            ])->post($url, $payload);

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['statusCode']) && $data['statusCode'] === '00' && !empty($data['paymentUrl'])) {
                    return [
                        'token' => $data['reference'] ?? '',
                        'redirect_url' => $data['paymentUrl'],
                        'mode' => 'duitku'
                    ];
                } else {
                    Log::error('Duitku API Business Error: ', $data);
                    throw new \Exception($data['statusMessage'] ?? 'Failed to get payment url from Duitku.');
                }
            } else {
                Log::error('Duitku API HTTP Error: ' . $response->body());
                throw new \Exception('Failed to connect to Duitku.');
            }
        } catch (\Exception $e) {
            Log::error('Duitku Connection Exception: ' . $e->getMessage());
            throw new \Exception('Gagal terhubung dengan gerbang pembayaran Duitku. ' . $e->getMessage());
        }
    }

    public function handleDuitkuCallback(array $notification): bool
    {
        Log::info('Duitku Webhook received:', $notification);

        $merchantCode = $notification['merchantCode'] ?? '';
        $amount = $notification['amount'] ?? '';
        $merchantOrderId = $notification['merchantOrderId'] ?? '';
        $resultCode = $notification['resultCode'] ?? '';
        $reference = $notification['reference'] ?? '';
        $signature = $notification['signature'] ?? '';

        $myMerchantCode = \App\Models\Setting::get('duitku_merchant_code') ?: env('DUITKU_MERCHANT_CODE', '');
        $apiKey = \App\Models\Setting::get('duitku_api_key') ?: env('DUITKU_API_KEY', '');

        $calcsignature = md5($myMerchantCode . $amount . $merchantOrderId . $apiKey);

        if ($signature !== $calcsignature) {
            Log::warning('Duitku Callback Signature Verification Failed.', [
                'received' => $signature,
                'calculated' => $calcsignature
            ]);
            return false;
        }

        $isRemaining = false;
        if ($merchantOrderId && str_ends_with($merchantOrderId, '-REMAINING')) {
            $isRemaining = true;
            $merchantOrderId = substr($merchantOrderId, 0, -10);
        }

        $order = Order::where('invoice_number', $merchantOrderId)->first();
        if (!$order) {
            Log::warning("Order not found for Duitku callback invoice: {$merchantOrderId}");
            return false;
        }

        if ($resultCode === '00') {
            $newStatus = 'processing';
            $statusLabel = 'settlement';
        } elseif ($resultCode === '02') {
            $newStatus = 'cancelled';
            $statusLabel = 'cancelled';
        } else {
            $newStatus = 'waiting_payment';
            $statusLabel = 'pending';
        }

        $paymentDetails = [
            'payment_method' => 'Duitku (' . ($notification['paymentCode'] ?? 'Gateway') . ')',
            'transaction_id' => $reference,
            'status' => $statusLabel,
            'raw_response' => $notification
        ];

        $this->orderService->updateStatus($order, $newStatus, null, $paymentDetails);
        return true;
    }

    public function getTripayPayment(Order $order, ?string $method = null, ?array $customerDetails = null): array
    {
        $merchantCode = \App\Models\Setting::get('tripay_merchant_code') ?: env('TRIPAY_MERCHANT_CODE', '');
        $apiKey = \App\Models\Setting::get('tripay_api_key') ?: env('TRIPAY_API_KEY', '');
        $privateKey = \App\Models\Setting::get('tripay_private_key') ?: env('TRIPAY_PRIVATE_KEY', '');
        $isProduction = (\App\Models\Setting::get('tripay_is_production') ?: env('TRIPAY_IS_PRODUCTION', 'false')) === 'true';

        if (empty($merchantCode) || empty($apiKey) || empty($privateKey)) {
            throw new \Exception('Koneksi Tripay gagal: Merchant Code, API Key, atau Private Key belum dikonfigurasi.');
        }

        $amount = (int)$order->total;
        $merchantRef = $order->invoice_number;
        
        $orderItems = [];

        if ($order->payment_type === 'dp' && $order->dp_status === 'unpaid') {
            $amount = (int)$order->dp_amount;
            $orderItems[] = [
                'sku' => 'DP',
                'name' => 'Uang Muka (DP) ' . (int)\App\Models\Setting::get('dp_percentage', 50) . '%',
                'price' => $amount,
                'quantity' => 1
            ];
        } elseif ($order->payment_type === 'dp' && $order->dp_status === 'paid') {
            $amount = (int)$order->remaining_payment;
            $merchantRef = $order->invoice_number . '-REMAINING';
            $orderItems[] = [
                'sku' => 'FINAL',
                'name' => 'Pelunasan Sisa Pembayaran',
                'price' => $amount,
                'quantity' => 1
            ];
        } else {
            foreach ($order->items as $item) {
                $price = $item->product->final_price;
                $orderItems[] = [
                    'sku' => $item->product->sku ?: ('SKU-' . $item->product_id),
                    'name' => substr($item->product->name, 0, 50),
                    'price' => (int)$price,
                    'quantity' => $item->qty
                ];
            }

            if ($order->shipping_cost > 0) {
                $orderItems[] = [
                    'sku' => 'SHIPPING',
                    'name' => 'Ongkos Kirim',
                    'price' => (int)$order->shipping_cost,
                    'quantity' => 1
                ];
            }

            if ($order->discount_amount > 0) {
                $orderItems[] = [
                    'sku' => 'DISCOUNT',
                    'name' => 'Diskon / Voucher',
                    'price' => -(int)$order->discount_amount,
                    'quantity' => 1
                ];
            }
        }

        $signature = hash_hmac('sha256', $merchantCode . $merchantRef . $amount, $privateKey);

        $payload = [
            'method' => $method ?: 'QRIS',
            'merchant_ref' => $merchantRef,
            'amount' => $amount,
            'customer_name' => $customerDetails['name'] ?? $order->user->name,
            'customer_email' => $customerDetails['email'] ?? $order->user->email,
            'customer_phone' => $customerDetails['phone'] ?? ($order->user->phone ?: '081234567890'),
            'order_items' => $orderItems,
            'callback_url' => route('payment.tripay-callback'),
            'return_url' => route('dashboard.orders'),
            'expired_time' => (time() + (24 * 60 * 60)), // 24 hours
            'signature' => $signature
        ];

        $url = $isProduction 
            ? 'https://tripay.co.id/api/transaction/create'
            : 'https://tripay.co.id/api-sandbox/transaction/create';

        try {
            $response = Http::withoutVerifying()->withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json',
            ])->post($url, $payload);

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['success']) && $data['success'] && !empty($data['data']['checkout_url'])) {
                    return [
                        'token' => $data['data']['reference'] ?? '',
                        'redirect_url' => $data['data']['checkout_url'],
                        'mode' => 'tripay'
                    ];
                } else {
                    Log::error('Tripay API Business Error: ', $data);
                    throw new \Exception($data['message'] ?? 'Failed to get payment url from Tripay.');
                }
            } else {
                Log::error('Tripay API HTTP Error: ' . $response->body());
                throw new \Exception('Failed to connect to Tripay.');
            }
        } catch (\Exception $e) {
            Log::error('Tripay Connection Exception: ' . $e->getMessage());
            throw new \Exception('Gagal terhubung dengan gerbang pembayaran Tripay. ' . $e->getMessage());
        }
    }

    public function handleTripayCallback(string $rawJson, string $signatureHeader): bool
    {
        $privateKey = \App\Models\Setting::get('tripay_private_key') ?: env('TRIPAY_PRIVATE_KEY', '');
        
        $calcsignature = hash_hmac('sha256', $rawJson, $privateKey);

        if ($signatureHeader !== $calcsignature) {
            Log::warning('Tripay Callback Signature Verification Failed.', [
                'received' => $signatureHeader,
                'calculated' => $calcsignature
            ]);
            return false;
        }

        $notification = json_decode($rawJson, true);
        Log::info('Tripay Webhook verified and parsed:', $notification);

        $merchantRef = $notification['merchant_ref'] ?? '';
        $status = strtoupper($notification['status'] ?? '');
        $reference = $notification['reference'] ?? '';

        $isRemaining = false;
        if ($merchantRef && str_ends_with($merchantRef, '-REMAINING')) {
            $isRemaining = true;
            $merchantRef = substr($merchantRef, 0, -10);
        }

        $order = Order::where('invoice_number', $merchantRef)->first();
        if (!$order) {
            Log::warning("Order not found for Tripay callback invoice: {$merchantRef}");
            return false;
        }

        if ($status === 'PAID') {
            $newStatus = 'processing';
            $statusLabel = 'settlement';
        } elseif (in_array($status, ['FAILED', 'EXPIRED'])) {
            $newStatus = 'cancelled';
            $statusLabel = 'cancelled';
        } else {
            $newStatus = 'waiting_payment';
            $statusLabel = 'pending';
        }

        $paymentDetails = [
            'payment_method' => 'Tripay (' . ($notification['payment_method'] ?? 'Gateway') . ')',
            'transaction_id' => $reference,
            'status' => $statusLabel,
            'raw_response' => $notification
        ];

        if ($newStatus === 'processing' || $newStatus === 'paid' || $newStatus === 'settlement') {
            $newStatus = 'paid';
        }

        $this->orderService->updateStatus($order, $newStatus, null, $paymentDetails, $isRemaining);
        return true;
    }

    /**
     * Get Midtrans payment channels (static list since Midtrans uses Snap popup)
     */
    public function getMidtransPaymentChannels(): array
    {
        return [
            ['code' => 'credit_card', 'name' => 'Kartu Kredit / Debit', 'icon' => 'card', 'description' => 'Visa, Mastercard, JCB'],
            ['code' => 'bca_va', 'name' => 'Virtual Account BCA', 'icon' => 'va', 'description' => 'Transfer via ATM / Mobile Banking BCA'],
            ['code' => 'bni_va', 'name' => 'Virtual Account BNI', 'icon' => 'va', 'description' => 'Transfer via ATM / Mobile Banking BNI'],
            ['code' => 'bri_va', 'name' => 'Virtual Account BRI', 'icon' => 'va', 'description' => 'Transfer via ATM / Mobile Banking BRI'],
            ['code' => 'mandiri_va', 'name' => 'Virtual Account Mandiri', 'icon' => 'va', 'description' => 'Transfer via ATM / Mobile Banking Mandiri'],
            ['code' => 'gopay', 'name' => 'GoPay', 'icon' => 'ewallet', 'description' => 'Bayar menggunakan GoPay'],
            ['code' => 'shopeepay', 'name' => 'ShopeePay', 'icon' => 'ewallet', 'description' => 'Bayar menggunakan ShopeePay'],
            ['code' => 'qris', 'name' => 'QRIS', 'icon' => 'qris', 'description' => 'Scan QR via aplikasi e-wallet manapun'],
            ['code' => 'indomaret', 'name' => 'Indomaret', 'icon' => 'retail', 'description' => 'Bayar di gerai Indomaret'],
            ['code' => 'alfamart', 'name' => 'Alfamart', 'icon' => 'retail', 'description' => 'Bayar di gerai Alfamart'],
        ];
    }

    /**
     * Get Duitku payment channels from their API
     */
    public function getDuitkuPaymentChannels(): array
    {
        $merchantCode = \App\Models\Setting::get('duitku_merchant_code') ?: env('DUITKU_MERCHANT_CODE', '');
        $apiKey = \App\Models\Setting::get('duitku_api_key') ?: env('DUITKU_API_KEY', '');
        $isProduction = (\App\Models\Setting::get('duitku_is_production') ?: env('DUITKU_IS_PRODUCTION', 'false')) === 'true';

        if (empty($merchantCode) || empty($apiKey)) {
            return $this->getDuitkuDefaultChannels();
        }

        $amount = 10000; // Dummy amount for channel listing
        $datetime = date('Y-m-d H:i:s');
        $signature = hash('sha256', $merchantCode . $amount . $datetime . $apiKey);

        $url = $isProduction
            ? 'https://api-prod.duitku.com/api/merchant/paymentmethod/getpaymentmethod'
            : 'https://sandbox.duitku.com/webapi/api/merchant/paymentmethod/getpaymentmethod';

        try {
            $response = Http::withoutVerifying()->withHeaders([
                'Content-Type' => 'application/json',
                'x-duitku-signature' => $signature,
                'x-duitku-timestamp' => $datetime,
                'x-duitku-merchantcode' => $merchantCode,
            ])->post($url, [
                'merchantCode' => $merchantCode,
                'amount' => $amount,
                'dateTime' => $datetime,
                'signature' => $signature,
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['paymentFee']) && is_array($data['paymentFee'])) {
                    $channels = [];
                    foreach ($data['paymentFee'] as $channel) {
                        $channels[] = [
                            'code' => $channel['paymentMethod'] ?? '',
                            'name' => $channel['paymentName'] ?? '',
                            'icon' => $this->mapDuitkuIcon($channel['paymentMethod'] ?? ''),
                            'description' => $channel['paymentDescription'] ?? '',
                            'image' => $channel['paymentImage'] ?? null,
                            'total_fee' => $channel['totalFee'] ?? 0,
                        ];
                    }
                    return $channels;
                }
            }
        } catch (\Exception $e) {
            Log::warning('Failed to fetch Duitku payment channels: ' . $e->getMessage());
        }

        return $this->getDuitkuDefaultChannels();
    }

    private function getDuitkuDefaultChannels(): array
    {
        return [
            ['code' => 'VC', 'name' => 'Kartu Kredit / Debit', 'icon' => 'card', 'description' => 'Visa, Mastercard'],
            ['code' => 'BK', 'name' => 'BCA Virtual Account', 'icon' => 'va', 'description' => 'Transfer via ATM/Mobile Banking BCA'],
            ['code' => 'M2', 'name' => 'BNI Virtual Account', 'icon' => 'va', 'description' => 'Transfer via ATM/Mobile Banking BNI'],
            ['code' => 'AG', 'name' => 'BRI Virtual Account', 'icon' => 'va', 'description' => 'Transfer via ATM/Mobile Banking BRI'],
            ['code' => 'M1', 'name' => 'Mandiri Virtual Account', 'icon' => 'va', 'description' => 'Transfer via ATM/Mobile Banking Mandiri'],
            ['code' => 'OV', 'name' => 'OVO', 'icon' => 'ewallet', 'description' => 'Bayar menggunakan OVO'],
            ['code' => 'SA', 'name' => 'ShopeePay', 'icon' => 'ewallet', 'description' => 'Bayar menggunakan ShopeePay'],
            ['code' => 'LF', 'name' => 'LinkAja', 'icon' => 'ewallet', 'description' => 'Bayar menggunakan LinkAja'],
            ['code' => 'QRIS', 'name' => 'QRIS', 'icon' => 'qris', 'description' => 'Scan QR via semua e-wallet'],
            ['code' => 'FT', 'name' => 'Alfamart / Alfamidi', 'icon' => 'retail', 'description' => 'Bayar di gerai Alfamart/Alfamidi'],
            ['code' => 'IR', 'name' => 'Indomaret', 'icon' => 'retail', 'description' => 'Bayar di gerai Indomaret'],
        ];
    }

    private function mapDuitkuIcon(string $code): string
    {
        $ewallets = ['OV', 'SA', 'LF', 'DA', 'SP', 'SB'];
        $vas = ['BK', 'M2', 'AG', 'M1', 'B1', 'BT', 'A1', 'I1', 'VA'];
        $retail = ['FT', 'IR', 'FT2'];
        if (in_array($code, $ewallets)) return 'ewallet';
        if (in_array($code, $vas)) return 'va';
        if (in_array($code, $retail)) return 'retail';
        if (strpos($code, 'QRIS') !== false) return 'qris';
        if (in_array($code, ['VC', 'DC'])) return 'card';
        return 'other';
    }

    /**
     * Get Tripay payment channels from their API
     */
    public function getTripayPaymentChannels(): array
    {
        $apiKey = \App\Models\Setting::get('tripay_api_key') ?: env('TRIPAY_API_KEY', '');
        $isProduction = (\App\Models\Setting::get('tripay_is_production') ?: env('TRIPAY_IS_PRODUCTION', 'false')) === 'true';

        if (empty($apiKey)) {
            return $this->getTripayDefaultChannels();
        }

        $url = $isProduction
            ? 'https://tripay.co.id/api/merchant/payment-channel'
            : 'https://tripay.co.id/api-sandbox/merchant/payment-channel';

        try {
            $response = Http::withoutVerifying()->withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
            ])->get($url);

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['success']) && $data['success'] && isset($data['data'])) {
                    $channels = [];
                    foreach ($data['data'] as $channel) {
                        if (($channel['active'] ?? false)) {
                            $channels[] = [
                                'code' => $channel['code'] ?? '',
                                'name' => $channel['name'] ?? '',
                                'icon' => $this->mapTripayIcon($channel['group'] ?? ''),
                                'description' => $channel['description'] ?? '',
                                'image' => $channel['icon_url'] ?? null,
                                'group' => $channel['group'] ?? '',
                                'fee_flat' => $channel['fee_flat'] ?? 0,
                                'fee_percent' => $channel['fee_percent'] ?? 0,
                            ];
                        }
                    }
                    return $channels;
                }
            }
        } catch (\Exception $e) {
            Log::warning('Failed to fetch Tripay payment channels: ' . $e->getMessage());
        }

        return $this->getTripayDefaultChannels();
    }

    private function getTripayDefaultChannels(): array
    {
        return [
            ['code' => 'BRIVA', 'name' => 'BRI Virtual Account', 'icon' => 'va', 'description' => 'Transfer ke Virtual Account BRI', 'group' => 'Virtual Account'],
            ['code' => 'BNIVA', 'name' => 'BNI Virtual Account', 'icon' => 'va', 'description' => 'Transfer ke Virtual Account BNI', 'group' => 'Virtual Account'],
            ['code' => 'BCAVA', 'name' => 'BCA Virtual Account', 'icon' => 'va', 'description' => 'Transfer ke Virtual Account BCA', 'group' => 'Virtual Account'],
            ['code' => 'MANDIRIVA', 'name' => 'Mandiri Virtual Account', 'icon' => 'va', 'description' => 'Transfer ke Virtual Account Mandiri', 'group' => 'Virtual Account'],
            ['code' => 'PERMATAVA', 'name' => 'Permata Virtual Account', 'icon' => 'va', 'description' => 'Transfer ke Virtual Account Permata', 'group' => 'Virtual Account'],
            ['code' => 'QRIS', 'name' => 'QRIS', 'icon' => 'qris', 'description' => 'Scan QR Code dengan e-wallet apapun', 'group' => 'QRIS'],
            ['code' => 'QRISC', 'name' => 'QRIS (Customizable)', 'icon' => 'qris', 'description' => 'QRIS untuk semua e-wallet', 'group' => 'QRIS'],
            ['code' => 'ALFAMART', 'name' => 'Alfamart', 'icon' => 'retail', 'description' => 'Bayar di gerai Alfamart/Alfamidi', 'group' => 'Gerai Retail'],
            ['code' => 'INDOMARET', 'name' => 'Indomaret', 'icon' => 'retail', 'description' => 'Bayar di gerai Indomaret', 'group' => 'Gerai Retail'],
        ];
    }

    private function mapTripayIcon(string $group): string
    {
        $map = [
            'Virtual Account' => 'va',
            'E-Wallet' => 'ewallet',
            'QRIS' => 'qris',
            'Gerai Retail' => 'retail',
            'Kartu Kredit' => 'card',
        ];
        return $map[$group] ?? 'other';
    }
}
