<?php
require_once '../config/headers.php';
require_once '../config/constants.php';
require_once '../utils/response.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

$data = json_decode(file_get_contents("php://input"));

if (empty($data->amount)) {
    sendResponse(400, 'error', 'Amount is required');
}

// Razorpay expects the amount in paise (multiply by 100)
$amount_in_paise = (int)($data->amount * 100);

// Call Razorpay API using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.razorpay.com/v1/orders');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'amount' => $amount_in_paise,
    'currency' => 'INR',
    'receipt' => 'pkg_rcpt_' . time()
]));
curl_setopt($ch, CURLOPT_USERPWD, RZP_KEY_ID . ':' . RZP_KEY_SECRET);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_status === 200) {
    $order = json_decode($result, true);
    sendResponse(200, 'success', 'Order created', ['order_id' => $order['id']]);
} else {
    sendResponse(500, 'error', 'Failed to create Razorpay order', json_decode($result, true));
}
?>