<?php
/**
 * order_status_lib.php
 * The actual "check order status" logic (incl. the on-demand FamPay Gmail
 * check for external callers), extracted out of payment/check_order.php so
 * it can be called directly in-process - same reasoning as
 * includes/order_lib.php for create_neopay_order(): no self-HTTP-call, so
 * no dependency on the current domain's /api/check-order-status rewrite
 * rule working.
 *
 * Returns ['http_code' => int, 'body' => array] - same shape as decoding
 * the HTTP JSON response from /api/check-order-status.
 */

function check_neopay_order_status($conn, $user_token, $order_id, $site_settings = null) {

    $sql = "SELECT acc_ban, acc_lock, expiry FROM users WHERE user_token = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $user_token);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {
        return ['http_code' => 401, 'body' => ["status" => false, "message" => "Unauthorized access"]];
    }

    $stmt->bind_result($acc_ban, $acc_lock, $expiry);
    $stmt->fetch();
    $stmt->close();

    if ($acc_ban == "on") {
        return ['http_code' => 403, 'body' => ["status" => false, "message" => "Your Account is Banned"]];
    }

    if ($acc_lock >= 3) {
        return ['http_code' => 403, 'body' => ["status" => false, "message" => "Your Account is Locked"]];
    }

    $sql = "SELECT status, amount, utr, create_date, Method, user_id, remark1 FROM orders WHERE user_token = ? AND order_id = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return ['http_code' => 500, 'body' => ["status" => false, "message" => "Database prepare error: " . $conn->error]];
    }

    $stmt->bind_param("ss", $user_token, $order_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {
        $stmt->close();
        return ['http_code' => 404, 'body' => ['status' => 'COMPLETED', 'message' => 'Order not found', 'result' => null]];
    }

    $stmt->bind_result($status, $amount, $utr, $create_date, $orderMethod, $orderUserId, $orderRemark1);
    $stmt->fetch();
    $stmt->close();

    // Same on-demand FamPay Gmail check the HTTP endpoint does - a caller
    // that never has its own browser polling payment_status.php (a
    // Telegram bot, the wallet top-up callback, etc.) still gets a live
    // check instead of only ever reading whatever's already in the DB.
    if ($status !== 'SUCCESS' && $status !== 'FAILURE' && strtolower($orderMethod) === 'fampay') {
        include_once __DIR__ . '/../auth/fampay_mail_check.php';
        include_once __DIR__ . '/google_oauth.php';
        include_once __DIR__ . '/fampay_gmail_api.php';
        include_once __DIR__ . '/fampay_order_resolver.php';

        $famRows = getXbyY("SELECT * FROM fampay_tokens WHERE user_token='" . $conn->real_escape_string($user_token) . "'");
        $rowFam = $famRows[0] ?? null;

        if ($rowFam && $rowFam['status'] === 'Active') {
            $orderCreatedTs = strtotime($create_date);
            if (!empty($rowFam['refresh_token'])) {
                $accessToken = google_oauth_get_valid_access_token($conn, $rowFam, $site_settings);
                $check = $accessToken
                    ? fampay_check_payment_oauth($accessToken, $amount, $order_id, null, null, $orderCreatedTs, $conn)
                    : ['matched' => false];
            } else {
                $check = fampay_check_payment($rowFam['gmail'], $rowFam['app_password'], $amount, $order_id, null, null, $orderCreatedTs, $conn);
            }

            if (!empty($check['matched'])) {
                $uRows = getXbyY("SELECT * FROM users WHERE id=" . (int)$orderUserId);
                $rowUser = $uRows[0] ?? null;
                if ($rowUser) {
                    resolve_fampay_order_success(
                        $conn, $order_id, $check['utr'], $amount, $user_token,
                        $orderRemark1, $orderUserId, $rowUser['callback_url'], $rowFam['gmail']
                    );
                    $status = 'SUCCESS';
                    $utr = $check['utr'];
                }
            }
        }
    }

    if ($status === 'SUCCESS') {
        return ['http_code' => 200, 'body' => [
            'status' => 'COMPLETED',
            'message' => 'Transaction Successfully',
            'result' => [
                "txnStatus" => "COMPLETED",
                "resultInfo" => "Transaction Success",
                "orderId" => $order_id,
                'status' => "SUCCESS",
                'amount' => $amount,
                'date' => $create_date,
                'utr' => $utr,
            ],
        ]];
    } elseif ($status === 'FAILURE') {
        return ['http_code' => 200, 'body' => [
            'status' => 'COMPLETED',
            'message' => 'Transaction Failed',
            'result' => [
                "txnStatus" => "FAILURE",
                "resultInfo" => "Transaction Failed",
                "orderId" => $order_id,
                'status' => "FAILURE",
                'amount' => $amount,
                'date' => $create_date,
            ],
        ]];
    } else {
        return ['http_code' => 200, 'body' => [
            'status' => 'COMPLETED',
            'message' => 'Transaction Pending',
            'result' => [
                "txnStatus" => "PENDING",
                "resultInfo" => "Transaction Pending",
                "orderId" => $order_id,
                'status' => "PENDING",
                'amount' => $amount,
                'date' => $create_date,
            ],
        ]];
    }
}
