<?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 PaystackService
{
    protected $gateway;
    protected $baseUrl;

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

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

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

        $data = [
            'amount' => $amount * 100, // Convert to kobo
            'email' => $email,
            'reference' => $reference,
            'callback_url' => route('payment.callback', ['gateway' => 'paystack']),
            'metadata' => $metadata
        ];

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

            $result = $response->json();

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

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

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

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

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

            $result = $response->json();

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

            if ($response->successful() && $result['status'] && $result['data']['status'] === 'success') {
                return [
                    'success' => true,
                    'amount' => $result['data']['amount'] / 100, // Convert from kobo
                    'reference' => $result['data']['reference'],
                    'paid_at' => $result['data']['paid_at'],
                    '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(
                'paystack',
                'verify_payment',
                ['reference' => $reference],
                ['error' => $e->getMessage()],
                'error'
            );

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

    /**
     * Process webhook
     */
    public function processWebhook($payload, $signature)
    {
        // Verify webhook signature
        $computedSignature = hash_hmac('sha512', json_encode($payload), $this->gateway->secret_key);
        
        if ($signature !== $computedSignature) {
            PaymentLog::logEvent(
                'paystack',
                'webhook',
                $payload,
                ['error' => 'Invalid signature'],
                'failed'
            );
            return ['success' => false, 'message' => 'Invalid signature'];
        }

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

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

        if ($event === 'charge.success') {
            $transaction = Transaction::where('gateway_reference', $data['reference'])->first();
            
            if ($transaction) {
                $transaction->markAsSuccessful($data);
                
                PaymentLog::logEvent(
                    'paystack',
                    'webhook_processed',
                    $payload,
                    ['transaction_id' => $transaction->id, 'status' => 'completed'],
                    'success',
                    $transaction->id
                );
            }
        }

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