<?php
// INTERNAL endpoint - called only from the logged-in user's dashboard (not part of public API)
// Request body and response are AES-256-GCM encrypted (see encryptedFetch() in assets/crypto.js
// and encryptPayload()/decryptPayload() in includes/functions.php).
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();

if (!isLoggedIn()) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Not logged in'], 401);
}

$body = readEncryptedRequestBody();

$user = getUserById($_SESSION['user_id']);
$planId = $body['plan_id'] ?? '';
$plan = getPlanById($planId);

if (!$plan) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Invalid plan selected'], 404);
}

$adminSettings = getAdminSettings();
if (empty($adminSettings['upi_id'])) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Payments are temporarily unavailable. Please contact support.']);
}

$orderId = generateOrderId('PLANBUY');
$noteCode = generatePaymentNoteCode();

$order = [
    'order_id' => $orderId,
    'type' => 'plan_purchase',
    'user_id' => $user['id'],
    'plan_id' => $plan['id'],
    'amount' => $plan['price'],
    'note_code' => $noteCode,
    'status' => 'pending',
    'created_at' => nowIST()->format('Y-m-d H:i:s'),
    'created_at_timestamp' => time()
];
saveOrder($order);

$upiString = "upi://pay?pa=" . urlencode($adminSettings['upi_id'])
    . "&pn=" . urlencode('FamAPI')
    . "&tr=" . urlencode($orderId)
    . "&tn=" . urlencode($noteCode)
    . "&am=" . urlencode($plan['price'])
    . "&cu=INR";

$qrUrl = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($upiString);

encryptedJsonResponse([
    'status' => 'success',
    'data' => [
        'order_id' => $orderId,
        'qr_url' => $qrUrl,
        'amount' => $plan['price']
    ]
]);
