<?php
// razorpay/create_order.php — Create a one-time Razorpay Order for 30-day access
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../helpers.php';

header('Content-Type: application/json');

$store = requireAuth();
$input = json_decode(file_get_contents('php://input'), true);
$planId = (int)($input['plan_id'] ?? 0);

if (!$planId) {
    jsonResponse(['success' => false, 'message' => 'Missing plan_id'], 400);
}

$db = getDB();
$stmt = $db->prepare("SELECT * FROM plans WHERE id = ? AND is_active = 1");
$stmt->execute([$planId]);
$plan = $stmt->fetch();

if (!$plan) {
    jsonResponse(['success' => false, 'message' => 'Plan not found'], 404);
}

if ($plan['price'] <= 0) {
    jsonResponse(['success' => false, 'message' => 'Cannot pay for a free plan'], 400);
}

// Create Razorpay Order
$receipt = 'rcpt_' . $store['id'] . '_' . time();
$orderPayload = [
    'amount'   => (int)($plan['price'] * 100),
    'currency' => 'INR',
    'receipt'  => $receipt,
    'notes'    => [
        'shop_domain' => $store['shop_domain'],
        'store_id'    => (string)$store['id'],
        'plan_id'     => (string)$plan['id'],
        'plan_name'   => $plan['name'],
    ],
];

$ch = curl_init('https://api.razorpay.com/v1/orders');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD        => RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($orderPayload),
    CURLOPT_TIMEOUT        => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode($response, true);

if ($httpCode >= 400 || !isset($result['id'])) {
    error_log('Razorpay Order Create Error: ' . $response);
    jsonResponse(['success' => false, 'message' => 'Failed to create order: ' . ($result['error']['description'] ?? 'Unknown')], 500);
}

// Save pending subscription record
$stmt = $db->prepare("
    INSERT INTO subscriptions (store_id, plan_id, razorpay_subscription_id, status, created_at)
    VALUES (?, ?, ?, 'created', NOW())
");
$stmt->execute([$store['id'], $plan['id'], $result['id']]);

jsonResponse([
    'success'      => true,
    'order_id'     => $result['id'],
    'razorpay_key' => RAZORPAY_KEY_ID,
    'amount'       => $orderPayload['amount'],
    'currency'     => 'INR',
    'plan_name'    => $plan['name'],
    'shop_name'    => $store['shop_name'] ?? $store['shop_domain'],
    'email'        => $store['email'] ?? '',
]);
