<?php

namespace App\Services;

use App\Models\PaymentGateway;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Razorpay\Api\Api;

class RazorpayGateway
{
    protected $gateway;
    protected $api;

    public function __construct(PaymentGateway $gateway)
    {
        $this->gateway = $gateway;
        $this->api = new Api($gateway->getApiKey(), $gateway->getApiSecret());
    }

    public function createOrder($orderId, $amount, $currency, User $user, $description = null)
    {
        try {
            // Convert amount to paise (Razorpay expects amount in smallest currency unit)
            $amountInPaise = $amount * 100;

            $orderData = [
                'receipt' => $orderId,
                'amount' => $amountInPaise,
                'currency' => $currency,
                'payment_capture' => 1, // Auto capture
                'notes' => [
                    'user_id' => $user->id,
                    'user_email' => $user->email,
                    'description' => $description ?? 'CLX Payment',
                ],
            ];

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

            return [
                'success' => true,
                'order_id' => $razorpayOrder['id'],
                'amount' => $razorpayOrder['amount'],
                'currency' => $razorpayOrder['currency'],
                'receipt' => $razorpayOrder['receipt'],
                'status' => $razorpayOrder['status'],
            ];

        } catch (\Exception $e) {
            Log::error('Razorpay order creation failed', [
                'order_id' => $orderId,
                'amount' => $amount,
                'currency' => $currency,
                'error' => $e->getMessage(),
            ]);

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

    public function verifyPayment(Transaction $transaction, $paymentData)
    {
        try {
            $paymentId = $paymentData['payment_id'] ?? null;
            $orderId = $paymentData['order_id'] ?? null;
            $signature = $paymentData['signature'] ?? null;

            if (!$paymentId || !$orderId || !$signature) {
                return [
                    'success' => false,
                    'error' => 'Missing payment data',
                ];
            }

            // Verify signature
            $expectedSignature = hash_hmac('sha256', $orderId . '|' . $paymentId, $this->gateway->getApiSecret());

            if ($expectedSignature !== $signature) {
                return [
                    'success' => false,
                    'error' => 'Invalid signature',
                ];
            }

            // Fetch payment details
            $payment = $this->api->payment->fetch($paymentId);

            if ($payment['status'] === 'captured') {
                return [
                    'success' => true,
                    'transaction_id' => $paymentId,
                    'amount' => $payment['amount'] / 100, // Convert back to rupees
                    'currency' => $payment['currency'],
                    'payment_method' => $payment['method'],
                ];
            } else {
                return [
                    'success' => false,
                    'error' => 'Payment not captured: ' . $payment['status'],
                ];
            }

        } catch (\Exception $e) {
            Log::error('Razorpay payment verification failed', [
                'transaction_id' => $transaction->transaction_id,
                'error' => $e->getMessage(),
            ]);

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

    public function createSubscription(User $user, $plan)
    {
        try {
            // Create customer
            $customerData = [
                'name' => $user->name,
                'email' => $user->email,
                'contact' => $user->phone_number,
                'fail_existing' => 0,
            ];

            $customer = $this->api->customer->create($customerData);

            // Create plan
            $planData = [
                'period' => 'monthly',
                'interval' => 1,
                'item' => [
                    'name' => $plan->plan_name,
                    'description' => 'CLX ' . $plan->plan_name . ' Subscription',
                    'amount' => $plan->price * 100, // Convert to paise
                    'currency' => $plan->currency_code ?? 'INR',
                ],
            ];

            $razorpayPlan = $this->api->plan->create($planData);

            // Create subscription
            $subscriptionData = [
                'plan_id' => $razorpayPlan['id'],
                'customer_id' => $customer['id'],
                'total_count' => 12, // 1 year subscription
                'quantity' => 1,
            ];

            $subscription = $this->api->subscription->create($subscriptionData);

            return [
                'success' => true,
                'subscription_id' => $subscription['id'],
                'customer_id' => $customer['id'],
                'plan_id' => $razorpayPlan['id'],
                'status' => $subscription['status'],
            ];

        } catch (\Exception $e) {
            Log::error('Razorpay subscription creation failed', [
                'user_id' => $user->id,
                'plan_id' => $plan->id,
                'error' => $e->getMessage(),
            ]);

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

    public function refundPayment(Transaction $transaction, $amount, $reason = null)
    {
        try {
            $paymentId = $transaction->gateway_transaction_id;
            
            if (!$paymentId) {
                return [
                    'success' => false,
                    'error' => 'No payment ID found for refund',
                ];
            }

            // Convert amount to paise
            $amountInPaise = $amount * 100;

            $refundData = [
                'amount' => $amountInPaise,
                'notes' => [
                    'reason' => $reason ?? 'Customer request',
                ],
            ];

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

            return [
                'success' => true,
                'refund_id' => $refund['id'],
                'refunded_amount' => $refund['amount'] / 100,
                'status' => $refund['status'],
            ];

        } catch (\Exception $e) {
            Log::error('Razorpay refund failed', [
                'transaction_id' => $transaction->transaction_id,
                'amount' => $amount,
                'error' => $e->getMessage(),
            ]);

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

    public function getWebhookSecret()
    {
        return $this->gateway->webhook_secret;
    }

    public function verifyWebhookSignature($payload, $signature)
    {
        $expectedSignature = hash_hmac('sha256', $payload, $this->getWebhookSecret());
        return hash_equals($expectedSignature, $signature);
    }
}
