<?php
// INTERNAL endpoint - polled from the dashboard after showing the ₹100 QR
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();

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

$body = readEncryptedRequestBody();
$orderId = $body['order_id'] ?? '';
$order = getOrderById($orderId);

if (!$order || $order['user_id'] !== $_SESSION['user_id']) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Order not found']);
}

if ($order['status'] === 'success') {
    encryptedJsonResponse(['status' => 'success', 'data' => ['new_key' => $order['issued_key'] ?? '']]);
}

$adminSettings = getAdminSettings();
if (empty($adminSettings['gmail_id'])) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Admin Gmail not configured. Contact support.']);
}

$appPassword = decryptData($adminSettings['app_password_encrypted']);
$result = checkFamAppInboxForPayment(
    $adminSettings['gmail_id'],
    $appPassword,
    $order['amount'],
    $order['created_at_timestamp'],
    $order['note_code'] ?? null
);

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

    if (count($user['api_keys']) >= 3) {
        // Refund scenario - shouldn't normally happen since we checked before payment,
        // but guard anyway (e.g. user bought via 2 tabs at once).
        updateOrder($orderId, ['status' => 'failed', 'note' => 'User already had 3 keys']);
        encryptedJsonResponse(['status' => 'error', 'message' => 'You already reached the 3-key limit. Contact support for a refund.']);
    }

    $newKey = generateCustomApiKey($order['custom_name']);
    $user['api_keys'][] = [
        'key' => $newKey,
        'label' => $order['custom_name'],
        'created_at' => nowIST()->format('Y-m-d H:i:s')
    ];
    saveUser($user);

    updateOrder($orderId, [
        'status' => 'success',
        'issued_key' => $newKey,
        'transaction_id' => $result['transaction_id'] ?? '',
        'utr' => $result['utr'] ?? '',
        'payment_time_ist' => date('d-m-Y H:i:s', $result['payment_timestamp'] ?: time())
    ]);

    encryptedJsonResponse(['status' => 'success', 'data' => ['new_key' => $newKey]]);
} elseif ($result['status'] === 'error') {
    encryptedJsonResponse(['status' => 'error', 'message' => $result['message']]);
} else {
    encryptedJsonResponse(['status' => 'pending', 'message' => 'Payment not received yet']);
}
