<?php

namespace App\Services;

use Razorpay\Api\Api;
use Exception;

class RazorpayService
{
    protected $api;
    protected $keyId;
    protected $keySecret;

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

    /**
     * Create a Razorpay order
     */
    public function createOrder($amount, $currency = 'INR', $metadata = [])
    {
        try {
            $order = $this->api->order->create([
                'amount' => $amount * 100, // Amount in paise
                'currency' => $currency,
                'receipt' => 'rcpt_' . uniqid(),
                'notes' => $metadata,
            ]);

            return [
                'id' => $order->id,
                'amount' => $order->amount / 100,
                'currency' => $order->currency,
                'status' => $order->status,
            ];
        } catch (Exception $e) {
            throw new Exception('Razorpay order creation failed: ' . $e->getMessage());
        }
    }

    /**
     * Create a subscription
     */
    public function createSubscription($planId, $customerId, $totalCount = 12)
    {
        try {
            $subscription = $this->api->subscription->create([
                'plan_id' => $planId,
                'customer_id' => $customerId,
                'total_count' => $totalCount,
                'quantity' => 1,
                'customer_notify' => 1,
            ]);

            return [
                'id' => $subscription->id,
                'status' => $subscription->status,
                'plan_id' => $subscription->plan_id,
                'start_at' => $subscription->start_at,
            ];
        } catch (Exception $e) {
            throw new Exception('Razorpay subscription creation failed: ' . $e->getMessage());
        }
    }

    /**
     * Verify payment signature
     */
    public function verifySignature($orderId, $paymentId, $signature)
    {
        try {
            $attributes = [
                'razorpay_order_id' => $orderId,
                'razorpay_payment_id' => $paymentId,
                'razorpay_signature' => $signature,
            ];

            $this->api->utility->verifyPaymentSignature($attributes);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Fetch payment details
     */
    public function fetchPayment($paymentId)
    {
        try {
            $payment = $this->api->payment->fetch($paymentId);
            return [
                'id' => $payment->id,
                'amount' => $payment->amount / 100,
                'status' => $payment->status,
                'method' => $payment->method,
                'email' => $payment->email,
                'contact' => $payment->contact,
            ];
        } catch (Exception $e) {
            throw new Exception('Failed to fetch payment: ' . $e->getMessage());
        }
    }

    /**
     * Create a refund
     */
    public function createRefund($paymentId, $amount = null)
    {
        try {
            $refundData = ['payment_id' => $paymentId];
            if ($amount) {
                $refundData['amount'] = $amount * 100; // Amount in paise
            }

            $refund = $this->api->refund->create($refundData);
            return [
                'id' => $refund->id,
                'amount' => $refund->amount / 100,
                'status' => $refund->status,
            ];
        } catch (Exception $e) {
            throw new Exception('Refund creation failed: ' . $e->getMessage());
        }
    }

    /**
     * Create customer
     */
    public function createCustomer($name, $email, $contact)
    {
        try {
            $customer = $this->api->customer->create([
                'name' => $name,
                'email' => $email,
                'contact' => $contact,
            ]);

            return [
                'id' => $customer->id,
                'name' => $customer->name,
                'email' => $customer->email,
                'contact' => $customer->contact,
            ];
        } catch (Exception $e) {
            throw new Exception('Customer creation failed: ' . $e->getMessage());
        }
    }
}
