<?php
ob_start(); // Start output buffering to prevent header issues
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

if (isset($_SESSION['order_id']) && isset($_SESSION['customer_mobile'])) {

    $order_id = $_SESSION['order_id'];
    $customer_mobile = $_SESSION['customer_mobile'];
    $minimum_amount = 49; // Minimum allowed amount

    if (!isset($_SESSION['wallet_updated'][$order_id])) {
        $url = "https://$flexsecure_upiUrl/api/check-order-status";
        $postData = [
            "user_token" => $flexsecure_upikey,
            "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)) {
            $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.");
        }

        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"] ?? '';

           

            // Success case
            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();
}
?>
