<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../common/journal_config_new.php';
require __DIR__ . '/razorpay-php/Razorpay.php';

use Razorpay\Api\Api;

try {
    // Get input from JSON body
    $input = json_decode(file_get_contents('php://input'), true);
    
    $tracking_code = $input['tracking_code'] ?? '';
    $amount = $input['amount'] ?? '';
    $currency = $input['currency'] ?? 'INR';
    
    if (!$tracking_code || !$amount || !$currency) {
        throw new Exception('Tracking code, amount, and currency are required');
    }
    
    // Validate amount is numeric
    if (!is_numeric($amount)) {
        throw new Exception('Invalid amount format');
    }
    
    $amount = (float)$amount;
    
    // Initialize Razorpay API
    $api = new Api(RAZORPAY_KEY_ID, RAZORPAY_SECRET);
    
    // Convert amount to smallest currency unit
    // For INR: 1 INR = 100 paise
    // For USD: 1 USD = 100 cents
    // For other currencies, multiply by 100
    $amount_in_smallest_unit = (int)($amount * 100);
    
    // Create Razorpay order
    $order = $api->order->create([
        'receipt'         => 'RSIS-' . $tracking_code,
        'amount'          => $amount_in_smallest_unit,
        'currency'        => $currency,
        'payment_capture' => 1 // auto capture
    ]);
    
    echo json_encode([
        'success' => true,
        'order_id' => $order['id'],
        'amount' => $amount_in_smallest_unit, // Amount in smallest unit for Razorpay
        'amount_display' => $amount, // Original amount for display
        'currency' => $currency
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
