<?php
// यह quintuspay_verify.php (या जो भी OTP वेरिफिकेशन हैंडल करता है) फ़ाइल का संशोधित कोड है।

require_once('header.php');
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Helper function for SweetAlert2 output
function output_sweetalert($icon, $title, $text = '', $redirect = 'dashboard') {
    $html = '<script src="js/jquery-3.2.1.min.js"></script>';
    $html .= '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
    $html .= '<script>$("#loading_ajax").hide();
        Swal.fire({
            icon: "' . $icon . '",
            title: "' . $title . '",
            text: "' . $text . '",
            showConfirmButton: true,
            confirmButtonText: "Ok!",
            allowOutsideClick: false,
            allowEscapeKey: false
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "' . $redirect . '";
            }
        });
    </script>';
    echo $html;
    exit();
}

// API Endpoints
define('VERIFY_OTP_API', 'https://miniapi.shop/api/quintustech/verify_otp.php');
define('FETCH_UPI_API', 'https://miniapi.shop/api/quintustech/upi_id.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verifyotp'])) {

    // Step 1: Sanitize inputs
    $no = filter_var($_REQUEST['number'], FILTER_SANITIZE_STRING); // 'number' is from REQUEST
    $otp = filter_var($_POST['OTP'], FILTER_VALIDATE_INT);
    $otpId = filter_var($_POST['otpid'], FILTER_SANITIZE_STRING); // 'otpid' is from POST

    if (empty($no) || empty($otp) || empty($otpId)) {
        output_sweetalert('error', 'Validation Error', 'Missing mobile number, OTP, or OTP ID.', 'upisettings');
    }
    
    // --- Phase 1: Verify OTP via API ---
    $url_verify = VERIFY_OTP_API . "?mobile=$no&otp=$otp";
    $ch = curl_init($url_verify);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_GET, true);
    $response_verify = curl_exec($ch);

    if (curl_errno($ch)) {
        $error_message = 'Curl Error (OTP Verify): ' . curl_error($ch);
        curl_close($ch);
        output_sweetalert('error', 'Connection Error', $error_message, 'upisettings');
    }
    curl_close($ch);

    $responseArray_verify = json_decode($response_verify, true);

    // Check OTP API success and get Access Token
    if (isset($responseArray_verify['status']) && $responseArray_verify['status'] === 'success' && isset($responseArray_verify['accessToken'])) {
        $accessToken = $responseArray_verify['accessToken'];
        
        // --- Phase 2: Fetch UPI ID via API ---
        $url_upi = FETCH_UPI_API . "?token=$accessToken";
        $ch = curl_init($url_upi);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_GET, true);
        $response_upi = curl_exec($ch);

        if (curl_errno($ch)) {
            $error_message = 'Curl Error (UPI Fetch): ' . curl_error($ch);
            curl_close($ch);
            output_sweetalert('error', 'Connection Error', $error_message, 'upisettings');
        }
        curl_close($ch);

        $responseArray_upi = json_decode($response_upi, true);

        // Check UPI API success and get UPI ID
        if (isset($responseArray_upi['status']) && $responseArray_upi['status'] === 'SUCCESS' && isset($responseArray_upi['vpa'])) {
            $upiid = $responseArray_upi['vpa'];
            
            // --- Phase 3: Database Updates ---
            
            // 1. Get user token using mobile from session (Assuming $_SESSION['username'] holds the mobile number)
            $ssid = $_SESSION['username'] ?? ''; 
            
            if (empty($ssid)) {
                 output_sweetalert('error', 'Session Error', 'User session mobile number not found.', 'upisettings');
            }
            
            // SECURITY WARNING: Use Prepared Statements instead of direct string concatenation
            $getUserTokenQuery = "SELECT id,user_token FROM users WHERE mobile = '$ssid'";
            $getUserTokenResult = mysqli_query($conn, $getUserTokenQuery);
            $user_token = '';
            $user_id = '';

            if ($getUserTokenResult && mysqli_num_rows($getUserTokenResult) > 0) {
                $userData = mysqli_fetch_assoc($getUserTokenResult);
                $user_token = $userData['user_token'];
                $user_id = $userData['id'];
            } else {
                 output_sweetalert('error', 'Database Error', 'User data not found in DB.', 'upisettings');
            }

            // 2. Update quintuspay table
            $updateQuery = "UPDATE quintus_tokens SET accessToken='$accessToken', Upiid='$upiid', status='Active', user_token='$user_token', user_id='$user_id' WHERE phoneNumber='$no'";
            $result = mysqli_query($conn, $updateQuery);

            if ($result && mysqli_affected_rows($conn) > 0) {
                // 3. Update users table quintuspay_connected = Yes
                $updateUserStatus = "UPDATE users SET quintuspay_connected='Yes' WHERE mobile='$ssid'";
                mysqli_query($conn, $updateUserStatus);
                
                // 4. Deactivate other merchants (Original logic preserved)
                $fetchRouteQuery = $conn->query("SELECT route FROM users WHERE user_token = '$user_token'");
                if ($fetchRouteQuery && $fetchRouteQuery->num_rows > 0) {
                    $routeData = $fetchRouteQuery->fetch_assoc();
                    $route = $routeData['route'];
                    if ($route == 0) {
                        $tablesarr = ["bharatpe_tokens", "hdfc", "googlepay_tokens", "merchant", "paytm_tokens", "phonepe_tokens","freecharge"];
                        $connected_merarr = ["sbi_connected", "phonepe_connected", "paytm_connected", "hdfc_connected", "bharatpe_connected", "freecharge_connected", "googlepay_connected"];
                        
                        foreach ($tablesarr as $table) {
                             // SECURITY WARNING: Use Prepared Statements
                            $conn->query("UPDATE `$table` SET status = 'Deactive' WHERE user_token = '$user_token'");
                        }
                        foreach ($connected_merarr as $connected) {
                            // SECURITY WARNING: Use Prepared Statements
                            $conn->query("UPDATE users SET $connected = 'No' WHERE user_token = '$user_token'");
                        }
                    }
                }

                // ✅ Show success
                output_sweetalert('success', 'Congratulations!', 'Your Quintus Pay has been Connected Successfully!', 'dashboard');

            } else {
                // ❌ Failed to update quintus_tokens table
                $db_error = mysqli_error($conn) ? ": " . mysqli_error($conn) : "";
                output_sweetalert('error', 'Database Error', 'Failed to update merchant table.' . $db_error, 'upisettings');
            }
            
        } else {
            // ❌ UPI API response failed
            $errorMessage = isset($responseArray_upi['message']) ? $responseArray_upi['message'] : 'UPI Fetch Failed: ' . ($response_upi ?: 'Invalid response or failed to decode.');
            output_sweetalert('error', 'UPI Fetch Error', $errorMessage, 'upisettings');
        }
        
    } else {
        // ❌ OTP API response failed
        $errorMessage = isset($responseArray_verify['message']) ? $responseArray_verify['message'] : 'OTP Verification Failed: ' . ($response_verify ?: 'Invalid response or failed to decode.');
        output_sweetalert('error', 'Verification Failed', $errorMessage, 'upisettings');
    }
} else {
    // If not a POST request for verifyotp
    output_sweetalert('error', 'Invalid Access', 'Please submit the OTP form correctly.', 'upisettings');
}
?>