<?php
if (!defined('ABSPATH'))
    exit;

/*
Plugin Name: Mori Chatbot
Description: Mori Chat Bot allows users to integrate a chatbot by simply adding a shortcode to any page.
Version: 3.5.1
Author: Mori Tech
Author URI:  https://mori.style/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

if (!defined('DORI_CHATBOT_PLUGIN_FILE')) {
    define('DORI_CHATBOT_PLUGIN_FILE', __FILE__);
}

if (!defined('DORI_CHATBOT_VERSION')) {
    define('DORI_CHATBOT_VERSION', '3.5.1');
}

$plugin_root = plugin_dir_path(__FILE__);
$vendor_autoload = $plugin_root . 'vendor/autoload.php';

if (!file_exists($vendor_autoload) && file_exists(dirname($plugin_root) . '/vendor/autoload.php')) {
    $vendor_autoload = dirname($plugin_root) . '/vendor/autoload.php';
}

if (file_exists($vendor_autoload)) {
    require_once $vendor_autoload;
}

require_once plugin_dir_path(__FILE__) . 'includes/services/class-api-constants.php';

require_once plugin_dir_path(__FILE__) . 'includes/core/class-plugin-loader.php';

Dori_Chatbot_Plugin_Loader::init();

function dori_chatbot_resource_hints()
{
    $widget_url = Dori_Chatbot_API_Constants::get_widget_url();
    $widget_host = parse_url($widget_url, PHP_URL_HOST);
    if (empty($widget_host)) {
        return;
    }
    ?>
    <link rel="dns-prefetch" href="//<?php echo esc_attr($widget_host); ?>">
    <link rel="preconnect" href="https://<?php echo esc_attr($widget_host); ?>" crossorigin>
    <?php
}

function dori_chatbot_get_page_type()
{
    if (function_exists("is_product") && is_product()) {
        return "pdp";
    }

    if (function_exists("is_shop") && is_shop()) {
        return "plp";
    }

    if (function_exists("is_product_taxonomy") && is_product_taxonomy()) {
        return "plp";
    }

    return null;
}

function dori_chatbot_inject_script()
{
    try {
        $sharing_id = Dori_Chatbot_Cache_Manager::get_sharing_id();
        if (empty($sharing_id))
            return;

        $product_id = Dori_Chatbot_Cache_Manager::get_current_product_id();

        $config = array(
            'sharingID' => $sharing_id,
            'productID' => !empty($product_id) ? $product_id : null,
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('dori_thread_session'),
            'pluginVersion' => DORI_CHATBOT_VERSION,
            'pageType' => dori_chatbot_get_page_type()
        );

        ?>
        <script>window.chatbotData = <?php echo wp_json_encode($config); ?>;</script>
        <script>
            (function () {
                function loadMoriWidget() {
                    if (document.getElementById('mori-react-widget')) {
                        return;
                    }

                    if (document.head) {
                        var script = document.createElement('script');
                        script.defer = true;
                        script.type = 'module';
                        script.id = 'mori-react-widget';
                        script.src = '<?php echo esc_js(Dori_Chatbot_API_Constants::get_widget_url()); ?>';
                        script.setAttribute('data-sharing-id', window.chatbotData.sharingID);
                        if (window.chatbotData.productID) {
                            script.setAttribute('data-product-id', window.chatbotData.productID);
                        }
                        script.setAttribute('data-ajaxurl', window.chatbotData.ajaxurl);
                        script.setAttribute('data-nonce', window.chatbotData.nonce);
                        script.setAttribute('data-plugin-version', window.chatbotData.pluginVersion);

                        document.head.appendChild(script);
                    } else {
                        if (document.readyState === 'loading') {
                            document.addEventListener('DOMContentLoaded', loadMoriWidget);
                        } else {
                            setTimeout(loadMoriWidget, 100);
                        }
                    }
                }

                loadMoriWidget();
            })();
        </script>
        <?php
    } catch (Exception $e) {
        return;
    }
}

function dori_chatbot_shortcode()
{
    return '<div id="chat-widget-container"></div>';
}

function dori_chatbot_activate()
{
    $widget_full_url = Dori_Chatbot_API_Constants::get_widget_url();
    $widget_host = parse_url($widget_full_url, PHP_URL_HOST);
    $widget_path = parse_url($widget_full_url, PHP_URL_PATH);
    $widget_base_path = !empty($widget_path) ? trim(dirname($widget_path), '/') : '';
    $widget_cdn_domain = !empty($widget_host) ? $widget_host . (!empty($widget_base_path) ? '/' . $widget_base_path : '') : '';
    $widget_package_name = 'mori-chat-widget';
    $widget_script_id = 'mori-react-widget';

    if (function_exists('update_rocket_option')) {
        $patterns_to_add = array(
            $widget_full_url,
            $widget_package_name,
            $widget_script_id
        );
        if (!empty($widget_cdn_domain)) {
            $patterns_to_add[] = $widget_cdn_domain;
        }

        $exclude_js = get_option('rocket_exclude_js', array());
        foreach ($patterns_to_add as $pattern) {
            if (!in_array($pattern, $exclude_js, true)) {
                $exclude_js[] = $pattern;
            }
        }
        update_rocket_option('rocket_exclude_js', $exclude_js);

        $exclude_defer = get_option('rocket_exclude_defer_js', array());
        foreach ($patterns_to_add as $pattern) {
            if (!in_array($pattern, $exclude_defer, true)) {
                $exclude_defer[] = $pattern;
            }
        }
        update_rocket_option('rocket_exclude_defer_js', $exclude_defer);

        $exclude_delay = get_option('rocket_delay_js_exclusions', array());
        foreach ($patterns_to_add as $pattern) {
            if (!in_array($pattern, $exclude_delay, true)) {
                $exclude_delay[] = $pattern;
            }
        }
        update_rocket_option('rocket_delay_js_exclusions', $exclude_delay);
    }

    if (class_exists('autoptimizeMain')) {
        $exclude_js = get_option('autoptimize_js_exclude', '');
        if (is_string($exclude_js)) {
            $exclude_array = array_filter(array_map('trim', explode(',', $exclude_js)));
            $patterns_to_add = array(
                $widget_full_url,
                $widget_package_name,
                $widget_script_id
            );
            foreach ($patterns_to_add as $pattern) {
                if (!in_array($pattern, $exclude_array, true)) {
                    $exclude_array[] = $pattern;
                }
            }
            update_option('autoptimize_js_exclude', implode(', ', $exclude_array));
        }
    }

    if (function_exists('litespeed_conf')) {
        $patterns_to_add = array(
            $widget_full_url,
            $widget_script_id
        );
        if (!empty($widget_cdn_domain)) {
            $patterns_to_add[] = $widget_cdn_domain;
        }

        $excludes = get_option('litespeed.conf.optm-js_excludes', array());
        if (!is_array($excludes)) {
            $excludes = array();
        }
        foreach ($patterns_to_add as $pattern) {
            if (!in_array($pattern, $excludes, true)) {
                $excludes[] = $pattern;
            }
        }
        update_option('litespeed.conf.optm-js_excludes', $excludes);

        $defer_excludes = get_option('litespeed.conf.optm-js_defer_excludes', array());
        if (!is_array($defer_excludes)) {
            $defer_excludes = array();
        }
        foreach ($patterns_to_add as $pattern) {
            if (!in_array($pattern, $defer_excludes, true)) {
                $defer_excludes[] = $pattern;
            }
        }
        update_option('litespeed.conf.optm-js_defer_excludes', $defer_excludes);
    }

    if (function_exists('w3tc_get_config')) {
        try {
            $config = w3tc_get_config();
            $exclude_js = $config->get_array('minify.js.reject');

            $patterns_to_add = array(
                $widget_full_url,
                $widget_package_name . '/widget.js',
                $widget_script_id
            );
            if (!empty($widget_cdn_domain)) {
                $patterns_to_add[] = $widget_cdn_domain;
            }

            foreach ($patterns_to_add as $pattern) {
                if (!in_array($pattern, $exclude_js, true)) {
                    $exclude_js[] = $pattern;
                }
            }

            $config->set('minify.js.reject', $exclude_js);
            $config->save();
        } catch (Exception $e) {
        }
    }

    if (class_exists('WP_Optimize')) {
        $patterns_to_add = array(
            $widget_full_url,
            $widget_package_name,
            $widget_script_id
        );

        $excludes = get_option('wpo_minify_js_excludes', array());
        if (!is_array($excludes)) {
            $excludes = array();
        }
        foreach ($patterns_to_add as $pattern) {
            if (!in_array($pattern, $excludes, true)) {
                $excludes[] = $pattern;
            }
        }
        update_option('wpo_minify_js_excludes', $excludes);

        $noptimize = get_option('wpo_minify_js_noptimize', '');
        if (is_string($noptimize)) {
            $noptimize_array = array_filter(array_map('trim', explode(',', $noptimize)));
            foreach ($patterns_to_add as $pattern) {
                if (!in_array($pattern, $noptimize_array, true)) {
                    $noptimize_array[] = $pattern;
                }
            }
            update_option('wpo_minify_js_noptimize', implode(', ', $noptimize_array));
        }
    }
}

add_action('init', function () {
    add_action('wp_head', 'dori_chatbot_resource_hints', 1);
    add_action('wp_head', 'dori_chatbot_inject_script', 2);
});

add_shortcode('dori-chatbot', 'dori_chatbot_shortcode');
register_activation_hook(__FILE__, 'dori_chatbot_activate');
