<?php
// INTERNAL endpoint - polled by dashboard while plan-purchase QR modal is open
// Request/response are AES-256-GCM encrypted (see assets/crypto.js).
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'], 404);
}

if ($order['status'] === 'success') {
    encryptedJsonResponse(['status' => 'success', 'message' => 'Already confirmed']);
}

$adminSettings = getAdminSettings();
if (empty($adminSettings['gmail_id']) || empty($adminSettings['app_password_encrypted'])) {
    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') {
    // Apply the plan to the user's account
    $user = getUserById($order['user_id']);
    $plan = getPlanById($order['plan_id']);

    if ($user && $plan) {
        $now = nowIST();
        // If current plan hasn't expired yet, extend from expiry date; else start fresh from now
        $currentExpiry = strtotime($user['plan_expires_at']);
        $baseTime = ($currentExpiry > time()) ? $currentExpiry : time();
        $newExpiry = (clone $now)->setTimestamp($baseTime)->modify('+' . $plan['days'] . ' days');

        $user['plan_id'] = $plan['id'];
        $user['plan_label'] = $plan['label'];
        $user['plan_expires_at'] = $newExpiry->format('Y-m-d H:i:s');
        saveUser($user);
    }

    updateOrder($orderId, [
        'status' => 'success',
        'transaction_id' => $result['transaction_id'],
        'utr' => $result['utr'],
        'confirmed_at' => nowIST()->format('Y-m-d H:i:s')
    ]);

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