<?php

// Define the absolute path to the functions.php file
define('ABSPATH', dirname(__FILE__) . '/'); // Adjust the path as needed
// Include the database connection file
require_once(ABSPATH . 'header.php');

?>


<?php

// Function to sanitize user input
function sanitizeInput($input) {
    if (is_string($input)) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    } else {
        return $input;
    }
}

if (isset($_POST['verifyotp'])) {

    $bbbyteuserid       = $_SESSION['user_id'];
    $bbytefampayuserid  = $userdata['user_token'];
    $bbytefampayupi     = trim($_POST["UPI"]);
    $bbytefampaygmail   = trim($_POST["GMAIL"]);
    $bbytefampayapppass = trim($_POST["APPPASSWORD"]);

    // ----- Try logging into Gmail via IMAP using the App Password -----
    $loginOk  = false;
    $errorMsg = '';

    if (!function_exists('imap_open')) {
        $errorMsg = "Server par IMAP extension enable nahi hai. cPanel > Select PHP Extensions me 'imap' ON karke dobara try karein.";
    } elseif (!filter_var($bbytefampaygmail, FILTER_VALIDATE_EMAIL)) {
        $errorMsg = "Gmail address sahi format me nahi hai.";
    } else {
        $mailbox = '{imap.gmail.com:993/imap/ssl}INBOX';
        // Suppress warnings, we handle failure via return value + imap_last_error()
        $imapStream = @imap_open($mailbox, $bbytefampaygmail, $bbytefampayapppass);

        if ($imapStream !== false) {
            $loginOk = true;
            imap_close($imapStream);
        } else {
            $loginOk  = false;
            $errorMsg = imap_last_error() ? imap_last_error() : "Gmail login fail ho gaya. App Password check karein.";
        }
    }

    if ($loginOk) {

        $bbytefampayupi_esc     = mysqli_real_escape_string($conn, $bbytefampayupi);
        $bbytefampaygmail_esc   = mysqli_real_escape_string($conn, $bbytefampaygmail);
        $bbytefampayapppass_esc = mysqli_real_escape_string($conn, $bbytefampayapppass);

        $sqlUpdateUser = "UPDATE users SET fampay_connected='Yes' WHERE user_token='$bbytefampayuserid'";
        mysqli_query($conn, $sqlUpdateUser);

        $sqlw = "UPDATE fampay_tokens SET upi_id='$bbytefampayupi_esc', gmail='$bbytefampaygmail_esc', app_password='$bbytefampayapppass_esc', status='Active', user_id=$bbbyteuserid WHERE user_token='$bbytefampayuserid'";
        $result = mysqli_query($conn, $sqlw);

        if ($result) {
            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_ajax").hide();
                Swal.fire({
                    icon: "success",
                    title: "Congratulations! Your FamPay Has been Connected Successfully!",
                    showConfirmButton: true,
                    confirmButtonText: "Ok!",
                    allowOutsideClick: false,
                    allowEscapeKey: false
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = "connect_merchant";
                    }
                });
            </script>';
            exit();
        } else {
            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_ajax").hide();
                Swal.fire({
                    icon: "error",
                    title: "Please Try Again Later!!",
                    showConfirmButton: true,
                    confirmButtonText: "Ok!",
                    allowOutsideClick: false,
                    allowEscapeKey: false
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = "connect_merchant";
                    }
                });
            </script>';
            exit();
        }

    } else {
        // Gmail login failed - do NOT mark connected
        $errorMsgJs = addslashes($errorMsg);
        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_ajax").hide();
            Swal.fire({
                icon: "error",
                title: "Gmail Login Failed!",
                text: "' . $errorMsgJs . '",
                showConfirmButton: true,
                confirmButtonText: "Ok!",
                allowOutsideClick: false,
                allowEscapeKey: false
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "connect_merchant";
                }
            });
        </script>';
        exit();
    }
}

if (isset($_POST['Verify'])) { // opened from connect_merchant page

    if ($userdata['fampay_connected'] == "Yes") {
        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_ajax").hide();
            Swal.fire({
                icon: "error",
                title: "Merchant Already Connected !!",
                showConfirmButton: true,
                confirmButtonText: "Ok!",
                allowOutsideClick: false,
                allowEscapeKey: false
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "connect_merchant";
                }
            });
        </script>';
        exit();
    }

    $fampay_mobile = preg_replace('/[^0-9]/', '', $_POST["fampay_mobile"]);
    ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>
    <script>
        // Instead of asking the merchant to type UPI ID / Gmail / App
        // Password by hand, send them straight to Google's own login +
        // consent screen. fampay_oauth_callback.php finishes the connect
        // once Google redirects back.
        window.location.href = "fampay_oauth_start.php?mobile=<?php echo urlencode($fampay_mobile); ?>";
    </script>
    <?php
} // isset Verify

else {

    echo '<script>
        Swal.fire({
            icon: "error",
            title: "Form Not Submitted!!",
            showConfirmButton: true,
            confirmButtonText: "Ok!",
            allowOutsideClick: false,
            allowEscapeKey: false
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "connect_merchant";
            }
        });
    </script>';
    exit;
}
?>

<!--bootstrap js-->
  <script src="assets/js/bootstrap.bundle.min.js"></script>

  <!--plugins-->
  <script src="assets/js/jquery.min.js"></script>
  <!--plugins-->
  <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>
