<?php
// INTERNAL endpoint - called when user has 0 reset chances left and wants to unlock 10 more
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);
}

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

$price = floatval($adminSettings['reset_unlock_price']);
$orderId = generateOrderId('RESETUNLOCK');
$noteCode = generatePaymentNoteCode();

$order = [
    'order_id' => $orderId,
    'type' => 'reset_unlock',
    'user_id' => $user['id'],
    '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
    ]
]);
