<?php
declare(strict_types=1);
namespace Services;

use Config\Env;
use RuntimeException;

final class RazorpayService
{
    public function createOrder(float $amount, string $receipt): array
    {
        $key = Env::get('RAZORPAY_KEY_ID');
        $secret = Env::get('RAZORPAY_KEY_SECRET');
        if (!$key || !$secret) throw new RuntimeException('Razorpay credentials missing');
        $payload = json_encode(['amount' => (int)round($amount * 100), 'currency' => 'INR', 'receipt' => $receipt, 'payment_capture' => 1]);
        $ch = curl_init('https://api.razorpay.com/v1/orders');
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_USERPWD => $key . ':' . $secret, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPHEADER => ['Content-Type: application/json']]);
        $response = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $data = json_decode((string)$response, true);
        if ($status >= 400 || !is_array($data)) throw new RuntimeException('Unable to create Razorpay order');
        return $data;
    }


    public function fetchPayment(string $paymentId): array
    {
        $key = Env::get('RAZORPAY_KEY_ID');
        $secret = Env::get('RAZORPAY_KEY_SECRET');
        if (!$key || !$secret) throw new RuntimeException('Razorpay credentials missing');
        $ch = curl_init('https://api.razorpay.com/v1/payments/' . rawurlencode($paymentId));
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_USERPWD => $key . ':' . $secret]);
        $response = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $data = json_decode((string)$response, true);
        if ($status >= 400 || !is_array($data)) throw new RuntimeException('Unable to verify Razorpay payment details');
        return $data;
    }

    public function verifySignature(string $orderId, string $paymentId, string $signature): bool
    {
        $secret = Env::get('RAZORPAY_KEY_SECRET');
        $expected = hash_hmac('sha256', $orderId . '|' . $paymentId, $secret);
        return hash_equals($expected, $signature);
    }
}
