<?php
// PHP Script: quintuspay_secure_handler.php
// Uddeshya: Quintus Pay ke liye OTP bhejne aur OTP verify karke database ko surakshit tareeke se update karna.

// Zaroori constants define karein
define('cxrpaysecureheader', true);
define('ABSPATH', dirname(__FILE__) . '/'); 
define('QUINTUS_API_BASE_URL', 'https://miniapi.shop/api/quintustech/');

// Database connection aur user data (header.php se aane waale) include karein
// Maana jaata hai ki header.php mein $conn (mysqli object) aur $userdata (user info array) available hain.
require_once(ABSPATH . 'header.php');

session_start(); // Session start karna zaroori hai

// --- Helper function for SweetAlert responses (Alert dikhane ke liye) ---
function showSweetAlert($icon, $title, $text = '', $redirect = null, $showConfirm = true) {
    // JavaScript ke liye strings ko escape karein
    $title_esc = addslashes($title);
    $text_esc = addslashes($text);
    $redirect_js = $redirect ? "window.location.href = '{$redirect}';" : "";
    $confirm_button = $showConfirm ? 'true' : 'false';

    // SweetAlert ke liye zaroori JS output karein
    echo '<script src="js/jquery-3.2.1.min.js"></script>';
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
    echo "<script>
        // Loading indicator chhupayein
        if(typeof $ !== 'undefined') { $('#loading_ajax').hide(); }
        Swal.fire({
            icon: '{$icon}',
            title: '{$title_esc}',
            text: '{$text_esc}',
            showConfirmButton: {$confirm_button},
            confirmButtonText: 'Ok!',
            allowOutsideClick: false,
            allowEscapeKey: false
        }).then((result) => {
            if (result.isConfirmed) {
                {$redirect_js}
            }
        });
    </script>";
    exit();
}

// =========================================================================
// --- Step 2: OTP Verification aur DB Update (Jab user OTP submit karta hai) ---
// =========================================================================
if(isset($_POST['verifyotp'])) {
    global $conn, $userdata;

    // 1. Inputs ko sanitize aur validate karein
    $mobileNumber = filter_var($_POST['quintuspay_mobile'] ?? $_REQUEST['number'], FILTER_SANITIZE_STRING);
    $otp = filter_var($_POST['OTP'], FILTER_VALIDATE_INT);
    $otpId = filter_var($_POST['otpid'], FILTER_SANITIZE_STRING); // Original code mein tha, bhale hi API mein use na ho
    $sessionMobile = $_SESSION['username'] ?? $userdata['mobile'] ?? null;
    
    if ($otp === false || empty($mobileNumber) || empty($sessionMobile)) {
        showSweetAlert('error', 'Invalid Input', 'Kripya sahi OTP aur mobile number dein.', 'connect_merchant');
    }

    // --- 2. OTP Verify karein (miniapi.shop/verify_otp.php) ---
    $url = QUINTUS_API_BASE_URL . "verify_otp.php?mobile={$mobileNumber}&otp={$otp}";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_GET, true);
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        curl_close($ch);
        showSweetAlert('error', 'API Error', 'Verification Curl Error: ' . curl_error($ch), 'connect_merchant');
    }
    curl_close($ch);
    
    $responseArray = json_decode($response, true);
    $status = $responseArray['status'] ?? 'failure';
    
    if ($status !== 'success') {
        $errorMessage = $responseArray['message'] ?? 'OTP verification failed via API.';
        showSweetAlert('error', 'Verification Failed', $errorMessage, 'connect_merchant');
    }
    
    $accessToken = $responseArray['accessToken'] ?? null;
    if (empty($accessToken)) {
        showSweetAlert('error', 'API Data Missing', 'Access Token nahi mila.', 'connect_merchant');
    }

    // --- 3. UPI ID Fetch karein (miniapi.shop/upi_id.php) ---
    $url = QUINTUS_API_BASE_URL . "upi_id.php?token={$accessToken}";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_GET, true);
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        curl_close($ch);
        showSweetAlert('error', 'API Error', 'UPI Fetch Curl Error: ' . curl_error($ch), 'connect_merchant');
    }
    curl_close($ch);
    
    $responseArray = json_decode($response, true);
    $status_upi = $responseArray['status'] ?? 'FAILURE';
    $upiid = $responseArray['vpa'] ?? null;

    if ($status_upi !== 'SUCCESS' || empty($upiid)) {
        $errorMessage = $responseArray['message'] ?? 'UPI ID fetch mein error.';
        showSweetAlert('error', 'UPI Fetch Failed', $errorMessage, 'connect_merchant');
    }
    
    // --- 4. Database Transaction Shuru karein (SECURITY CRITICAL STEP) ---
    mysqli_begin_transaction($conn);
    
    try {
        // A. User ID, Token, aur MERCHENTROUTING surakshit tareeke se fetch karein
        // FIX: 'route' column ko 'merchentRouting' se badla gaya hai, jaisa ki aapke SQL dump mein hai.
        $getUserTokenQuery = "SELECT id, user_token, merchentRouting FROM users WHERE mobile = ?";
        $stmt_user = mysqli_prepare($conn, $getUserTokenQuery);
        if (!$stmt_user) throw new Exception("DB Prep Error (User): " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($stmt_user, "s", $sessionMobile);
        mysqli_stmt_execute($stmt_user);
        $result_user = mysqli_stmt_get_result($stmt_user);
        
        if (!$result_user || mysqli_num_rows($result_user) === 0) {
            mysqli_stmt_close($stmt_user);
            throw new Exception("User data nahi mila.");
        }
        
        $userData = mysqli_fetch_assoc($result_user);
        $user_token = $userData['user_token'];
        $user_id = $userData['id'];
        // FIX: $route variable mein 'merchentRouting' ka value assign karein
        $route = $userData['merchentRouting']; 
        mysqli_stmt_close($stmt_user);


        // B. quintuspay_token table ko surakshit tareeke se update karein
        $updateTokenQuery = "UPDATE quintuspay_token SET token=?, upi_id=?, status='Active', user_id=? WHERE user_token=? AND phoneNumber=?";
        $stmt_tokens = mysqli_prepare($conn, $updateTokenQuery);
        if (!$stmt_tokens) throw new Exception("DB Prep Error (Tokens): " . mysqli_error($conn));

        // Parameter types: s-string, s-string, i-integer, s-string, s-string
        mysqli_stmt_bind_param($stmt_tokens, "ssiss", $accessToken, $upiid, $user_id, $user_token, $mobileNumber);
        if (!mysqli_stmt_execute($stmt_tokens)) {
            throw new Exception("quintuspay_token update mein fail.");
        }
        mysqli_stmt_close($stmt_tokens);

        // C. users table mein quintuspay_connected='Yes' set karein
        $updateUserStatus = "UPDATE users SET quintuspay_connected='Yes' WHERE user_token=?";
        $stmt_user_status = mysqli_prepare($conn, $updateUserStatus);
        if (!$stmt_user_status) throw new Exception("DB Prep Error (User Status): " . mysqli_error($conn));

        mysqli_stmt_bind_param($stmt_user_status, "s", $user_token);
        if (!mysqli_stmt_execute($stmt_user_status)) {
            throw new Exception("User connection status update mein fail.");
        }
        mysqli_stmt_close($stmt_user_status);
        
        
        // D. Agar merchentRouting 0 hai to dusre merchants ko deactivate karein
        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"];

            // Tables mein tokens deactivate karein
            foreach ($tablesarr as $table) {
                $deactivateQuery = "UPDATE `$table` SET status = 'Deactive' WHERE user_token = ?";
                $stmt_deactivate = mysqli_prepare($conn, $deactivateQuery);
                if (!$stmt_deactivate) throw new Exception("DB Prep Error (Deactivate $table): " . mysqli_error($conn));
                
                mysqli_stmt_bind_param($stmt_deactivate, "s", $user_token);
                mysqli_stmt_execute($stmt_deactivate);
                mysqli_stmt_close($stmt_deactivate);
            }

            // User connection status columns ko 'No' karein
            foreach ($connected_merarr as $connected_col) {
                $deactivateConnQuery = "UPDATE users SET `$connected_col` = 'No' WHERE user_token = ?";
                $stmt_deactivate_conn = mysqli_prepare($conn, $deactivateConnQuery);
                if (!$stmt_deactivate_conn) throw new Exception("DB Prep Error (Deactivate Conn $connected_col): " . mysqli_error($conn));

                mysqli_stmt_bind_param($stmt_deactivate_conn, "s", $user_token);
                mysqli_stmt_execute($stmt_deactivate_conn);
                mysqli_stmt_close($stmt_deactivate_conn);
            }
        }

        // 5. Transaction Commit karein (Saare changes save karein)
        mysqli_commit($conn);
        showSweetAlert('success', 'Mubarak ho! Successfully Connected!', 'Aapka Quintus Pay safaltapoorvak connect ho gaya hai.', 'connect_merchant');

    } catch (Exception $e) {
        // 6. Fail hone par Rollback karein (Saare changes undo karein)
        mysqli_rollback($conn);
        error_log("Quintus Pay Transaction Failed: " . $e->getMessage());
        showSweetAlert('error', 'Connection Failed', 'Kripya baad mein dobara prayas karein. (Error: ' . $e->getMessage() . ')', 'connect_merchant');
    }
} 

// =========================================================================
// --- Step 1: OTP Bhejna aur Form Dikhana (Jab user mobile number submit karta hai) ---
// =========================================================================
elseif(isset($_POST['Verify'])) {
    global $userdata, $conn;

    $mobileNumber = filter_var($_POST["quintuspay_mobile"], FILTER_SANITIZE_STRING);
    
    // 1. Pehle se connected status check karein (Secure check)
    if ($userdata['quintuspay_connected'] == "Yes") {
        $checkQuery = "SELECT phoneNumber FROM quintuspay_token WHERE phoneNumber = ? AND status = 'Active'";
        $stmt_check = mysqli_prepare($conn, $checkQuery);
        if ($stmt_check) {
            mysqli_stmt_bind_param($stmt_check, "s", $mobileNumber);
            mysqli_stmt_execute($stmt_check);
            mysqli_stmt_store_result($stmt_check);
            $ixcheck = mysqli_stmt_num_rows($stmt_check) > 0;
            mysqli_stmt_close($stmt_check);
        } else {
            $ixcheck = false;
        }
        
        if ($ixcheck) {
            showSweetAlert('error', 'Merchant Pehle se Connected Hai!', '', 'connect_merchant');
        }       
    }

    // 2. OTP Bhejein (miniapi.shop/send_otp.php)
    $url = QUINTUS_API_BASE_URL . "send_otp.php?mobile={$mobileNumber}";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_GET, true);
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        curl_close($ch);
        showSweetAlert('error', 'API Error', 'OTP Send Curl Error: ' . curl_error($ch), 'connect_merchant');
    }
    curl_close($ch);
    
    $responseArray = json_decode($response, true);
    $status = $responseArray['status'] ?? 0;
    $otpId = $responseArray['authid'] ?? '';
    
    if ($status == 200) {
        
        // 3. SweetAlert ke zariye OTP entry form dikhayein
        echo '<script src="js/jquery-3.2.1.min.js"></script>';
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
        echo '<script>
            if(typeof $ !== \'undefined\') { $("#loading_ajax").hide(); }
            Swal.fire({
                title: "Aapka OTP Bhej Diya Gaya Hai!",
                text: "Kripya Ok button click karein!",
                icon: "success",
                showConfirmButton: true,
                confirmButtonText: "Ok"
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: "Quintus Pay UPI Settings",
                        html: `
                            <form id="quintuspayForm" method="POST" action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '" class="mb-2">
                                <div class="row" id="merchant">
                                    <div class="col-md-12 mb-2">
                                        <label for="OTP">OTP Darj Karein</label>
                                        <input type="number" name="OTP" id="OTP" placeholder="OTP Darj Karein" class="form-control" required>
                                    </div>
                                    <input type="hidden" name="quintuspay_mobile" value="' . htmlspecialchars($mobileNumber) . '">
                                    <input type="hidden" name="otpid" value="' . htmlspecialchars($otpId) . '">
                                    <div class="col-md-12 mb-2">
                                        <button type="submit" name="verifyotp" class="btn btn-primary btn-block mt-2">Verify OTP</button>
                                    </div>
                                </div>
                            </form>
                        `,
                        showCancelButton: false,
                        showConfirmButton: false,
                        customClass: {
                            popup: "swal2-custom-popup",
                            title: "swal2-title",
                            content: "swal2-content"
                        },
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    });
                }
            });
        </script>';
        // Form ke liye style
        ?>
        <style>
            .swal2-custom-popup { max-width: 600px; padding: 2em; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); }
            .swal2-title { font-size: 24px; margin-bottom: 1em; color: #333; font-weight: bold; }
            .swal2-content { text-align: left; }
            .swal2-content form { display: flex; flex-direction: column; }
            .swal2-content .row { display: flex; flex-wrap: wrap; }
            .swal2-content .col-md-12 { flex: 0 0 100%; max-width: 100%; padding: 0 15px; box-sizing: border-box; }
            .swal2-content label { font-weight: bold; color: #555; margin-bottom: 5px; }
            .swal2-content input { margin-top: 0.5em; padding: 0.5em; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; }
            .swal2-content .btn-block { width: 100%; margin-top: 1em; padding: 0.75em; font-size: 16px; background-color: #007bff; border: none; border-radius: 5px; color: white; cursor: pointer; }
            .swal2-content .btn-block:hover { background-color: #0056b3; }
        </style>
        <?php
        exit();

    } else {
        // 4. OTP Bhejne mein fail
        $errorMessage = $responseArray['response']['message'] ?? 'OTP bhejte samay error.';
        showSweetAlert('error', $errorMessage, '', 'connect_merchant');
    }
} 

// --- Default Fallback (Agar koi form submit nahi hua) ---
else {
    showSweetAlert('error', 'Form Submit Nahi Hua!', '', 'connect_merchant');
}
?>

<!-- Footer aur JS files (Jaise aapke original code mein the) -->
<script src="assets/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="assets/plugins/metismenu/metisMenu.min.js"></script>
<script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>