<?php

namespace App\Services\Payments\Gateways;

use App\Services\Payments\PaymentGatewayInterface;
use Illuminate\Support\Facades\Http;
use Exception;

class RazorpayGateway implements PaymentGatewayInterface
{
    protected $keyId;
    protected $keySecret;
    protected $baseUrl = 'https://api.razorpay.com/v1';

    public function __construct($config, $mode)
    {
        $credentials = ($mode === 'live') ? $config['live_credentials'] : $config['test_credentials'];
        $this->keyId = $credentials['key_id'] ?? '';
        $this->keySecret = $credentials['key_secret'] ?? '';
    }

    public function pay(float $amount, string $currency, array $metadata)
    {
        if (empty($this->keyId) || empty($this->keySecret)) {
            throw new Exception("Razorpay credentials are not configured.");
        }

        $orderNumber = $metadata['order_number'];

        // Razorpay accepts amount in subunits (paise / cents)
        $amountInSubunits = round($amount * 100);

        $response = Http::withBasicAuth($this->keyId, $this->keySecret)
            ->post("{$this->baseUrl}/payment_links", [
                'amount' => $amountInSubunits,
                'currency' => strtoupper($currency),
                'accept_partial' => false,
                'reference_id' => $orderNumber,
                'description' => 'Order #' . $orderNumber,
                'customer' => [
                    'name' => auth()->user()->name ?? 'Customer',
                    'email' => auth()->user()->email ?? 'customer@example.com',
                ],
                'notify' => ['sms' => false, 'email' => false],
                'reminder_enable' => false,
                'callback_url' => route('payment.callback', ['gateway' => 'razorpay', 'order' => $orderNumber]),
                'callback_method' => 'get'
            ]);

        if ($response->successful() && $response->json('short_url')) {
            return ['url' => $response->json('short_url')];
        }

        throw new Exception("Razorpay Order Creation Failed: " . $response->body());
    }

    public function verify(array $requestData): array
    {
        $orderNumber = $requestData['order'] ?? null;
        $paymentLinkId = $requestData['razorpay_payment_link_id'] ?? null;

        if (!$paymentLinkId) {
            return ['success' => false, 'order_number' => $orderNumber];
        }

        // Server-to-Server secure verification
        $response = Http::withBasicAuth($this->keyId, $this->keySecret)
            ->get("{$this->baseUrl}/payment_links/{$paymentLinkId}");

        $isSuccess = false;
        if ($response->successful()) {
            $isSuccess = $response->json('status') === 'paid';
        }

        return [
            'success' => $isSuccess,
            'order_number' => $orderNumber
        ];
    }
}