<?php
// ─── Create Razorpay Order (AJAX endpoint) ────────────────────────────────────
// Called via fetch() from payment.php
// Returns JSON: { id: "order_xxx", amount: NNN }

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'], $_SESSION['pending_order_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

include 'config/db.php';
include 'config/razorpay.php';

$order_id = (int) $_SESSION['pending_order_id'];
$row = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT total_price FROM orders WHERE id = $order_id AND user_id = " . (int)$_SESSION['user_id']
));

if (!$row) {
    http_response_code(404);
    echo json_encode(['error' => 'Order not found']);
    exit;
}

// Amount in paise (multiply by 100)
$amount_paise = (int) round($row['total_price'] * 100);

// Call Razorpay Orders API
$ch = curl_init('https://api.razorpay.com/v1/orders');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_USERPWD        => RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS     => json_encode([
        'amount'   => $amount_paise,
        'currency' => 'INR',
        'receipt'  => 'order_' . $order_id,
    ]),
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code !== 200) {
    http_response_code(500);
    echo json_encode(['error' => 'Razorpay API error', 'detail' => $response]);
    exit;
}

$rzp_order = json_decode($response, true);

// Store razorpay order id in session for verification later
$_SESSION['razorpay_order_id'] = $rzp_order['id'];

echo json_encode([
    'id'     => $rzp_order['id'],
    'amount' => $rzp_order['amount'],
]);
