<?php

namespace App\Services;

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

class PaymentService
{
    protected $api;

    public function __construct()
    {
        $this->api = new Api(config('services.razorpay.key'), config('services.razorpay.secret'));
    }

    public function createOrder($amount, $receipt = null)
    {
        try {
            $orderData = [
                'receipt' => $receipt ?? (string) rand(1000, 9999),
                'amount' => $amount * 100, // Amount in paise
                'currency' => 'INR',
                'payment_capture' => 1 // Auto capture
            ];

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

            return $razorpayOrder->id;

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

    public function verifySignature($attributes)
    {
        try {
            $this->api->utility->verifyPaymentSignature($attributes);
            return true;
        } catch (\Exception $e) {
            Log::error('Razorpay Signature Verification Failed: ' . $e->getMessage());
            return false;
        }
    }

    public function fetchPayment($paymentId)
    {
        return $this->api->payment->fetch($paymentId);
    }

    /**
     * Process a refund for a payment.
     * 
     * @param string $paymentId The Razorpay Payment ID to refund.
     * @param float $amount The amount to refund in INR.
     * @param array $options Additional options like 'speed' (normal/optimum).
     */
    public function refund($paymentId, $amount, $options = [])
    {
        try {
            $refundData = array_merge([
                'amount' => $amount * 100, // Amount in paise
                'speed' => 'normal',
            ], $options);

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

            return $refund;

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