<?php

namespace App\Services;

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

class PaymentService
{
    protected $razorpayKey;
    protected $razorpaySecret;
    protected $paypalClientId;
    protected $paypalSecret;
    protected $paypalMode;

    public function __construct()
    {
        $this->razorpayKey = \App\Models\Setting::getValue('razorpay_key', config('services.razorpay.key'));
        $this->razorpaySecret = \App\Models\Setting::getValue('razorpay_secret', config('services.razorpay.secret'));
        $this->paypalClientId = \App\Models\Setting::getValue('paypal_client_id', config('services.paypal.client_id'));
        $this->paypalSecret = \App\Models\Setting::getValue('paypal_secret', config('services.paypal.secret'));
        $this->paypalMode = \App\Models\Setting::getValue('paypal_mode', 'sandbox'); // sandbox or live
    }

    // ===================== RAZORPAY =====================

    public function createRazorpayOrder($amount, $currency = 'INR', $receipt = null)
    {
        if (!class_exists('Razorpay\Api\Api')) {
            Log::error('Razorpay SDK not installed.');
            return [
                'success' => false,
                'message' => 'Razorpay SDK not installed.'
            ];
        }

        try {
            $api = new Api($this->razorpayKey, $this->razorpaySecret);
            
            $orderData = [
                'receipt'         => $receipt,
                'amount'          => $amount * 100, // Amount in paise
                'currency'        => $currency,
                'payment_capture' => 1 // Auto capture
            ];

            $razorpayOrder = $api->order->create($orderData);
            
            return [
                'success' => true,
                'order_id' => $razorpayOrder['id'],
                'amount' => $orderData['amount'],
                'currency' => $orderData['currency'],
                'key' => $this->razorpayKey
            ];

        } catch (\Exception $e) {
            Log::error('Razorpay Order Creation Failed: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    public function verifyRazorpayPayment($signature, $paymentId, $orderId)
    {
        if (!class_exists('Razorpay\Api\Api')) {
            return false;
        }

        try {
            $api = new Api($this->razorpayKey, $this->razorpaySecret);
            
            $attributes = [
                'razorpay_signature'  => $signature,
                'razorpay_payment_id' => $paymentId,
                'razorpay_order_id'   => $orderId
            ];

            $api->utility->verifyPaymentSignature($attributes);
            return true;

        } catch (\Exception $e) {
            Log::error('Razorpay Signature Verification Failed: ' . $e->getMessage());
            return false;
        }
    }

    // ===================== PAYPAL =====================

    protected function getPaypalBaseUrl()
    {
        return $this->paypalMode === 'live' 
            ? 'https://api-m.paypal.com' 
            : 'https://api-m.sandbox.paypal.com';
    }

    protected function getPaypalAccessToken()
    {
        try {
            $response = Http::withBasicAuth($this->paypalClientId, $this->paypalSecret)
                ->asForm()
                ->post($this->getPaypalBaseUrl() . '/v1/oauth2/token', [
                    'grant_type' => 'client_credentials'
                ]);

            if ($response->successful()) {
                return $response->json()['access_token'];
            }

            Log::error('PayPal Access Token Failed: ' . $response->body());
            return null;

        } catch (\Exception $e) {
            Log::error('PayPal Access Token Exception: ' . $e->getMessage());
            return null;
        }
    }

    public function createPaypalOrder($amount, $currency = 'USD', $description = 'Subscription')
    {
        $accessToken = $this->getPaypalAccessToken();
        
        if (!$accessToken) {
            return [
                'success' => false,
                'message' => 'Failed to get PayPal access token'
            ];
        }

        try {
            $response = Http::withToken($accessToken)
                ->post($this->getPaypalBaseUrl() . '/v2/checkout/orders', [
                    'intent' => 'CAPTURE',
                    'purchase_units' => [[
                        'amount' => [
                            'currency_code' => $currency,
                            'value' => number_format($amount, 2, '.', '')
                        ],
                        'description' => $description
                    ]],
                    'application_context' => [
                        'brand_name' => 'The Mini Port',
                        'landing_page' => 'LOGIN',
                        'user_action' => 'PAY_NOW',
                        'return_url' => route('seller.subscription.paypal.success'),
                        'cancel_url' => route('seller.subscription.index')
                    ]
                ]);

            if ($response->successful()) {
                $data = $response->json();
                $approvalUrl = collect($data['links'])->firstWhere('rel', 'approve')['href'] ?? null;
                
                return [
                    'success' => true,
                    'order_id' => $data['id'],
                    'approval_url' => $approvalUrl
                ];
            }

            Log::error('PayPal Order Creation Failed: ' . $response->body());
            return [
                'success' => false,
                'message' => 'Failed to create PayPal order'
            ];

        } catch (\Exception $e) {
            Log::error('PayPal Order Exception: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    public function capturePaypalOrder($orderId)
    {
        $accessToken = $this->getPaypalAccessToken();
        
        if (!$accessToken) {
            return [
                'success' => false,
                'message' => 'Failed to get PayPal access token'
            ];
        }

        try {
            $response = Http::withToken($accessToken)
                ->withHeaders(['Content-Type' => 'application/json'])
                ->post($this->getPaypalBaseUrl() . "/v2/checkout/orders/{$orderId}/capture");

            if ($response->successful()) {
                $data = $response->json();
                
                if ($data['status'] === 'COMPLETED') {
                    return [
                        'success' => true,
                        'payment_id' => $data['id'],
                        'status' => $data['status'],
                        'payer_email' => $data['payer']['email_address'] ?? null
                    ];
                }
            }

            Log::error('PayPal Capture Failed: ' . $response->body());
            return [
                'success' => false,
                'message' => 'Failed to capture PayPal payment'
            ];

        } catch (\Exception $e) {
            Log::error('PayPal Capture Exception: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    public function getPaypalClientId()
    {
        return $this->paypalClientId;
    }

    public function getPaypalMode()
    {
        return $this->paypalMode;
    }
}

