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

// ✅ TheMonkeyPay Configuration
$themonkey_token = "e8d2a2f1ac98d41d3b7422fd11ab98fa";
$themonkey_api_url = "themonkeypay.in";

// ✅ Backup Gateway Configuration
$backup_token = $flexsecure_upikey;
$backup_api_url = "server.responsecheck.site";

if (isset($_GET['order_id']) && isset($_GET['customer_mobile'])) {
    $order_id = $_GET['order_id'];
    $customer_mobile = $_GET['customer_mobile'];
    $gateway_used = $_SESSION['gateway_used'] ?? 'themonkeypay';

    // 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/wallet';
        </script>";
        exit;
    }

    $txn_data = mysqli_fetch_assoc($txn_check_qry);

    // ✅ Prepare API call based on gateway
    if ($gateway_used === 'themonkeypay') {
        $url = "https://{$themonkey_api_url}/api/check-order-status";
        $postData = [
            "user_token" => $themonkey_token,
            "order_id" => $order_id,
        ];
    } else {
        $url = "https://{$backup_api_url}/api/check-order-status";
        $postData = [
            "user_token" => $backup_token,
            "order_id" => $order_id,
        ];
    }

    // ✅ Call API
    $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));
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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

    $resArray = json_decode($response, true);

    // ✅ Process response based on gateway
    if ($gateway_used === 'themonkeypay') {
        // TheMonkeyPay Response Format
        $txnStatus = $resArray['status'] ?? '';
        
        if ($txnStatus === 'COMPLETED') {
            $result = $resArray['result'] ?? null;
            if ($result) {
                $txnAmount = floatval($result['amount'] ?? 0);
                $orderId = $result['orderId'] ?? '';
                $utr = $result['utr'] ?? '';

                // Check if local status is "pending" and API status is "COMPLETED"
                if ($txn_data['status'] === "pending") {
                    if (!empty($utr)) {
                        $minimum_amount = 0;
                        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='Payment Success via TheMonkeyPay', 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 added to wallet.');
                                    window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                                </script>";
                            } else {
                                mysqli_rollback($ahk_conn);
                                echo "<script>
                                    alert('Database update failed: " . mysqli_error($ahk_conn) . "');
                                    window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                                </script>";
                            }
                        } else {
                            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/wallet';
                            </script>";
                        }
                    } else {
                        echo "<script>
                            alert('Payment UTR missing. Payment considered invalid.');
                            window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                        </script>";
                    }
                } elseif ($txn_data['status'] === "success") {
                    echo "<script>
                        alert('Payment already processed. No update needed.');
                        window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                    </script>";
                } else {
                    echo "<script>
                        alert('Payment status is not completed yet.');
                        window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                    </script>";
                }
            } else {
                echo "<script>
                    alert('API returned no transaction result.');
                    window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                </script>";
            }
        } else {
            echo "<script>
                alert('Payment not successful or still pending.');
                window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
            </script>";
        }

    } else {
        // Backup Gateway Response Format
        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"] ?? '';

                if ($txn_data['status'] === "pending" && strtoupper($txnStatus) === "COMPLETED") {
                    if (!empty($utr)) {
                        $minimum_amount = 0;
                        if ($txnAmount > $minimum_amount) {
                            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/wallet';
                                </script>";
                            } else {
                                mysqli_rollback($ahk_conn);
                                echo "<script>
                                    alert('Database update failed: " . mysqli_error($ahk_conn) . "');
                                    window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                                </script>";
                            }
                        } else {
                            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/wallet';
                            </script>";
                        }
                    } else {
                        echo "<script>
                            alert('Payment UTR missing. Payment considered invalid.');
                            window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                        </script>";
                    }
                } elseif ($txn_data['status'] === "success") {
                    echo "<script>
                        alert('Payment already processed. No update needed.');
                        window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                    </script>";
                } else {
                    echo "<script>
                        alert('Payment status is not completed yet.');
                        window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                    </script>";
                }
            } else {
                echo "<script>
                    alert('API returned no transaction result.');
                    window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
                </script>";
            }
        } else {
            echo "<script>
                alert('Payment not successful or unauthorized access.');
                window.location.href='https://".$_SERVER['SERVER_NAME']."/admin/wallet';
            </script>";
        }
    }

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