<?php
session_start();
include '../includes/config.php';

if (isset($_GET['order_id']) && isset($_GET['customer_mobile'])) {
    $order_id = $_GET['order_id'];
    $customer_mobile = $_GET['customer_mobile'];

    // Fetch local transaction data from wallet table
    $txn_check_qry = mysqli_query($ahk_conn, "SELECT * FROM wallet WHERE txn_id='$order_id'");
    if (!$txn_check_qry) {
        die("DB Error: " . mysqli_error($ahk_conn));
    }
    if (mysqli_num_rows($txn_check_qry) !== 1) {
        echo "<script>
            alert('Transaction not found or multiple records exist.');
            window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
        </script>";
        exit;
    }

    $txn_data = mysqli_fetch_assoc($txn_check_qry);

    // Call API to check order status
    $url = "https://$flexsecure_upiUrl/api/check-order-status";
    $postData = [
        "user_token" => $flexsecure_upikey2,
        "order_id" => $order_id,
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        die("cURL Error: " . curl_error($ch));
    }
    curl_close($ch);

    $resArray = json_decode($response, true);

    if (isset($resArray["message"]) && $resArray["message"] === "Transaction Successfully") {
        $result = $resArray["result"] ?? null;
        if ($result) {
            $txnStatus = $result["txnStatus"] ?? '';
            $txnAmount = floatval($result["amount"] ?? 0);
            $orderId = $result["orderId"] ?? '';
            $utr = $result["utr"] ?? '';
            $resultInfo = $result["resultInfo"] ?? '';

            // Check if local status is "pending" and API status is "COMPLETED"
            if ($txn_data['status'] === "pending" && strtoupper($txnStatus) === "COMPLETED") {
                if (!empty($utr)) {
                    // Update wallet: mark txn success and add amount to user balance
                    $minimum_amount = 0;  // set your minimum allowed amount here
                    if ($txnAmount > $minimum_amount) {
                        // Start transaction
                        mysqli_begin_transaction($ahk_conn);

                        $update_wallet = mysqli_query($ahk_conn, "UPDATE wallet SET status='success', amount='$txnAmount', BANKTXNID='$utr', RESPMSG='$resultInfo', PAYMENTMODE='UPI QR' WHERE txn_id='$order_id'");
                        $update_user = mysqli_query($ahk_conn, "UPDATE users SET balance = balance + $txnAmount WHERE phone='$customer_mobile'");

                        if ($update_wallet && $update_user) {
                            mysqli_commit($ahk_conn);
                            echo "<script>
                                alert('Payment success! ₹$txnAmount Wallet updated.');
                                window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
                            </script>";
                        } else {
                            mysqli_rollback($ahk_conn);
                            echo "<script>
                                alert('Database update failed: " . mysqli_error($ahk_conn) . "');
                                window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
                            </script>";
                        }
                    } else {
                        // Amount less than minimum (possible cheat)
                        mysqli_query($ahk_conn, "UPDATE wallet SET status='failed', RESPMSG='Amount less than minimum. Possible fraud.' WHERE txn_id='$order_id'");
                        echo "<script>
                            alert('Amount less than minimum allowed. Transaction marked failed.');
                            window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
                        </script>";
                    }
                } else {
                    // UTR missing, treat payment as invalid
                    echo "<script>
                        alert('Payment UTR missing. Payment considered invalid.');
                        window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
                    </script>";
                }
            } elseif ($txn_data['status'] === "success") {
                // Already success, don't update again
                echo "<script>
                    alert('Payment already processed. No update needed.');
                    window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
                </script>";
            } else {
                // Payment status not completed
                echo "<script>
                    alert('Payment status is not completed yet.');
                    window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
                </script>";
            }
        } else {
            echo "<script>
                alert('API returned no transaction result.');
                window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
            </script>";
        }
    } else {
        echo "<script>
            alert('Payment not successful or unauthorized access.');
            window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
        </script>";
    }

} else {
    echo "<script>
        alert('Required parameters missing.');
        window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/balance';
    </script>";
}
?>
