<?php
// INTERNAL endpoint - called only from the logged-in user's dashboard
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();

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

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'User not found'], 404);
}

if (count($user['api_keys']) >= 3) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'You already have the maximum of 3 API keys.']);
}

$body = readEncryptedRequestBody();
$customName = trim($body['custom_name'] ?? '');
if ($customName === '') {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Please enter a name for your API key.']);
}
if (!preg_match('/^[A-Za-z0-9_]{2,30}$/', $customName)) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Name can only contain letters, numbers, underscores (2-30 chars).']);
}

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

$price = floatval($adminSettings['custom_api_price']);
$orderId = generateOrderId('CUSTOMAPI');
$noteCode = generatePaymentNoteCode();

$order = [
    'order_id' => $orderId,
    'type' => 'custom_api_purchase',
    'user_id' => $user['id'],
    'custom_name' => $customName,
    'amount' => $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($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' => $price
    ]
]);
