<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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($_SESSION['order_id']) && isset($_SESSION['customer_mobile'])) {

    $order_id = $_SESSION['order_id'];
    $customer_mobile = $_SESSION['customer_mobile'];
    $gateway_used = $_SESSION['gateway_used'] ?? 'themonkeypay';
    $minimum_amount = 49;

    if (!isset($_SESSION['wallet_updated'][$order_id])) {
        
        // ✅ Prepare API call based on gateway used
        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)) {
            $curlError = curl_error($ch);
            curl_close($ch);
            ob_end_clean();
            die("API request failed: " . htmlspecialchars($curlError));
        }
        curl_close($ch);

        $responseData = json_decode($response, true);

        if (!$responseData) {
            ob_end_clean();
            die("Failed to decode API response.");
        }

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

            if ($txnStatus === 'COMPLETED') {
                if ($amount >= $minimum_amount) {
                    $phoneEscaped = mysqli_real_escape_string($ahk_conn, $customer_mobile);
                    $amountEscaped = mysqli_real_escape_string($ahk_conn, $amount);
                    $utrEscaped = mysqli_real_escape_string($ahk_conn, $utr);
                    $orderIdEscaped = mysqli_real_escape_string($ahk_conn, $orderId);

                    $sql1 = "UPDATE users SET status = '1' WHERE phone = '$phoneEscaped'";
                    $sql2 = "UPDATE wallet 
                             SET status = 'success', amount='$amountEscaped', BANKTXNID='$utrEscaped', 
                                 RESPMSG='Payment Success via TheMonkeyPay', PAYMENTMODE='UPI QR'
                             WHERE txn_id = '$orderIdEscaped'";

                    $userUpdate = $ahk_conn->query($sql1);
                    $walletUpdate = $ahk_conn->query($sql2);

                    ob_end_clean();
                    echo "<!DOCTYPE html><html><head>
                    <meta charset='UTF-8'>
                    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                    </head><body>";

                    if ($userUpdate && $walletUpdate) {
                        $_SESSION['wallet_updated'][$order_id] = true;
                        echo "<script>
                        Swal.fire({
                            title: 'SUCCESS',
                            text: 'Your registration was successful.',
                            icon: 'success'
                        }).then(() => {
                            window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                        });
                        </script>";
                    } else {
                        $errorMsg = addslashes($ahk_conn->error);
                        echo "<script>
                        Swal.fire({
                            title: 'FAILED',
                            text: 'Database update failed: {$errorMsg}',
                            icon: 'error'
                        }).then(() => {
                            window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                        });
                        </script>";
                    }
                    echo "</body></html>";
                    exit();

                } else {
                    ob_end_clean();
                    echo "<!DOCTYPE html><html><head>
                    <meta charset='UTF-8'>
                    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                    </head><body>
                    <script>
                    Swal.fire({
                        title: 'Invalid Amount',
                        text: 'You paid ₹{$amount}, but minimum ₹{$minimum_amount} required.',
                        icon: 'error'
                    }).then(() => {
                        window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                    });
                    </script></body></html>";
                    exit();
                }
            } else {
                ob_end_clean();
                echo "<!DOCTYPE html><html><head>
                <meta charset='UTF-8'>
                <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                </head><body>
                <script>
                Swal.fire({
                    title: 'Payment Pending',
                    text: 'Your payment is still processing.',
                    icon: 'warning'
                }).then(() => {
                    window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                });
                </script></body></html>";
                exit();
            }

        } else {
            // Backup Gateway Response Format
            if (isset($responseData["message"]) && $responseData["message"] === "Unauthorized access") {
                ob_end_clean();
                die("Unauthorized access to API.");
            }

            if (isset($responseData["result"])) {
                $txnStatus = $responseData["result"]["txnStatus"] ?? '';
                $orderId = $responseData["result"]["orderId"] ?? '';
                $status = $responseData["result"]["status"] ?? '';
                $amount = $responseData["result"]["amount"] ?? 0;
                $date = $responseData["result"]["date"] ?? '';
                $utr = $responseData["result"]["utr"] ?? '';

                if ($txnStatus === "COMPLETED") {
                    if ($amount >= $minimum_amount) {
                        $phoneEscaped = mysqli_real_escape_string($ahk_conn, $customer_mobile);
                        $amountEscaped = mysqli_real_escape_string($ahk_conn, $amount);
                        $utrEscaped = mysqli_real_escape_string($ahk_conn, $utr);
                        $statusEscaped = mysqli_real_escape_string($ahk_conn, $status);
                        $orderIdEscaped = mysqli_real_escape_string($ahk_conn, $orderId);

                        $sql1 = "UPDATE users SET status = '1' WHERE phone = '$phoneEscaped'";
                        $sql2 = "UPDATE wallet 
                                 SET status = 'success', amount='$amountEscaped', BANKTXNID='$utrEscaped', 
                                     RESPMSG='$statusEscaped', PAYMENTMODE='UPI QR'
                                 WHERE txn_id = '$orderIdEscaped'";

                        $userUpdate = $ahk_conn->query($sql1);
                        $walletUpdate = $ahk_conn->query($sql2);

                        ob_end_clean();
                        echo "<!DOCTYPE html><html><head>
                        <meta charset='UTF-8'>
                        <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                        </head><body>";

                        if ($userUpdate && $walletUpdate) {
                            $_SESSION['wallet_updated'][$order_id] = true;
                            echo "<script>
                            Swal.fire({
                                title: 'SUCCESS',
                                text: 'Your registration was successful.',
                                icon: 'success'
                            }).then(() => {
                                window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                            });
                            </script>";
                        } else {
                            $errorMsg = addslashes($ahk_conn->error);
                            echo "<script>
                            Swal.fire({
                                title: 'FAILED',
                                text: 'Database update failed: {$errorMsg}',
                                icon: 'error'
                            }).then(() => {
                                window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                            });
                            </script>";
                        }
                        echo "</body></html>";
                        exit();

                    } else {
                        ob_end_clean();
                        echo "<!DOCTYPE html><html><head>
                        <meta charset='UTF-8'>
                        <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                        </head><body>
                        <script>
                        Swal.fire({
                            title: 'Invalid Amount',
                            text: 'You paid ₹{$amount}, but minimum ₹{$minimum_amount} required.',
                            icon: 'error'
                        }).then(() => {
                            window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                        });
                        </script></body></html>";
                        exit();
                    }
                } else {
                    ob_end_clean();
                    echo "<!DOCTYPE html><html><head>
                    <meta charset='UTF-8'>
                    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                    </head><body>
                    <script>
                    Swal.fire({
                        title: 'Payment Failed',
                        text: 'Your payment was not completed.',
                        icon: 'warning'
                    }).then(() => {
                        window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
                    });
                    </script></body></html>";
                    exit();
                }
            } else {
                ob_end_clean();
                die("Unexpected API response structure.");
            }
        }
    } else {
        ob_end_clean();
        echo "<script>
            alert('Payment already processed.');
            window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/admin/';
        </script>";
        exit();
    }
} else {
    ob_end_clean();
    echo "<script>
        alert('Session expired or invalid access.');
        window.location.href = 'https://" . $_SERVER['SERVER_NAME'] . "/';
    </script>";
    exit();
}
?>