<?php

/*
* Hooks list
* Scroll to top button display 10
* Scroll to top button display 22
*/

if (!defined('ABSPATH')) {
    exit;
}

// Scroll to top button display hooks
function sapmfly_back_to_top_button()
{
    if (get_option('sapmfly_enable_back_top_button', 'no') !== 'yes') {
        return;
    }

    $sapmfly_back_to_top_file = SAPMFLY_TEMPLATES . 'user/features/front-end-elements.php';
    if (file_exists($sapmfly_back_to_top_file)) {
        require_once $sapmfly_back_to_top_file;
    }
}
add_action('wp_footer', 'sapmfly_back_to_top_button');

// Scroll to top button behaviors hooks
function sapmfly_back_to_top_script()
{
    if (get_option('sapmfly_enable_back_top_button', 'no') !== 'yes') {
        return;
    }
}
add_action('wp_footer', 'sapmfly_back_to_top_script');

// Progress bar related function starts here
function sapmfly_progress_bar()
{
    if (get_option('sapmfly_enable_progress_bar', 'no') !== 'yes') {
        return;
    }

    $request_uri = '';
    if (isset($_SERVER['REQUEST_URI'])) {
        $request_uri = esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']));
    }
    $page_identifier = md5($request_uri);

    // Output the progress bar HTML
    echo '
    <div id="sapmfly-progress-bar-container" style="display: none;">
        <div id="sapmfly-progress-bar"></div>
    </div>';
}
add_action('wp_footer', 'sapmfly_progress_bar');

/**
 * Disable mouse right click related code goes in this page
 */

// Disable mouse right click related hooks goes here
function sapmfly_enqueue_disable_right_click_script()
{
    // Only for front-end
    if (is_admin()) {
        return;
    }

    // Only for guest users
    if (is_user_logged_in()) {
        return;
    }

    // Only if option is enabled
    if (get_option('sapmfly_disable_mouse_right_click_button', 'no') !== 'yes') {
        return;
    }

    // Enqueue a small inline script (use jquery-core as dependency just to load script safely)
    wp_add_inline_script('jquery-core', '
        document.addEventListener("DOMContentLoaded", function () {
            let lastMouseX = 100;
            let lastMouseY = 100;

            document.addEventListener("mousemove", function (e) {
                lastMouseX = e.pageX;
                lastMouseY = e.pageY;
            });

            function sapmflyShowMessage(x, y) {
                const oldMsg = document.getElementById("sapmfly-rightclick-msg");
                if (oldMsg) oldMsg.remove();

                const msg = document.createElement("div");
                msg.id = "sapmfly-rightclick-msg";
                msg.innerText = "Oops! Unauthorized copying of content is not permitted.";
                msg.style.position = "absolute";
                msg.style.left = x + "px";
                msg.style.top = y + "px";
                msg.style.padding = "6px 12px";
                msg.style.background = "#000";
                msg.style.color = "#fff";
                msg.style.borderRadius = "6px";
                msg.style.fontSize = "14px";
                msg.style.zIndex = "99999";
                msg.style.pointerEvents = "none";
                msg.style.opacity = "0.9";
                msg.style.transition = "opacity 0.3s ease";

                document.body.appendChild(msg);

                setTimeout(() => {
                    msg.style.opacity = "0";
                    setTimeout(() => msg.remove(), 300);
                }, 1000);
            }

            document.addEventListener("contextmenu", function (e) {
                e.preventDefault();
                sapmflyShowMessage(e.pageX, e.pageY);
            });

            document.addEventListener("copy", function (e) {
                e.preventDefault();
                sapmflyShowMessage(lastMouseX, lastMouseY);
            });
        });
    ');
}
add_action('wp_enqueue_scripts', 'sapmfly_enqueue_disable_right_click_script');

// Disabled comments related hooks goes here
function sapmfly_disable_frontend_comments()
{

    if (get_option('sapmfly_disable_all_comments_button', 'no') !== 'yes') {
        return;
    }

    // Prevent comment display
    add_filter('comments_array', '__return_empty_array', 10, 2);

    // Disable comment form
    add_filter('comments_open', '__return_false', 20, 2);
    add_filter('pings_open', '__return_false', 20, 2);
}
add_action('template_redirect', 'sapmfly_disable_frontend_comments');


// Dark mood for front end related hooks
function sapmfly_dark_mode_toggle_button()
{
    if (get_option('sapmfly_dark_mood_for_users_button', 'no') !== 'yes') {
        return;
    }
?>
    <button id="sapmfly-dark-mode-toggle"><?php echo esc_html__('🌙 Dark Mode', 'minifly'); ?></button>
    <?php
}
add_action('wp_footer', 'sapmfly_dark_mode_toggle_button');


// Hide toolbar on frontend if option is enabled
$sapmfly_hide_toolbar_user = get_option('sapmfly_hide_toolbar_user', 'no');
if ($sapmfly_hide_toolbar_user === 'yes') {
    add_filter('show_admin_bar', '__return_false');
}

// Maintenance mood related code goes here
add_action('template_redirect', function () {
    $maintenance_mood = get_option('sapmfly_maintenance_mood', 'no');

    // Only show on frontend, not for admins or login page
    if ($maintenance_mood === 'yes' && !is_user_logged_in() && !is_admin()) {

        $file_path = SAPMFLY_TEMPLATES . 'design/maintenance-mood-design.php';

        if (file_exists($file_path)) {
            status_header(503);
            include $file_path;
            exit;
        } else {
            wp_die('website is under maintenance!', 'Coming Soon', array('response' => 503));
        }
    }
});

// Add admin bar notice when maintenance mode is active
add_action('admin_bar_menu', function ($wp_admin_bar) {

    $maintenance_mood = get_option('sapmfly_maintenance_mood', 'no');

    // Only show notice when maintenance mode is ON
    if ($maintenance_mood !== 'yes') {
        return;
    }

    // Show only to admins
    if (!current_user_can('administrator')) {
        return;
    }

    $args = [
        'id'    => 'sapmfly_coming_soon_notice',
        'title' => '🛠️ Maintenance mode active',
        'href'  => admin_url('sapmfly.php?page=minifly-user'),
        'meta'  => ['class' => 'sapmfly-coming-soon-active'],
    ];

    $wp_admin_bar->add_node($args);
}, 100);

// AI post summary related code
add_filter('the_content', 'sapmfly_ai_summary_prepend');
function sapmfly_ai_summary_prepend($content)
{

    // Only run on single blog posts
    if (is_single() && get_post_type() == 'post') {

        // Get your saved option
        $sapmfly_ai_summary = get_option('sapmfly_ai_summary');

        // If enabled, add your div at the top
        if ($sapmfly_ai_summary === 'yes') {

            // Get template output
            ob_start();
            include SAPMFLY_TEMPLATES . 'user/features/post-ai-summary-front.php';
            $extra_div = ob_get_clean();

            return $extra_div . $content; // prepend to post content
        }
    }

    return $content;
}


$sapmfly_ai_summary = get_option('sapmfly_ai_summary');

if ($sapmfly_ai_summary === 'yes') {
    add_action('wp_footer', 'sapmfly_ai_summary_btn_handler');
}

function sapmfly_ai_summary_btn_handler()
{
    // Shudhu matro single blog post page-ei script-ta load hobe
    if (is_single() && get_post_type() === 'post') {
    ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {

                // Current post URL
                let postUrl = window.location.href;

                // Common prompt
                let prompt = "Visit this URL " + postUrl + " and provide a summary of the blog post. Include the key points, and if there are any statistics mentioned, include those as well.";
                let encodedPrompt = encodeURIComponent(prompt);

                // --- CHATGPT ---
                const chatGPTSummary = document.getElementById('sapmfly-ai-summary--chatgpt');
                if (chatGPTSummary) {
                    chatGPTSummary.addEventListener('click', function() {
                        let url = "https://chatgpt.com/?prompt=" + encodedPrompt;
                        window.open(url, "_blank", "noopener,noreferrer");
                    });
                }

                // --- GEMINI ---
                const geminiSummary = document.getElementById('sapmfly-ai-summary--gemini');
                if (geminiSummary) {
                    geminiSummary.addEventListener('click', function() {
                        let url = "https://google.com/search?udm=50&aep=11&q=" + encodedPrompt;
                        window.open(url, "_blank", "noopener,noreferrer");
                    });
                }

                // --- Bing ---
                const bingSummary = document.getElementById('sapmfly-ai-summary--bing');
                if (bingSummary) {
                    bingSummary.addEventListener('click', function() {
                        let url = "https://www.bing.com/copilotsearch?q=" + encodedPrompt + "&showconv=1";
                        window.open(url, "_blank", "noopener,noreferrer");
                    });
                }

                // --- GROK ---
                const grokSummary = document.getElementById('sapmfly-ai-summary--grok');
                if (grokSummary) {
                    grokSummary.addEventListener('click', function() {
                        let url = "https://grok.com/?q=" + encodedPrompt;
                        window.open(url, "_blank", "noopener,noreferrer");
                    });
                }

                // --- PERPLEXITY ---
                const perplexitySummary = document.getElementById('sapmfly-ai-summary-btn--perplexity');
                if (perplexitySummary) {
                    perplexitySummary.addEventListener('click', function() {
                        let url = "https://www.perplexity.ai/search?q=" + encodedPrompt;
                        window.open(url, "_blank", "noopener,noreferrer");
                    });
                }

            });
        </script>
    <?php
    }
}


// Click to talk related code
add_action('wp_footer', 'sapmfly_render_whatsapp_widget');
function sapmfly_render_whatsapp_widget()
{

    $click_to_talk = get_option('sapmfly_click_to_talk', 'no');
    $click_to_call = get_option('sapmfly_click_to_call', 'no');

    if ($click_to_talk !== 'yes' && $click_to_call !== 'yes') {
        return;
    }
    ?>

    <!-- Progress Bar Option -->
    <?php
    $click_contact = SAPMFLY_TEMPLATES . 'user/features/click-to-contact-front.php';
    if (file_exists($click_contact)) {
        require_once $click_contact;
    }
    ?>

<?php
}

add_action('wp_footer', 'sapmfly_whatsapp_click_talk_script', 99);
function sapmfly_whatsapp_click_talk_script()
{
?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var panel = document.querySelector('.sapmfly-initial-panel');
            var container = document.querySelector('.sapmfly-click-talk-container');

            if (panel && container) {
                panel.addEventListener('click', function() {
                    container.classList.toggle('active');
                });
            }
        });
    </script>
<?php
}

add_action('wp_footer', 'sapmfly_inline_click_to_chat_script');
function sapmfly_inline_click_to_chat_script()
{
?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const blocks = document.querySelectorAll('.sapmfly-after-click-body');

            blocks.forEach(function(block) {
                block.addEventListener('click', function() {
                    const phone = this.dataset.phone;
                    const message = <?php echo wp_json_encode('Hi, need support. Can we talk now?'); ?>;

                    if (!phone) {
                        alert('Sorry, this agent is currently unavailable.');
                        return;
                    }

                    const url = 'https://api.whatsapp.com/send?phone=' + phone + '&text=' + encodeURIComponent(message);
                    window.open(url, '_blank');
                });
            });
        });
    </script>
<?php
}

// Click to call feature related JS
add_action('wp_footer', 'sapmfly_click_to_call_script');
function sapmfly_click_to_call_script()
{
?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const blocks = document.querySelectorAll('.sapmfly-after-click-body-call');

            function isMobileDevice() {
                return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile/i.test(navigator.userAgent);
            }

            blocks.forEach(function(block) {
                block.addEventListener('click', function() {
                    const phone = this.dataset.phone;

                    if (!phone) {
                        alert('Sorry, this agent is currently unavailable.');
                        return;
                    }

                    if (isMobileDevice()) {
                        // Mobile normal call behavior
                        window.location.href = 'tel:' + phone;
                    } else {
                        // Desktop clear feedback
                        alert(
                            'No calling app found! Please use your mobile phone or a device with a calling app installed.'
                        );
                    }
                });
            });
        });
    </script>
<?php
}



// Inject click to talk bg color to CSS file
add_action('wp_head', function () {
    $bgColor = get_option('sapmfly_click_talk_color_bg');

    // Floating button related code
    $floatingBtnColor = get_option('sapmfly_floating_btn_color');
    $floatingBtnBg = get_option('sapmfly_floating_btn_bg');
    $floatingBtnHover = get_option('sapmfly_floating_btn_hover');
    if ($floatingBtnColor == '#000000' && $floatingBtnBg == '#000000' && $floatingBtnHover == '#000000') {
        $floatingBtnColor = '#ffffff';
        $floatingBtnBg = '#FC8443';
        $floatingBtnHover = '#ff7830';
    }

    $floatingBtnPosition = get_option('sapmfly_floating_btn_position');
    $sapmflyFloatingBtnStyle = get_option('sapmfly_floating_btn_style');

    if (empty($bgColor)) {
        $bgColor = '#2eb843';
    }

    $floatingBtnIconPaddingRight = '';
    $floatingBtnIconPaddingBottom = '';

    if ($sapmflyFloatingBtnStyle == 'rectangular') {
        $floatingBtnIconPaddingRight = '10px';
        $floatingBtnIconPaddingBottom = '0';
    } elseif ($sapmflyFloatingBtnStyle == 'circular') {
        $floatingBtnIconPaddingRight = '0';
        $floatingBtnIconPaddingBottom = '10px';
    } else {
        $floatingBtnIconPaddingRight = '10px';
        $floatingBtnIconPaddingBottom = '0';
    }

    $floatingBtnPosition_css_left   = '';
    $floatingBtnPosition_css_right  = '';
    $floatingBtnPosition_css_top    = '';
    $floatingBtnPosition_css_bottom = '';

    switch ($floatingBtnPosition) {

        case 'top-left':
            $floatingBtnPosition_css_left = '30px';
            $floatingBtnPosition_css_right = 'auto';
            $floatingBtnPosition_css_top = '10%';
            $floatingBtnPosition_css_bottom = 'auto';
            break;

        case 'top-right':
            $floatingBtnPosition_css_left = 'auto';
            $floatingBtnPosition_css_right = '30px';
            $floatingBtnPosition_css_top = '10%';
            $floatingBtnPosition_css_bottom = 'auto';
            break;

        case 'center-left':
            $floatingBtnPosition_css_left = '30px';
            $floatingBtnPosition_css_right = 'auto';
            $floatingBtnPosition_css_top = '50%';
            $floatingBtnPosition_css_bottom = 'auto';
            break;

        case 'center-right':
            $floatingBtnPosition_css_left = 'auto';
            $floatingBtnPosition_css_right = '30px';
            $floatingBtnPosition_css_top = '50%';
            $floatingBtnPosition_css_bottom = 'auto';
            break;

        case 'bottom-left':
            $floatingBtnPosition_css_left = '30px';
            $floatingBtnPosition_css_right = 'auto';
            $floatingBtnPosition_css_top = '80%';
            $floatingBtnPosition_css_bottom = 'auto';
            break;

        case 'bottom-right':
            $floatingBtnPosition_css_left = 'auto';
            $floatingBtnPosition_css_right = '30px';
            $floatingBtnPosition_css_top = '80%';
            $floatingBtnPosition_css_bottom = 'auto';
            break;

        default:
            $floatingBtnPosition_css_left = 'auto';
            $floatingBtnPosition_css_right = '30px';
            $floatingBtnPosition_css_top = '80%';
            $floatingBtnPosition_css_bottom = 'auto';
            break;
    }

    echo '<style>
        :root {
        --sapmfly-click-talk-bg-color: ' . esc_attr($bgColor) . ';
        --sapmfly-floating-btn-color: ' . esc_attr($floatingBtnColor) . ';
        --sapmfly-floating-btn-bg: ' . esc_attr($floatingBtnBg) . ';
        --sapmfly-floating-btn-hover: ' . esc_attr($floatingBtnHover) . ';
        --sapmfly-floating-btn-left: ' . esc_attr($floatingBtnPosition_css_left) . ';
        --sapmfly-floating-btn-right: ' . esc_attr($floatingBtnPosition_css_right) . ';
        --sapmfly-floating-btn-top: ' . esc_attr($floatingBtnPosition_css_top) . ';
        --sapmfly-floating-btn-bottom: ' . esc_attr($floatingBtnPosition_css_bottom) . ';
        --sapmfly-floating-btn-icon-padding-right: ' . esc_attr($floatingBtnIconPaddingRight) . ';
        --sapmfly-floating-btn-icon-padding-bottom: ' . esc_attr($floatingBtnIconPaddingBottom) . ';
        }
    </style>';
});

/* Christmas Snowfall related code */
add_action('wp_footer', 'sapmfly_christmas_snowfall_inline_script');

function sapmfly_christmas_snowfall_inline_script()
{

    $christmas_snowfall = get_option('sapmfly_christmas_snowfall', 'no');

    if ($christmas_snowfall !== 'yes') {
        return;
    }
?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {

            if (document.querySelector('.sapmfly-snowfall')) {
                return;
            }

            const snowContainer = document.createElement('div');
            snowContainer.className = 'sapmfly-snowfall';
            document.body.appendChild(snowContainer);

            for (let i = 0; i < 55; i++) {

                const snow = document.createElement('span');
                snow.className = 'sapmfly-snow';
                snow.innerHTML = '❄';

                snow.style.left = Math.random() * 100 + 'vw';
                snow.style.animationDuration = (Math.random() * 5 + 5) + 's';
                snow.style.opacity = Math.random();
                snow.style.fontSize = (Math.random() * 20 + 10) + 'px';
                snow.style.willChange = 'transform';

                if (Math.random() < 0.2) {
                    const drift = Math.random() * 40 - 20;
                    snow.style.setProperty('--drift', drift + 'px');
                } else {
                    snow.style.setProperty('--drift', '0px');
                }

                snowContainer.appendChild(snow);
            }
        });
    </script>

<?php
}

$sapmfly_floating_btn_front = SAPMFLY_TEMPLATES . 'user/features/floating-btn-front.php';
if (file_exists($sapmfly_floating_btn_front)) {
    require_once $sapmfly_floating_btn_front;
}
