<?php

// Use CodeIgniter's config and session services
use Config\Services;
use Razorpay\Api\Api;

// Load Razorpay configuration
require APPPATH . 'Config/Razorpay.php';
require APPPATH . 'ThirdParty/razorpay-php/Razorpay.php';

// Start session
$session = Services::session();
$session->start();

// Create the Razorpay Order
$config = config('Razorpay');
$api = new Api($config->keyId, $config->keySecret);

// Create an order using Razorpay's orders API
// Docs: https://docs.razorpay.com/docs/orders
$orderData = [
    'receipt'         => 3456,
    'amount'          => 2000 * 100, // 2000 rupees in paise
    'currency'        => 'INR',
    'payment_capture' => 1 // auto capture
];

$razorpayOrder = $api->order->create($orderData);
$razorpayOrderId = $razorpayOrder['id'];

// Store order ID in session
$session->set('razorpay_order_id', $razorpayOrderId);

$displayAmount = $amount = $orderData['amount'];

// Currency conversion (if needed)
if ($config->displayCurrency !== 'INR') {
    // Consider using a more reliable currency conversion API
    $url = "https://api.fixer.io/latest?symbols={$config->displayCurrency}&base=INR";
    $exchange = json_decode(file_get_contents($url), true);

    $displayAmount = $exchange['rates'][$config->displayCurrency] * $amount / 100;
}

// Determine checkout type
$checkout = 'automatic';
if (isset($_GET['checkout']) && in_array($_GET['checkout'], ['automatic', 'manual'], true)) {
    $checkout = $_GET['checkout'];
}

// Prepare data for Razorpay
$data = [
    "key"           => $config->keyId,
    "amount"        => $amount,
    "name"          => "DJ Tiesto",
    "description"   => "Tron Legacy",
    "image"         => "https://s29.postimg.org/r6dj1g85z/daft_punk.jpg",
    "prefill"       => [
        "name"    => "Daft Punk",
        "email"   => "customer@merchant.com",
        "contact" => "9999999999",
    ],
    "notes"         => [
        "address"           => "Hello World",
        "merchant_order_id" => "12312321",
    ],
    "theme"         => [
        "color" => "#F37254"
    ],
    "order_id"      => $razorpayOrderId,
];

if ($config->displayCurrency !== 'INR') {
    $data['display_currency'] = $config->displayCurrency;
    $data['display_amount'] = $displayAmount;
}

$json = json_encode($data);

// Load appropriate checkout view
require APPPATH . "Views/razorpay/checkout/{$checkout}.php";