<?php
/*
Plugin Name: oct8ne
Plugin URI: https://oct8ne.com/
Description: Help your customers by showing them images and videos of your products using the coviewer to help them along in the decision making process.
Version: 1.2.5
Author: Oct8ne
License: GPL2
*/

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

require_once('helpers/loginhelper.php');
require_once('helpers/oct8neHtaccessHelper.php');
require_once('helpers/jsinfo.php');
require_once('helpers/oct8nedb.php');
require_once('helpers/search/searchfactory.php');
require_once('helpers/wishlist/wishlistfactory.php');
require_once('helpers/translation/translationfactory.php');

if (!class_exists('WC_Oct8ne_Plugin')) :

    class WC_Oct8ne_Plugin
    {

        /**
         * Singleton
         * @var
         */
        public static $instance;


        /**
         * Get or create class
         * @return WC_Oct8ne_Plugin
         */
        public static function get_instance()
        {
            if (null === self::$instance) {
                self::$instance = new self();
            }
            return self::$instance;
        }
        //http://hookr.io/plugins/woocommerce/#index=a
        //https://businessbloomer.com/woocommerce-visual-hook-guide-cart-page/

        /**
         * WC_Oct8ne_Plugin constructor.
         */
        protected function __construct()
        {
            add_action('admin_init', array($this, 'check_environment'));
            add_action('admin_notices', array($this, 'admin_notices'), 15);
            add_action('admin_menu', array($this, 'init'));

            //Position to load js
            $position = get_option('oct8ne_js_position', 'Footer');
            if ($position == 'Footer') {
                add_action('wp_footer', array($this, 'addOct8neJs'));
            } else if ($position == 'Header') {
                add_action('wp_head', array($this, 'addOct8neJs'));
            } else {
                add_action('wp_footer', array($this, 'addOct8neJs'));
                update_option('oct8ne_js_position', 'Footer');
            }

            //register hooks
            register_deactivation_hook(__FILE__, array('WC_Oct8ne_Plugin', 'unistall'));
            register_activation_hook(__FILE__, array('WC_Oct8ne_Plugin', 'install'));
            register_uninstall_hook(__FILE__, array('WC_Oct8ne_Plugin', 'fullUninstall'));

            add_action('admin_init', array($this, 'oct8ne_register_settings'));
            add_action('admin_init', array($this, 'oct8ne_handle_login'));
            add_action('admin_init', array($this, 'oct8ne_handle_logout'));
        }





        function oct8ne_settings_page()
        {
            $license = get_option('oct8ne_license');

            if (empty($license)) {
?>
                <div class="wrap">
                    <h2><?php echo esc_html__('Oct8ne plugin configuration', 'oct8ne') ?></h2>
                    <?php settings_errors('oct8ne_login'); ?>
                    <form method="post" action="">
                        <table class="form-table">
                            <tr valign="top">
                                <th scope="row"><?php echo esc_html__('Email', 'oct8ne'); ?></th>
                                <td><input type="email" name="oct8ne_email" class="regular-text" required /></td>
                            </tr>
                            <tr valign="top">
                                <th scope="row"><?php echo esc_html__('Password', 'oct8ne'); ?></th>
                                <td><input type="password" name="oct8ne_password" class="regular-text" required /></td>
                            </tr>
                        </table>
                        <?php submit_button(__('Login', 'oct8ne'), 'primary', 'oct8ne_login'); ?>
                    </form>
                </div>
            <?php
            } else {
            ?>
                <div class="wrap">
                    <h2><?php echo esc_html__('Oct8ne plugin configuration', 'oct8ne') ?></h2>
                    <form method="post" action="options.php">
                        <?php
                        settings_fields('oct8ne-settings-group');
                        do_settings_sections('oct8ne');
                        submit_button();
                        ?>
                    </form>
                    <form method='POST' action=''>
                        <h1>Session</h1>
                        <br>
                        <table>
                            <tr>
                                <th><label for="oct8ne_value">Email: </label></th>
                                <td>
                                    <span id='oct8ne_value'> <?php echo esc_html(get_option('oct8ne_email_linked')); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <?php submit_button('Logout', 'primary', 'oct8ne_logout'); ?>
                                </td>
                            </tr>
                        </table>
                    </form>

                    <style>
                        tr.oct8ne-doofinder-indent th,
                        tr.oct8ne-doofinder-indent td {
                            padding-left: 40px !important;
                            background-color: #f9f9f9;
                        }
                    </style>

                    <script type="text/javascript">
                        document.addEventListener('DOMContentLoaded', function () {
                            const engineSelect = document.querySelector('select[name="oct8ne_search_engine"]');
                            const searchEngineRow = document.getElementById('oct8ne-search-engine-row');
                            const doofinderRows = document.querySelectorAll('.oct8ne-doofinder-row');

                            // Mueve los campos justo debajo del selector
                            if (searchEngineRow && doofinderRows.length > 0) {
                                const parent = searchEngineRow.parentNode;
                                doofinderRows.forEach(row => {
                                    parent.insertBefore(row, searchEngineRow.nextSibling);
                                });
                            }

                            const toggleFields = () => {
                                const isDoofinder = engineSelect.value === 'doofinder';
                                doofinderRows.forEach(row => {
                                    row.style.display = isDoofinder ? 'table-row' : 'none';
                                });
                            };

                            if (engineSelect) {
                                engineSelect.addEventListener('change', toggleFields);
                                toggleFields();
                            }
                        });
                    </script>


                </div>
            <?php
            }
        }

        function oct8ne_handle_logout()
        {
            if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['oct8ne_logout'])) {
                delete_option('oct8ne_token');
                delete_option('oct8ne_license');
                delete_option('oct8ne_email');
                delete_option('oct8ne_server');
                delete_option('oct8ne_static');
                wp_safe_redirect(admin_url('admin.php?page=oct8ne-settings'));
                exit;
            }
        }

        function oct8ne_handle_login()
        {
            if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['oct8ne_login'])) {
                $email = sanitize_email($_POST['oct8ne_email']);
                $password = sanitize_text_field($_POST['oct8ne_password']);

                $response = wp_remote_post('https://backoffice.oct8ne.com/platformConnection/linkup', array(
                    'method'    => 'POST',
                    'body'      => json_encode(array(
                        'email' => $email,
                        'pass' => $password,
                        'platform' => 'wordpress_v1',
                        'urlDomain' => site_url(),
                        'statusPlatform' => true
                    )),
                    'headers'   => array(
                        'Content-Type' => 'application/json'
                    ),
                    'timeout'   => 60, 
                ));

                if (is_wp_error($response)) {
                    add_settings_error('oct8ne_login', 'invalid_credentials', 'Invalid email or password', 'error');
                    return;
                }

                $body = wp_remote_retrieve_body($response);
                $response = json_decode($body, true);
                $apiToken = $response['ApiToken'];

                $licenseId = $response['LicenseId'];

                $server = $response['Server'];

                $UrlStatic = $response['UrlStatic'];
                if (isset($apiToken) && isset($licenseId) && !empty($apiToken) && !empty($licenseId)) {
                    update_option('oct8ne_token', $apiToken);
                    update_option('oct8ne_license', $licenseId);

                    if (isset($server) && !empty($server)) {

                        update_option('oct8ne_server', $server);
                    } else {
                        update_option('oct8ne_server', 'backoffice.oct8ne.com/');
                    }

                    if (isset($UrlStatic) && !empty($UrlStatic)) {

                        update_option('oct8ne_static', $UrlStatic);
                    } else {
                        update_option('oct8ne_static', 'static.oct8ne.com/');
                    }

                    update_option('oct8ne_email', $email);
                    update_option('oct8ne_email_linked', $email);
                    wp_safe_redirect(admin_url('admin.php?page=oct8ne-settings'));
                    exit;
                }

                add_settings_error('oct8ne_login', 'invalid_credentials', 'Invalid email or password', 'error');
            }
        }

        function oct8ne_register_settings()
        {
            register_setting('oct8ne-settings-group', 'oct8ne_js_position');
            register_setting('oct8ne-settings-group', 'oct8ne_search_engine');
            register_setting('oct8ne-settings-group', 'oct8ne_wishlist_engine');
            register_setting('oct8ne-settings-group', 'oct8ne_translation_engine');
            register_setting('oct8ne-settings-group', 'oct8ne_script_extra');
            register_setting('oct8ne-settings-group', 'oct8ne_script_events');
            register_setting('oct8ne-settings-group', 'oct8ne_script_timer');
            register_setting('oct8ne-settings-group', 'oct8ne_email');

            add_settings_section('oct8ne_main_section', 'Oct8ne Settings', null, 'oct8ne');

            add_settings_field('oct8ne_email', 'Email', array($this, 'oct8ne_email_callback'), 'oct8ne', 'oct8ne_main_section');
            add_settings_field('oct8ne_js_position', 'Javascript Position', array($this, 'oct8ne_js_position_callback'), 'oct8ne', 'oct8ne_main_section');
            add_settings_field('oct8ne_search_engine', 'Search Engine', array($this, 'oct8ne_search_engine_callback'), 'oct8ne', 'oct8ne_main_section', ['id' => 'oct8ne-search-engine-row']);

           // Registro de opciones específicas de Doofinder
            $doofinder_options = [
                'oct8ne_doofinder_hash_id',
                'oct8ne_doofinder_api_key',
                'oct8ne_doofinder_search_zone',
                'oct8ne_doofinder_query_name',
                'oct8ne_doofinder_indices',
                'oct8ne_doofinder_productid_property'
            ];

            $languages = array();
            if (function_exists('icl_get_languages')) { 
                $languages = icl_get_languages('skip_missing=0'); 
            } elseif (function_exists('pll_the_languages')) { 
                $languages = pll_the_languages(array('raw' => 1)); 
            }

            foreach ($doofinder_options as $option) {
                register_setting('oct8ne-settings-group', $option, 'sanitize_text_field');
            }

            if (!empty($languages)) {
                foreach ($languages as $code => $lang) {
                    $simple_code = substr($code, 0, 2);
                    foreach ($doofinder_options as $option) {
                        register_setting('oct8ne-settings-group', $option . '_' . $simple_code, 'sanitize_text_field');
                    }
                }
            }

            add_settings_field(
                'oct8ne_doofinder_config_block', 
                'Configuración Doofinder', 
                array($this, 'render_doofinder_complete_block'), // Función nueva
                'oct8ne', 
                'oct8ne_main_section', 
                ['class' => 'oct8ne-doofinder-row'] // Clase para que el JS lo oculte/muestre
            );

            add_settings_field('oct8ne_wishlist_engine', 'WishList Engine', array($this, 'oct8ne_wishlist_engine_callback'), 'oct8ne', 'oct8ne_main_section');
            add_settings_field('oct8ne_translation_engine', 'Translation Engine', array($this, 'oct8ne_translation_engine_callback'), 'oct8ne', 'oct8ne_main_section');
            add_settings_field('oct8ne_script_extra', 'Additional script', array($this, 'oct8ne_script_extra_callback'), 'oct8ne', 'oct8ne_main_section');
            add_settings_field('oct8ne_script_events', 'Delay Oct8ne loading until user interaction', array($this, 'oct8ne_script_events_callback'), 'oct8ne', 'oct8ne_main_section');
            add_settings_field('oct8ne_script_timer', 'Delay Oct8ne loading on page (seconds)', array($this, 'oct8ne_script_timer_callback'), 'oct8ne', 'oct8ne_main_section');

            

        }
        function render_doofinder_complete_block() {
        // Detectar idiomas
        $languages = array();
        if (function_exists('icl_get_languages')) {
            $languages = icl_get_languages('skip_missing=0');
        } elseif (function_exists('pll_the_languages')) {
            $languages = pll_the_languages(array('raw' => 1));
        }

        // Estilos CSS inline
        echo '<style>
            .oct8ne-lang-box { border: 1px solid #ccd0d4; background: #fff; padding: 15px; margin-bottom: 20px; box-shadow: 0 1px 1px rgba(0,0,0,.04); }
            .oct8ne-lang-header { border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 10px; font-size: 14px; font-weight: 600; display: flex; align-items: center; }
            .oct8ne-field-row { margin-bottom: 10px; display: flex; align-items: center; }
            .oct8ne-field-label { width: 180px; font-weight: 500; color: #555; }
            .oct8ne-field-input input, .oct8ne-field-input select { width: 100%; min-width: 300px; }
        </style>';

        
        if (!empty($languages)) {
            
            foreach ($languages as $code => $lang) {
                $simple_code = substr($code, 0, 2);
                
                $flag_html = '';
                if (isset($lang['country_flag_url']) && $lang['country_flag_url']) {
                    $flag_html = '<img src="' . esc_attr($lang['country_flag_url']) . '" width="20" style="margin-right:10px;">';
                } elseif (isset($lang['flag_url'])) {
                    $flag_html = (strpos($lang['flag_url'], '<img') !== false) ? $lang['flag_url'] : '<img src="' . esc_attr($lang['flag_url']) . '" width="20" style="margin-right:10px;">';
                }
                $lang_name = isset($lang['native_name']) ? $lang['native_name'] : strtoupper($simple_code);

                echo '<div class="oct8ne-lang-box" style="border-left: 4px solid #007cba;">';
                echo "<div class='oct8ne-lang-header'>" . wp_kses_post($flag_html) . esc_html($lang_name) . " (" . esc_html(strtoupper($simple_code)) . ")</div>";
                
                $this->render_doofinder_fields_group('_' . $simple_code);
                
                echo '</div>';
            }
            
            } else {
                echo '<div class="oct8ne-lang-box" style="border-left: 4px solid #444;">';
                echo '<div class="oct8ne-lang-header">Configuración Doofinder</div>';
                $this->render_doofinder_fields_group(''); 
                echo '</div>';
            }
        }

        function render_doofinder_fields_group($suffix = '') {
            $fields = [
                'oct8ne_doofinder_hash_id' => ['label' => 'Hash ID', 'ph' => 'Ej: a1b2c3d4...'],
                'oct8ne_doofinder_api_key' => ['label' => 'API Key', 'ph' => 'API Key Secreta'],
                'oct8ne_doofinder_search_zone' => ['label' => 'Zona', 'ph' => 'Ej: eu1'],
                'oct8ne_doofinder_indices' => ['label' => 'Índices', 'ph' => 'product_index, blog_index'],
                'oct8ne_doofinder_productid_property' => ['label' => 'Propiedad ID', 'ph' => 'id, sku'],
                'oct8ne_doofinder_query_name' => ['label' => 'Tipo de Query', 'type' => 'select', 'options' => ['match_and', 'match_or', 'fuzzy', 'none']]
            ];

            foreach ($fields as $base_name => $conf) {
                $option_name = $base_name . $suffix;
                $value = get_option($option_name);
                
                echo '<div class="oct8ne-field-row">';
                echo '<div class="oct8ne-field-label">' . esc_html($conf['label']) . ':</div>';
                echo '<div class="oct8ne-field-input">';
                
                if (isset($conf['type']) && $conf['type'] === 'select') {
                    echo "<select name='" . esc_attr($option_name) . "'>";
                    foreach ($conf['options'] as $opt) {
                        $selected = ($value == $opt) ? "selected='selected'" : "";
                        echo "<option value='".esc_attr($opt)."' ".selected($value, $opt, false).">".esc_html($opt)."</option>";
                    }
                    echo "</select>";
                } else {
                    echo "<input type='text' name='" . esc_attr($option_name) . "' value='" . esc_attr($value) . "' placeholder='" . esc_attr($conf['ph']) . "' />";
                }
                
                echo '</div></div>';
            }
        }
        function render_multilang_field($base_name, $placeholder = '', $is_select = false, $select_options = []) {
            $languages = array();
            if (function_exists('icl_get_languages')) {
                $languages = icl_get_languages('skip_missing=0');
            } elseif (function_exists('pll_the_languages')) {
                $languages = pll_the_languages(array('raw' => 1));
            }

            echo '<div style="background: #fdfdfd; padding: 10px; border: 1px solid #ddd; margin-top:5px;">';
            
            // Si hay idiomas, mostramos uno por cada idioma
            if (!empty($languages)) {
                foreach ($languages as $code => $lang) {
                    $simple_code = substr($code, 0, 2);
                    $option_name = $base_name . '_' . $simple_code;
                    $value = get_option($option_name);
                    
                    // Icono bandera
                    $flag_html = '';
                    if (isset($lang['country_flag_url']) && $lang['country_flag_url']) $flag_html = '<img src="' . $lang['country_flag_url'] . '" width="16" style="vertical-align:middle; margin-right:5px;">';
                    elseif (isset($lang['flag_url'])) $flag_html = (strpos($lang['flag_url'], '<img') !== false) ? $lang['flag_url'] : '<img src="' . $lang['flag_url'] . '" width="16" style="vertical-align:middle; margin-right:5px;">';

                    echo "<div style='margin-bottom: 8px; display:flex; align-items:center;'>";
                    echo "<div style='width:90px; font-size:11px;'>".esc_html($flag_html)." <strong>" . esc_html(strtoupper($simple_code)) . "</strong></div>";
                    
                    if ($is_select) {
                        echo "<select name='" . esc_attr($option_name) . "' style='width: 300px;'>";
                        foreach ($select_options as $opt_val => $opt_label) { // Key => Label
                            // Para selects simples donde value y label son iguales
                            if(is_numeric($opt_val)) $opt_val = $opt_label; 
                            
                            $selected = ($value == $opt_val) ? "selected='selected'" : "";
                            echo "<option value='".esc_attr($opt_val)."' ".selected($value, $opt_val, false).">".esc_html($opt_label)."</option>";
                        }
                        echo "</select>";
                    } else {
                        echo "<input type='text' name='" . esc_attr($option_name) . "' value='" . esc_attr($value) . "' class='regular-text' placeholder='".esc_attr($placeholder)."' style='width: 300px;' />";
                    }
                    echo "</div>";
                }
                // Input oculto base para compatibilidad
                echo "<input type='hidden' name='".esc_attr($base_name)."' value='" . esc_attr(get_option($base_name)) . "' />";
            } else {
                // Fallback sin idiomas
                $val = get_option($base_name);
                if($is_select){
                    echo "<select name='".esc_attr($base_name)."'>";
                    foreach ($select_options as $opt) {
                        $selected = ($val == $opt) ? "selected='selected'" : "";
                        echo "<option value='".esc_attr($opt)."' ".selected($val, $opt, false).">".esc_html($opt)."</option>";
                    }
                    echo "</select>";
                } else {
                    echo "<input type='text' name='".esc_attr($base_name)."' value='" . esc_attr($val) . "' class='regular-text' />";
                }
            }
            echo '</div>';
        }
        function oct8ne_doofinder_hash_id_callback() {
            $this->render_multilang_field('oct8ne_doofinder_hash_id', 'Ej: a1b2c3d4...');
        }

        function oct8ne_doofinder_api_key_callback() {
            $this->render_multilang_field('oct8ne_doofinder_api_key', 'API Key Secreta');
        }

        function oct8ne_doofinder_search_zone_callback() {
            $this->render_multilang_field('oct8ne_doofinder_search_zone', 'Ej: eu1', false); // Puedes cambiar a true si quieres un select
        }

        function oct8ne_doofinder_query_name_callback() {
            $options = ['match_and', 'match_or', 'fuzzy', 'none'];
            $this->render_multilang_field('oct8ne_doofinder_query_name', '', true, $options);
        }

        function oct8ne_doofinder_indices_callback() {
            $this->render_multilang_field('oct8ne_doofinder_indices', 'product_index, blog_index');
        }

        function oct8ne_doofinder_productid_property_callback() {
            $this->render_multilang_field('oct8ne_doofinder_productid_property', 'id, sku');
        }
        
        
        

        function oct8ne_email_callback()
        {
            $value = get_option('oct8ne_email_linked');
            echo "<input style='width: 200px' type='text' disabled name='oct8ne_email' value='".esc_attr($value)."' />";
        }

        function oct8ne_js_position_callback()
        {
            $options = Oct8neJsInfo::getPositions();
            $value = get_option('oct8ne_js_position');
            echo "<select style='width: 200px'  name='oct8ne_js_position'>";
            foreach ($options as $key => $label) {
                $selected = ($label) ? 'selected="selected"' : '';
                echo "<option value='". esc_attr($key) ."' ". selected($value, $key, false) .">".esc_html($key)."</option>";
            }
            echo "</select>";
        }

        function oct8ne_search_engine_callback()
        {
            $options = Oct8neSearchFactory::getEngines();
            $value = get_option('oct8ne_search_engine');
            echo "<select style='width: 200px'  name='oct8ne_search_engine'>";
            foreach ($options as $key => $label) {
                $selected = ($key == $value) ? 'selected="selected"' : '';
                echo "<option value='". esc_attr($key) ."' ". selected($value, $key, false) .">".esc_html($key)."</option>";
            }
            echo "</select>";
        }

        function oct8ne_wishlist_engine_callback()
        {
            $options = WishListFactory::getEngines();
            $value = get_option('oct8ne_wishlist_engine');
            echo "<select style='width: 200px'  name='oct8ne_wishlist_engine'>";
            foreach ($options as $key => $label) {
                $selected = ($key == $value) ? 'selected="selected"' : '';
                echo "<option value='". esc_attr($key) ."' ". selected($value, $key, false) .">".esc_html($key)."</option>";
            }
            echo "</select>";
        }

        function oct8ne_translation_engine_callback()
        {
            $options = Oct8neTranslationFactory::getEngines();
            $value = get_option('oct8ne_translation_engine');
            echo "<select style='width: 200px'  name='oct8ne_translation_engine'>";
            foreach ($options as $key => $label) {
                $selected = ($key == $value) ? 'selected="selected"' : '';
                echo "<option value='". esc_attr($key) ."' ". selected($value, $key, false) .">".esc_html($key)."</option>";
            }
            echo "</select>";
        }

        function oct8ne_script_extra_callback()
        {
            $value = get_option('oct8ne_script_extra');
            echo "<textarea style='width: 200px'  name='oct8ne_script_extra' style='width: 400px;height: 100px;'>".esc_textarea($value)."</textarea>";
        }

        function oct8ne_script_events_callback()
        {
            $value = get_option('oct8ne_script_events');
            $options = [
                'Disabled' => 'Disabled',
                'All' => 'Any user event (Click, Scroll, Mousemove)',
                'scroll' => 'Scroll',
                'click' => 'Click',
                'mousemove' => 'Mousemove',
                'Script' => 'Script call',
            ];
            echo "<select style='width: 200px'  name='oct8ne_script_events'>";
            foreach ($options as $key => $label) {
                $selected = ($key == $value) ? 'selected="selected"' : '';
                echo "<option value='". esc_attr($key) ."' ". selected($value, $key, false) .">".esc_html($key)."</option>";
            }
            echo "</select>";
            echo "<br/><span style='font-size: 11px'>**If you choose \"Script call\" you must call the function <i>insertOct8ne();</i> whenever you want load Oct8ne's code on the page.**</span>";
        }

        function oct8ne_script_timer_callback()
        {
            $value = get_option('oct8ne_script_timer');
            $options = range(1, 10);
            array_unshift($options, 'Disabled');
            echo "<select style='width: 200px'  name='oct8ne_script_timer'>";
            foreach ($options as $option) {
                $selected = ($option == $value) ? 'selected="selected"' : '';
                echo "<option value='". esc_attr($option) ."' ". selected($value, $option, false) .">".esc_html($option)."</option>";
            }
            echo "</select>";
        }

        /**
         * Notificaciones
         * @var array
         */
        public $notices = array();

        /**
         * Private clone method to prevent cloning of the instance of the
         * *Singleton* instance.
         *
         * @return void
         */
        private function __clone()
        {
        }

        /**
         * Private unserialize method to prevent unserializing of the *Singleton*
         * instance.
         *
         * @return void
         */
        public function __wakeup()
        {
        }

        /**
         * On plugin activate
         */
        public static function install()
        {
            Oct8neHtaccessHelper::setHtaccessRules();

            //Oct8neDb::createTables();

            if (is_plugin_active("yith-woocommerce-wishlist/init.php")) {

                update_option('oct8ne_wishlist_engine', "yith-woocommerce-wishlist");
            }

            //var_dump(ob_get_contents());

        }

        /**
         * On plugin deactivate
         */
        public static function unistall()
        {
            Oct8neHtaccessHelper::removeHtaccessRules();
        }

        /**
         * On plugin delete
         */
        public static function fullUninstall()
        {
            //Oct8neDb::dropTables();

            delete_option('oct8ne_token');
            delete_option('oct8ne_license');
            delete_option('oct8ne_email');
            delete_option('oct8ne_search_engine');
            delete_option('oct8ne_wishlist_engine');
        }

        /**
         * Init the plugin after plugins_loaded so environment variables are set.
         */
        public function init()
        {
            // Don't hook anything else in the plugin if we're in an incompatible environment
            if (self::get_environment_warning()) {
                return;
            }

            add_submenu_page(
                'woocommerce',
                'Ajustes plugin Oct8ne',
                'Oct8ne',
                'administrator',
                'oct8ne-settings',
                array($this, 'oct8ne_settings_page')
            );
        }


        /**
         * Comprueba si se cumplen los requisitos para instalar oct8ne
         */
        public function check_environment()
        {

            $environment_warning = self::get_environment_warning();

            if ($environment_warning) {
                $this->add_admin_notice('bad_environment', 'error', $environment_warning);
            }

            //desactivar si no se cumplen
            if (count($this->notices) > 0) {

                deactivate_plugins(plugin_basename(__FILE__));
                $this->notices = array();
            }
        }


        /**
         * Comprobar requisitos
         * @return bool|string|void
         */
        static function get_environment_warning()
        {
            if (!defined('WC_VERSION')) {
                return __('Oct8ne requires WooCommerce to be activated to work.', 'oct8ne');
            }

            return false;
        }

        /**
         * Errores a mostrar
         * @param $slug
         * @param $class
         * @param $message
         */
        public function add_admin_notice($slug, $class, $message)
        {
            $this->notices[$slug] = array(
                'class' => $class,
                'message' => $message,
            );
        }

        /**
         * Mostrando errores
         */
        public function admin_notices()
        {

            foreach ((array)$this->notices as $notice_key => $notice) {
                echo "<div class='" . esc_attr($notice['class']) . "'><p>";
                echo wp_kses($notice['message'], array('a' => array('href' => array())));
                echo '</p></div>';
            }


            if (count($this->notices) > 0) {

                add_filter('gettext', function ($translated_text, $untranslated_text, $domain) {

                    $old = array("Plugin <strong>activated</strong>.");
                    $new = "Oct8ne not installed";

                    if (in_array($untranslated_text, $old, true)) $translated_text = $new;
                    return $translated_text;
                }, 0, 3);
            }
        }

        /**
         * Añade el javascript necesario para que funcione Oct8ne
         */
        public function addOct8neJs()
        {

            if (Oct8neLoginHelper::isLogged()) {
            ?>
                <script type="text/javascript">
                    var oct8ne = document.createElement("script");
                    oct8ne.type = "text/javascript";
                    oct8ne.src = (document.location.protocol == "https:" ? "https://" : "http://") + "<?php echo esc_js(Oct8neJsInfo::getUrlStatic()); ?>" + 'api/v2/oct8ne.js';
                    oct8ne.server = "<?php echo esc_js(Oct8neJsInfo::getServer()); ?>";
                    oct8ne.async = true;
                    oct8ne.license = "<?php echo esc_js(Oct8neJsInfo::getLicense()); ?>";
                    oct8ne.baseUrl = "<?php echo esc_js(Oct8neJsInfo::getBaseUrl()); ?>";
                    oct8ne.checkoutUrl = "<?php echo esc_js(Oct8neJsInfo::getCheckoutUrl()); ?>";
                    oct8ne.loginUrl = "<?php echo esc_js(Oct8neJsInfo::getLoginUrl()); ?>";
                    oct8ne.checkoutSuccessUrl = "<?php echo esc_js(Oct8neJsInfo::getSuccessUrl()); ?>";
                    oct8ne.locale = "<?php echo esc_js(Oct8neJsInfo::getLocale()); ?>";
                    oct8ne.currencyCode = "<?php echo esc_js(Oct8neJsInfo::getCurrency()); ?>";
                    oct8ne.platform = "wordpress_v1";
                    oct8ne.apiVersion = "2.5";
                    oct8ne.onProductAddedToCart = function(productId) {
                        //location.reload();
                    };

                    <?php if (esc_js(Oct8neJsInfo::getExtraScript())) { ?>

                        <?php echo esc_js(Oct8neJsInfo::getExtraScript()); ?>
                    <?php } ?>

                    <?php if (esc_js(Oct8neJsInfo::isProductPage())) { ?>
                        oct8ne.currentProduct = {
                            id: "<?php echo esc_js(Oct8neJsInfo::getProductId()); ?>",
                            thumbnail: "<?php echo esc_js(Oct8neJsInfo::getProductThumbnail()); ?>"
                        };

                    <?php } ?>

                    <?php
                    $oct8neEvents = esc_js(Oct8neJsInfo::getScriptEvents());
                    $oct8neTimer = esc_js(Oct8neJsInfo::getScriptTimer());
                    ?>

                    <?php if ($oct8neEvents == "Disabled" && $oct8neTimer == "Disabled") { ?>
                        insertOct8ne();
                    <?php } else { ?>

                        if (document.cookie.indexOf("oct8ne-room") == -1) {
                            <?php if ($oct8neTimer != "Disabled") { ?>

                                setTimeout(insertOct8ne, <?php echo esc_js($oct8neTimer) ?> * 1000);
                            <?php } ?>
                            <?php if ($oct8neEvents != "Disabled" && $oct8neEvents != "SCRIPT") { ?>
                                <?php if ($oct8neEvents == "All") { ?>

                                    window.addEventListener('mousemove', insertOct8ne);
                                    window.addEventListener('scroll', insertOct8ne);
                                    window.addEventListener('click', insertOct8ne);
                                    window.addEventListener('keydown', insertOct8ne);
                                    window.addEventListener('touchstart', insertOct8ne);
                                <?php } else { ?>

                                    window.addEventListener('<?php echo esc_js($oct8neEvents); ?>', insertOct8ne);
                                <?php } ?>
                            <?php } ?>
                        } else {
                            insertOct8ne();
                        }
                    <?php } ?>

                    function insertOct8ne() {
                        if (!window.oct8neScriptInserted) {
                            var s = document.getElementsByTagName("script")[0];
                            s.parentNode.insertBefore(oct8ne, s);
                            window.oct8neScriptInserted = true;

                            <?php if ($oct8neEvents != "Disabled") { ?>
                                <?php if ($oct8neEvents == "All") { ?>

                                    window.removeEventListener('mousemove', insertOct8ne);
                                    window.removeEventListener('scroll', insertOct8ne);
                                    window.removeEventListener('click', insertOct8ne);
                                    window.removeEventListener('keydown', insertOct8ne);
                                    window.removeEventListener('touchstart', insertOct8ne);
                                <?php } else { ?>
                                    <?php if ($oct8neEvents != "Script") { ?>
                                        window.removeEventListener('<?php echo esc_js($oct8neEvents); ?>', insertOct8ne);
                                    <?php } ?>
                                <?php } ?>
                            <?php } ?>

                        }
                    }
                </script>


                <?php
                try {
                    if (is_order_received_page() || is_wc_endpoint_url( 'order-received' )) {
                        $order_id = absint(get_query_var('order-received'));
                        if ($order_id) {
                            $order = wc_get_order($order_id);

                            if ($order) {
                                $total_pedido = $order->get_total();
                                $moneda_pedido = $order->get_currency();
                                $locale_pedido = get_locale();
                                $reference_pedido = $order->get_order_number();
                                $customer_id = $order->get_user_id();

                                $base_url = 'https://' . Oct8neJsInfo::getUrlStatic() . 'api/source/js/ext/sale-notification.js';
                                $params = array(
                                    'license'      => Oct8neJsInfo::getLicense(),
                                    'CurrencyCode' => $moneda_pedido,
                                    'locale'       => $locale_pedido,
                                    'value'        => $total_pedido,
                                    'reference'    => $reference_pedido,
                                    'CustomerId'   => $customer_id,
                                );
                                $final_url = add_query_arg( $params, $base_url );
                                wp_enqueue_script( 'oct8ne-sale-notification', $final_url, array(), '1.2.5', true );
                            }
                        }
                    }
                } catch (Exception $e) {
                    echo "<!-- Error: Oct8ne pixel not available -->";
                }
                ?>


<?php
            }
        }
    }

    function oct8ne_endopint_register()
    {
        register_rest_route('oct8ne/v1', '/api/', array(
            'methods' => 'GET',
            'callback' => 'oct8ne_callback_function',
            'permission_callback' => '__return_true'  // Asegúrate de gestionar los permisos adecuadamente
        ));
    }

    add_action('rest_api_init', 'oct8ne_endopint_register');

    function oct8ne_callback_function(WP_REST_Request $request)
    {
        include_once plugin_dir_path(__FILE__) . 'actions/oct8neconnector/index.php';

        $result = postProcess();
        return new WP_REST_Response($result, 200);
    }

endif;

$GLOBALS['wc_soct8ne'] = WC_Oct8ne_Plugin::get_instance();

if ( ! class_exists( 'Oct8ne_Auto_Update' ) ) {

    class Oct8ne_Auto_Update {

        public $current_version;
        public $update_path;
        public $plugin_slug;
        public $slug;
        private $cache_key;

        public function __construct( $current_version, $update_path, $plugin_slug ) {
            $this->current_version = $current_version;
            $this->update_path     = $update_path;
            $this->plugin_slug     = $plugin_slug;
            list( $t1, $t2 )       = explode( '/', $plugin_slug );
            $this->slug            = str_replace( '.php', '', $t2 );
            $this->cache_key       = 'oct8ne_upd_' . md5( $this->slug );

            add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'check_update' ) );
            add_filter( 'plugins_api', array( $this, 'check_info' ), 10, 3 );
        }

        public function check_update( $transient ) {
            if ( empty( $transient->checked ) ) {
                return $transient;
            }
            global $pagenow;
            if ( $pagenow === 'update-core.php' && isset( $_GET['force-check'] ) ) {
                delete_transient( $this->cache_key );
            }
            $remote_version = $this->get_remote_version();

            if ( $remote_version && version_compare( $this->current_version, $remote_version->new_version, '<' ) ) {
                $res = new stdClass();
                $res->slug = $this->slug;
                $res->plugin = $this->plugin_slug;
                $res->new_version = $remote_version->new_version;
                $res->package = $remote_version->package;
                
                if(isset($remote_version->icons)) $res->icons = (array)$remote_version->icons;
                if(isset($remote_version->sections)) $res->sections = (array)$remote_version->sections;
                if(isset($remote_version->url)) $res->url = $remote_version->url;

                $transient->response[ $this->plugin_slug ] = $res;
            }

            return $transient;
        }

        public function check_info( $false, $action, $arg ) {
            if ( $action !== 'plugin_information' ) {
                return $false;
            }

            if ( $this->slug !== $arg->slug ) {
                return $false;
            }

            $remote_version = $this->get_remote_version();

            if ( ! $remote_version ) {
                return $false;
            }

            $res = new stdClass();
            $res->name = 'Oct8ne Plugin';
            $res->slug = $this->slug;
            $res->version = $remote_version->new_version;
            $res->download_link = $remote_version->package;
            $res->sections = (array) $remote_version->sections;
            
            if(isset($remote_version->icons)) {
                $res->icons = (array)$remote_version->icons;
            }
            return $res;
        }

        public function get_remote_version() {
            $remote_version = get_transient( $this->cache_key );
            if ( false !== $remote_version ) {
                return $remote_version;
            }
            $args= array(
                'timeout' => 5,
                'headers' => array( 'Accept' => 'application/json' )
            );
            $request = wp_remote_get( $this->update_path, $args );
            if ( is_wp_error( $request ) || 200 !== wp_remote_retrieve_response_code( $request ) ) {
                return false;
            }
            $body=wp_remote_retrieve_body( $request );
            $data=json_decode($body);
            if ( json_last_error() !== JSON_ERROR_NONE ) {
                return false; 
            }
            if(!is_object($data)){
                 return false;
            }
            if ( empty( $data->new_version ) || empty( $data->package ) || empty( $data->slug ) ) {
                return false;
            }
            set_transient( $this->cache_key, $data, 86400 );
            return $data;
        }
    }

    add_action( 'plugins_loaded', function() {
        if ( ! is_admin() ) {
            return;
        }
        global $pagenow;
        $paginas_permitidas = array( 'plugins.php', 'update-core.php', 'plugin-install.php' );
        if ( ! in_array( $pagenow, $paginas_permitidas ) ) {
            return;
        }
        $api_url = 'https://oct8ne.com/plugins/wordpress/update.json';
        $plugin_data = get_file_data( __FILE__, array( 'Version' => 'Version' ), false );
        $current_version = $plugin_data['Version']; 
        new Oct8ne_Auto_Update( $current_version, $api_url, plugin_basename( __FILE__ ) );
    });
}
?>