<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use Razorpay\Api\Api;

class PaymentController extends Controller
{
    private $keyId = "rzp_test_SInNQpMHXzYQFk";
    private $keySecret = "wBEatFCyy8cvq0oJeVD1fT4q";

    public function createOrder()
    {
        $api = new Api($this->keyId, $this->keySecret);

        $amount = 1000; // ₹10

        $order = $api->order->create([
            'receipt' => 'order_' . time(),
            'amount' => $amount,
            'currency' => 'INR'
        ]);

        return $this->response->setJSON([
            'status' => true,
            'order_id' => $order['id'],
            'amount' => $order['amount'],
            'key' => $this->keyId
        ]);
    }

    public function verifyPayment()
    {
        $input = json_decode(file_get_contents("php://input"), true);

        $api = new Api($this->keyId, $this->keySecret);

        try {
            $attributes = [
                'razorpay_order_id' => $input['razorpay_order_id'],
                'razorpay_payment_id' => $input['razorpay_payment_id'],
                'razorpay_signature' => $input['razorpay_signature']
            ];

            $api->utility->verifyPaymentSignature($attributes);

            return $this->response->setJSON([
                'status' => true,
                'message' => 'Payment Successful'
            ]);

        } catch (\Exception $e) {

            return $this->response->setJSON([
                'status' => false,
                'message' => 'Payment Verification Failed'
            ]);
        }
    }
}