<?php
require_once __DIR__ . '/../functions.php';
requireAuth();
header('Content-Type: application/json');

if (empty(RAZORPAY_KEY_ID) || empty(RAZORPAY_KEY_SECRET)) {
    echo json_encode(['success' => false, 'message' => 'Razorpay not configured.']);
    exit;
}

$items = getCartItems();
if (count($items) === 0) {
    echo json_encode(['success' => false, 'message' => 'Cart is empty.']);
    exit;
}

$subtotal = getCartTotal();
$coupon = getAppliedCoupon();
$shippingState = $_SESSION['user_state'] ?? null;
$totals = calculateTotals($subtotal, $coupon, $items, $shippingState);
$amountPaise = round($totals['total'] * 100);
$receipt = 'rcpt_' . time() . '_' . $_SESSION['user_id'];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => 'https://api.razorpay.com/v1/orders',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode([
        'amount' => $amountPaise,
        'currency' => 'INR',
        'receipt' => $receipt,
        'payment_capture' => 1,
    ]),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    echo json_encode(['success' => false, 'message' => 'Failed to create payment order.']);
    exit;
}

$order = json_decode($response, true);

echo json_encode([
    'success' => true,
    'razorpay_key_id' => RAZORPAY_KEY_ID,
    'razorpay_order_id' => $order['id'],
    'amount' => $order['amount'],
    'currency' => $order['currency'],
    'user_name' => $_SESSION['user_name'],
    'user_email' => $_SESSION['user_email'],
]);
