<?php

namespace App\Helpers;

use App\Models\Setting;

class PaymentGateway
{
    public static function isEnabled($gateway = null)
    {
        $setting = new Setting();
        $globalEnabled = $setting->getValue('payment_gateway_enabled', 'false');
        if ($globalEnabled !== 'true') return false;
        if ($gateway) {
            $gwEnabled = $setting->getValue($gateway . '_enabled', 'false');
            return $gwEnabled === 'true';
        }
        return true;
    }

    public static function getAvailableGateways()
    {
        $gateways = [];
        if (self::isEnabled('paystack')) $gateways[] = 'paystack';
        if (self::isEnabled('hubtel')) $gateways[] = 'hubtel';
        return $gateways;
    }

    public static function initPaystackPayment($email, $amount, $reference, $callbackUrl)
    {
        $setting = new Setting();
        $secretKey = $setting->getValue('paystack_secret_key', '');
        if (!$secretKey) {
            return ['success' => false, 'message' => 'Paystack not configured'];
        }

        $url = 'https://api.paystack.co/transaction/initialize';
        $fields = [
            'email' => $email,
            'amount' => round($amount * 100),
            'reference' => $reference,
            'callback_url' => $callbackUrl,
        ];

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($fields),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $secretKey,
                'Content-Type: application/json',
                'Cache-Control: no-cache',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_TIMEOUT => 30,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($curlError) {
            return ['success' => false, 'message' => 'cURL error: ' . $curlError];
        }

        $data = json_decode($response);
        if (!$data || !$data->status) {
            $msg = $data->message ?? 'Paystack initialization failed';
            return ['success' => false, 'message' => $msg];
        }

        return [
            'success' => true,
            'authorization_url' => $data->data->authorization_url,
            'access_code' => $data->data->access_code,
            'reference' => $data->data->reference,
        ];
    }

    public static function verifyPaystackPayment($reference)
    {
        $setting = new Setting();
        $secretKey = $setting->getValue('paystack_secret_key', '');
        if (!$secretKey) {
            return ['success' => false, 'message' => 'Paystack not configured'];
        }

        $url = 'https://api.paystack.co/transaction/verify/' . $reference;
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $secretKey,
                'Cache-Control: no-cache',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_TIMEOUT => 30,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $data = json_decode($response);
        if (!$data || !$data->status) {
            return ['success' => false, 'message' => $data->message ?? 'Verification failed'];
        }

        $isSuccess = $data->data->status === 'success';
        return [
            'success' => $isSuccess,
            'amount' => $data->data->amount / 100,
            'reference' => $data->data->reference,
            'paid_at' => $data->data->paid_at ?? date('Y-m-d H:i:s'),
            'channel' => $data->data->channel ?? '',
            'gateway_response' => $data->data->gateway_response ?? '',
            'raw' => $data,
        ];
    }

    public static function initHubtelPayment($email, $amount, $reference, $callbackUrl, $description = 'Membership Contribution')
    {
        $setting = new Setting();
        $clientId = $setting->getValue('hubtel_client_id', '');
        $clientSecret = $setting->getValue('hubtel_client_secret', '');
        $merchantAccount = $setting->getValue('hubtel_merchant_account', '');

        if (!$clientId || !$clientSecret || !$merchantAccount) {
            return ['success' => false, 'message' => 'Hubtel not fully configured'];
        }

        $url = 'https://api.hubtel.com/v1/merchantaccount/merchants/' . $merchantAccount . '/onlinecheckout/invoice/create';
        $fields = [
            'totalAmount' => round($amount, 2),
            'description' => $description,
            'callbackUrl' => $callbackUrl,
            'returnUrl' => $callbackUrl,
            'merchantBusinessLogoUrl' => '',
            'customerName' => $email,
            'customerEmail' => $email,
            'invoiceDescription' => $description,
            'orderDesc' => $reference,
        ];

        $auth = base64_encode($clientId . ':' . $clientSecret);
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($fields),
            CURLOPT_HTTPHEADER => [
                'Authorization: Basic ' . $auth,
                'Content-Type: application/json',
                'Cache-Control: no-cache',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_TIMEOUT => 30,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($curlError) {
            return ['success' => false, 'message' => 'cURL error: ' . $curlError];
        }

        $data = json_decode($response);
        if (!$data || !($data->responseCode === '00' || ($data->status ?? '') === 'success')) {
            $msg = $data->message ?? $data->errors ?? 'Hubtel initialization failed';
            if (is_array($msg)) $msg = json_encode($msg);
            return ['success' => false, 'message' => $msg];
        }

        return [
            'success' => true,
            'authorization_url' => $data->data->checkoutUrl ?? ($data->checkoutUrl ?? ''),
            'reference' => $data->data->invoiceToken ?? ($data->invoiceToken ?? ''),
        ];
    }

    public static function verifyHubtelPayment($reference)
    {
        $setting = new Setting();
        $clientId = $setting->getValue('hubtel_client_id', '');
        $clientSecret = $setting->getValue('hubtel_client_secret', '');
        $merchantAccount = $setting->getValue('hubtel_merchant_account', '');

        if (!$clientId || !$clientSecret || !$merchantAccount) {
            return ['success' => false, 'message' => 'Hubtel not fully configured'];
        }

        $url = 'https://api.hubtel.com/v1/merchantaccount/merchants/' . $merchantAccount . '/invoices/' . $reference;
        $auth = base64_encode($clientId . ':' . $clientSecret);
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => [
                'Authorization: Basic ' . $auth,
                'Cache-Control: no-cache',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_TIMEOUT => 30,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $data = json_decode($response);
        if (!$data) {
            return ['success' => false, 'message' => 'Invalid Hubtel response'];
        }

        $isSuccess = ($data->status ?? '') === 'success' || ($data->status ?? '') === 'paid';
        return [
            'success' => $isSuccess,
            'amount' => $data->totalAmount ?? 0,
            'reference' => $reference,
            'paid_at' => $data->paidAt ?? date('Y-m-d H:i:s'),
            'channel' => 'hubtel',
            'gateway_response' => $data->description ?? '',
            'raw' => $data,
        ];
    }
}
