<?php

namespace App\Services;

use Razorpay\Api\Api;
use App\Models\Payment;
use Illuminate\Support\Facades\Log;

class RazorpayService
{
    protected $api;

    public function __construct()
    {
        $this->api = new Api(env('RAZORPAY_KEY'), env('RAZORPAY_SECRET'));
    }

    /**
     * Create Razorpay Order
     */
    public function createOrder(Payment $payment, array $options = [])
    {
        try {
            $orderData = [
                'receipt' => 'receipt_' . $payment->payment_id,
                'amount' => $payment->getAmountInPaise(),
                'currency' => $payment->currency ?? 'INR',
                'payment_capture' => 1 // Auto capture
            ];

            // Merge custom options
            $orderData = array_merge($orderData, $options);

            $razorpayOrder = $this->api->order->create($orderData);

            // Update payment with Razorpay order ID
            $payment->update([
                'razorpay_order_id' => $razorpayOrder['id'],
                'payment_gateway' => 'razorpay'
            ]);

            return [
                'success' => true,
                'order_id' => $razorpayOrder['id'],
                'amount' => $razorpayOrder['amount'],
                'currency' => $razorpayOrder['currency'],
                'key' => env('RAZORPAY_KEY')
            ];

        } catch (\Exception $e) {
            Log::error('Razorpay Order Creation Failed: ' . $e->getMessage());

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

    /**
     * Verify Payment Signature
     */
    public function verifyPayment(array $attributes)
    {
        try {
            $generatedSignature = hash_hmac('sha256', $attributes['razorpay_order_id'] . '|' . $attributes['razorpay_payment_id'], env('RAZORPAY_SECRET'));

            return hash_equals($generatedSignature, $attributes['razorpay_signature']);

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

    /**
     * Fetch Payment Details from Razorpay
     */
    public function fetchPayment($paymentId)
    {
        try {
            return $this->api->payment->fetch($paymentId);
        } catch (\Exception $e) {
            Log::error('Razorpay Fetch Payment Failed: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Refund Payment
     */
    public function refundPayment($paymentId, $amount = null, $notes = [])
    {
        try {
            $refundData = [];
            if ($amount) {
                $refundData['amount'] = $amount * 100; // Convert to paise
            }
            if (!empty($notes)) {
                $refundData['notes'] = $notes;
            }

            return $this->api->payment->fetch($paymentId)->refund($refundData);

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

    /**
     * Check if payment is captured
     */
    public function isPaymentCaptured($paymentId)
    {
        try {
            $payment = $this->api->payment->fetch($paymentId);
            return $payment->captured;
        } catch (\Exception $e) {
            return false;
        }
    }
}
