<?php
// INTERNAL endpoint - polled from dashboard after showing the ₹5 reset-unlock 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' => ['reset_chances' => 10]]);
}

$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']);
    }

    $user['reset_chances'] = 10;
    saveUser($user);

    updateOrder($orderId, [
        'status' => 'success',
        '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' => ['reset_chances' => 10]]);
} elseif ($result['status'] === 'error') {
    encryptedJsonResponse(['status' => 'error', 'message' => $result['message']]);
} else {
    encryptedJsonResponse(['status' => 'pending', 'message' => 'Payment not received yet']);
}
