<?php

namespace App\Services\Payment;

use App\Models\PaymentGateway;
use App\Models\PaymentLog;
use App\Models\Transaction;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class FlutterwaveService
{
    protected $gateway;
    protected $baseUrl;

    public function __construct()
    {
        $this->gateway = PaymentGateway::getByName('flutterwave');
        $this->baseUrl = $this->gateway->isTestMode() 
            ? 'https://api.flutterwave.com/v3' 
            : 'https://api.flutterwave.com/v3';
    }

    /**
     * Initialize payment
     */
    public function initializePayment($amount, $email, $currency = 'NGN', $reference = null, $metadata = [])
    {
        if (!$this->gateway || !$this->gateway->is_active) {
            throw new \Exception('Flutterwave gateway is not configured or active');
        }

        $reference = $reference ?? 'FLW_' . Str::upper(Str::random(16));

        $data = [
            'tx_ref' => $reference,
            'amount' => $amount,
            'currency' => $currency,
            'redirect_url' => route('payment.callback', ['gateway' => 'flutterwave']),
            'customer' => [
                'email' => $email,
                'name' => $metadata['name'] ?? 'Customer'
            ],
            'customizations' => [
                'title' => config('app.name'),
                'description' => $metadata['description'] ?? 'Payment',
                'logo' => asset('logo.png')
            ],
            'meta' => $metadata
        ];

        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->gateway->secret_key,
                'Content-Type' => 'application/json'
            ])->post($this->baseUrl . '/payments', $data);

            $result = $response->json();

            PaymentLog::logEvent(
                'flutterwave',
                'initialize_payment',
                $data,
                $result,
                $response->successful() ? 'success' : 'failed'
            );

            if ($response->successful() && $result['status'] === 'success') {
                return [
                    'success' => true,
                    'payment_url' => $result['data']['link'],
                    'reference' => $reference
                ];
            }

            return [
                'success' => false,
                'message' => $result['message'] ?? 'Payment initialization failed'
            ];
        } catch (\Exception $e) {
            PaymentLog::logEvent(
                'flutterwave',
                'initialize_payment',
                $data,
                ['error' => $e->getMessage()],
                'error'
            );

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

    /**
     * Verify payment
     */
    public function verifyPayment($transactionId)
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->gateway->secret_key
            ])->get($this->baseUrl . '/transactions/' . $transactionId . '/verify');

            $result = $response->json();

            PaymentLog::logEvent(
                'flutterwave',
                'verify_payment',
                ['transaction_id' => $transactionId],
                $result,
                $response->successful() ? 'success' : 'failed'
            );

            if ($response->successful() && $result['status'] === 'success' && $result['data']['status'] === 'successful') {
                return [
                    'success' => true,
                    'amount' => $result['data']['amount'],
                    'currency' => $result['data']['currency'],
                    'reference' => $result['data']['tx_ref'],
                    'flw_ref' => $result['data']['flw_ref'],
                    'customer' => $result['data']['customer'],
                    'raw_data' => $result['data']
                ];
            }

            return [
                'success' => false,
                'message' => $result['message'] ?? 'Payment verification failed',
                'raw_data' => $result
            ];
        } catch (\Exception $e) {
            PaymentLog::logEvent(
                'flutterwave',
                'verify_payment',
                ['transaction_id' => $transactionId],
                ['error' => $e->getMessage()],
                'error'
            );

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

    /**
     * Process webhook
     */
    public function processWebhook($payload, $signature)
    {
        // Verify webhook signature
        $secretHash = config('services.flutterwave.webhook_secret') ?? $this->gateway->settings['webhook_secret'] ?? '';
        
        if ($signature !== $secretHash) {
            PaymentLog::logEvent(
                'flutterwave',
                'webhook',
                $payload,
                ['error' => 'Invalid signature'],
                'failed'
            );
            return ['success' => false, 'message' => 'Invalid signature'];
        }

        PaymentLog::logEvent(
            'flutterwave',
            'webhook',
            $payload,
            ['status' => 'received'],
            'success'
        );

        $event = $payload['event'] ?? null;
        $data = $payload['data'] ?? [];

        if ($event === 'charge.completed' && $data['status'] === 'successful') {
            $transaction = Transaction::where('gateway_reference', $data['tx_ref'])->first();
            
            if ($transaction) {
                // Verify the transaction amount matches
                if ((float)$transaction->amount === (float)$data['amount']) {
                    $transaction->markAsSuccessful($data);
                    
                    PaymentLog::logEvent(
                        'flutterwave',
                        'webhook_processed',
                        $payload,
                        ['transaction_id' => $transaction->id, 'status' => 'completed'],
                        'success',
                        $transaction->id
                    );
                } else {
                    PaymentLog::logEvent(
                        'flutterwave',
                        'webhook_processed',
                        $payload,
                        ['error' => 'Amount mismatch', 'expected' => $transaction->amount, 'received' => $data['amount']],
                        'failed',
                        $transaction->id
                    );
                }
            }
        }

        return ['success' => true];
    }
}
