<?php

defined('ABSPATH') || exit;

const DEJAVOSE_VERSION = '2.1.0';

if ( class_exists('WC_Product') and dej_options('dej_show_ajax_search' , '1') ) {
    class DejavoSearch
    {
        protected static $instance = null;
        protected static $settings = [];
        protected static $rules = [];

        public static function instance()
        {
            if (is_null(self::$instance)) {
                self::$instance = new self();
            }

            return self::$instance;
        }

        function __construct()
        {
            self::$settings = (array)get_option('DejavoSE_settings', []);

            // frontend
            add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
            add_action('wp_footer', [$this, 'footer']);

            // backend
            add_action('admin_enqueue_scripts', [$this, 'admin_enqueue_scripts']);
            add_action('admin_init', [$this, 'register_settings']);
            add_action('admin_menu', [$this, 'admin_menu']);

            if (self::get_setting('search_sku', 'no') === 'yes') {
                add_filter('pre_get_posts', [$this, 'search_sku'], 99);
            }

            // ajax
            add_action('wp_ajax_DejavoSE_search', [$this, 'ajax_search']);
            add_action('wp_ajax_nopriv_DejavoSE_search', [$this, 'ajax_search']);


            // actions
            if (self::get_setting('compare', 'yes') === 'yes') {
                add_action('DejavoSE_product_actions', [$this, 'item_compare'], 1);
            }

            if (self::get_setting('wishlist', 'yes') === 'yes') {
                add_action('DejavoSE_product_actions', [$this, 'item_wishlist'], 2);
            }

            if (self::get_setting('add_to_cart', 'yes') === 'yes') {
                add_action('DejavoSE_product_actions', [$this, 'item_add_to_cart'], 3);
            }

        }


        function enqueue_scripts()
        {
            // disable on some pages
            if (apply_filters('DejavoSE_disable', false)) {
                return;
            }


            // animated placeholder
            if (self::get_setting('animated_placeholder', 'no') === 'yes') {
                wp_enqueue_script('placeholderTypewriter', DEJ_TUI . '/assets/libs/placeholderTypewriter/placeholderTypewriter.js', ['jquery'], DEJAVOSE_VERSION, true);
            }

            // css
            wp_enqueue_style('DejavoSE-frontend', DEJ_TUI . '/assets/css/ajax-search.css', [], DEJAVOSE_VERSION);

            if ((self::get_setting('animated_placeholder', 'no') === 'yes') && !empty(self::get_setting('placeholder_text'))) {
                $animated_placeholder = [
                    'delay' => 50,
                    'pause' => 3000,
                ];

                $placeholder_text = self::get_setting('placeholder_text');
                $placeholder_arr = explode("\n", $placeholder_text);
                $placeholder_arr = array_map('esc_attr', $placeholder_arr);
                $animated_placeholder['text'] = array_map('trim', $placeholder_arr);
            } else {
                $animated_placeholder = [];
            }

            // js
            wp_enqueue_script('DejavoSE-frontend', DEJ_TUI . '/assets/js/ajax-search.js', ['jquery'], DEJAVOSE_VERSION, true);
            wp_localize_script('DejavoSE-frontend', 'DejavoSE_vars', [
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('DejavoSE-security'),
                    'auto_show' => 'yes_inline',
                    'auto_exclude' => apply_filters('DejavoSE_auto_show_exclude', ''),
                    'manual_show' => 'header-search-icon',
                    'animated_placeholder' => apply_filters('DejavoSE_animated_placeholder', json_encode($animated_placeholder)),
                ]
            );
        }

        function admin_enqueue_scripts($hook)
        {
            if (strpos($hook, 'DejavoSE')) {
                wp_enqueue_editor();
                wp_localize_script('DejavoSE-backend', 'DejavoSE_vars', [
                    'DejavoSE_nonce' => wp_create_nonce('DejavoSE_nonce')
                ]);
            }
        }


        function register_settings()
        {
            // settings
            register_setting('DejavoSE_settings', 'DejavoSE_settings');
        }

        function admin_menu()
        {
            add_submenu_page('future', esc_html__('AJAX Search', 'dejavo'), esc_html__('AJAX Search', 'dejavo'), 'manage_options', 'future-DejavoSE', array(
                $this,
                'admin_menu_content'
            ));
        }

        function admin_menu_content()
        {
            add_thickbox();
            $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'settings';
            ?>
            <div class="dejavo_settings_page wrap">
                <h1 class="dejavo_settings_page_title"><?php echo esc_html__('AJAX Search', 'dejavo') . ' ' . DEJAVOSE_VERSION; ?></h1>

                <?php if (isset($_GET['settings-updated']) && $_GET['settings-updated']) { ?>
                    <div class="notice notice-success is-dismissible">
                        <p><?php esc_html_e('Settings updated.', 'dejavo'); ?></p>
                    </div>
                <?php } ?>
                <div class="dejavo_settings_page_nav">
                    <h2 class="nav-tab-wrapper">
                        <a href="<?php echo admin_url('admin.php?page=future-DejavoSE&tab=settings'); ?>"
                           class="<?php echo esc_attr($active_tab === 'settings' ? 'nav-tab nav-tab-active' : 'nav-tab'); ?>">
                            <?php esc_html_e('Settings', 'dejavo'); ?>
                        </a>
                    </h2>
                </div>
                <div class="dejavo_settings_page_content">
                    <?php if ($active_tab === 'settings') {
                        $link = self::get_setting('link', 'yes');
                        $compare = self::get_setting('compare', 'yes');
                        $wishlist = self::get_setting('wishlist', 'yes');
                        $add_to_cart = self::get_setting('add_to_cart', 'yes');
                        $exclude_unpurchasable = self::get_setting('exclude_unpurchasable', 'yes');
                        $animated_placeholder = self::get_setting('animated_placeholder', 'no');
                        $search_category = self::get_setting('search_category', 'yes');
                        $search_sku = self::get_setting('search_sku', 'no');
                        ?>
                        <form method="post" action="options.php">
                            <table class="form-table">

                                <tr>
                                    <th><?php esc_html_e('Link to individual product', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[link]">
                                            <option value="yes" <?php selected($link, 'yes'); ?>><?php esc_html_e('Yes, open in the same tab', 'dejavo'); ?></option>
                                            <option value="yes_blank" <?php selected($link, 'yes_blank'); ?>><?php esc_html_e('Yes, open in the new tab', 'dejavo'); ?></option>
                                            <option value="yes_popup" <?php selected($link, 'yes_popup'); ?>><?php esc_html_e('Yes, open quick view popup', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($link, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e('Compare button', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[compare]">
                                            <option value="yes" <?php selected($compare, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($compare, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>

                                    </td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e('Wishlist button', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[wishlist]">
                                            <option value="yes" <?php selected($wishlist, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($wishlist, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>

                                    </td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e('Add to cart button', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[add_to_cart]">
                                            <option value="yes" <?php selected($add_to_cart, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($add_to_cart, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e('Exclude unpurchasable', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[exclude_unpurchasable]">
                                            <option value="yes" <?php selected($exclude_unpurchasable, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($exclude_unpurchasable, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>
                                        <span class="description"><?php esc_html_e('Exclude unpurchasable products from the search result.', 'dejavo'); ?></span>
                                    </td>
                                </tr>

                                <tr>
                                    <th scope="row"><?php esc_html_e('Popular keywords', 'dejavo'); ?></th>
                                    <td>
                                        <textarea name="DejavoSE_settings[popular_keywords]" rows="5" cols="50"
                                                  class="large-text"><?php echo self::get_setting('popular_keywords'); ?></textarea>
                                        <span class="description"><?php esc_html_e('با کاما جدا کنید', 'avina'); ?></span>

                                    </td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e('Animated placeholder', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[animated_placeholder]"
                                                class="DejavoSE_animated_placeholder">
                                            <option value="yes" <?php selected($animated_placeholder, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($animated_placeholder, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>
                                        <span class="description"><?php esc_html_e('Enable animated placeholder text.', 'dejavo'); ?></span>
                                    </td>
                                </tr>
                                <tr class="DejavoSE-show-if-animated-placeholder">
                                    <th scope="row"><?php esc_html_e('Animated placeholder text', 'dejavo'); ?></th>
                                    <td>
                                        <textarea name="DejavoSE_settings[placeholder_text]" rows="10" cols="50"
                                                  class="large-text"><?php echo self::get_setting('placeholder_text'); ?></textarea>
                                        <span class="description"><?php esc_html_e('Add animated placeholder text, each text in one line.', 'dejavo'); ?></span>
                                    </td>
                                </tr>

                                <tr>
                                    <th><?php esc_html_e('Search by category', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[search_category]">
                                            <option value="yes" <?php selected($search_category, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($search_category, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e('Search limit', 'dejavo'); ?></th>
                                    <td>
                                        <input type="number" min="1" max="500" name="DejavoSE_settings[search_limit]"
                                               value="<?php echo esc_attr(self::get_setting('search_limit', 10)); ?>"/>
                                    </td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e('Search by SKU', 'dejavo'); ?></th>
                                    <td>
                                        <select name="DejavoSE_settings[search_sku]">
                                            <option value="yes" <?php selected($search_sku, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                            <option value="no" <?php selected($search_sku, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                        </select>
                                    </td>
                                </tr>

                                <tr class="submit">
                                    <th colspan="2">
                                        <?php settings_fields('DejavoSE_settings'); ?><?php submit_button(); ?>
                                    </th>
                                </tr>
                            </table>
                        </form>
                    <?php }  ?>
                </div>
            </div>
            <?php
        }

        function ajax_search()
        {
            if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'DejavoSE-security')) {
                die('<div class="DejavoSE-error">خطای دسترسی</div>');
            }

            $keyword = sanitize_text_field($_POST['keyword']);
            $category = absint(sanitize_text_field($_POST['category']));

            $products = [];

            do_action('DejavoSE_before_search', $keyword, $category);

            ob_start();

            do_action('DejavoSE_before_search_result', $keyword, $category);

            if (!$products) {
                $args = [
                    'is_DejavoSE' => true,
                    'post_type' => 'product',
                    'post_status' => 'publish',
                    'fields' => 'ids',
                    'posts_per_page' => self::get_setting('search_limit', 10)
                ];

                if ($category) {
                    $args['tax_query'] = [
                        [
                            'taxonomy' => 'product_cat',
                            'terms' => $category,
                            'field' => 'ID',
                            'include_children' => true,
                            'operator' => 'IN'
                        ]
                    ];
                }

                $args['s'] = $keyword;

                $query = new WP_Query(apply_filters('DejavoSE_search_query_args', $args));
                $products = $query->posts;
            }

            if ($products) {
                self::show_products($products, $keyword, $category);
            } else {
                do_action('DejavoSE_before_not_found', $keyword, $category);

                if (!empty($category) && ($cat = get_term_by('id', absint($category), 'product_cat'))) {
                    echo '<div class="DejavoSE-not-found"><span>' . sprintf(esc_html__('No results found for "%s" in "%s".', 'dejavo'), $keyword, esc_html($cat->name)) . '</span></div>';
                } else {
                    echo '<div class="DejavoSE-not-found"><span>' . sprintf(esc_html__('No results found for "%s".', 'dejavo'), $keyword) . '</span></div>';
                }

                do_action('DejavoSE_after_not_found', $keyword, $category);
            }

            end:

            do_action('DejavoSE_after_search_result', $keyword, $category);

            $return = ob_get_clean();


            do_action('DejavoSE_after_search', $keyword, $category);

            echo apply_filters('DejavoSE_search_result', $return, $keyword, $category);

            wp_die();
        }

        function show_products($products, $keyword = '', $category = 0)
        {
            $link = self::get_setting('link', 'yes');

            echo '<div class="DejavoSE-products">';

            do_action('DejavoSE_before_products', $keyword, $category);

            foreach ($products as $_product_id) {
                $_product = wc_get_product($_product_id);

                if (!$_product) {
                    continue;
                }

                if ((self::get_setting('exclude_unpurchasable', 'no') === 'yes') && (!$_product->is_in_stock() || !$_product->is_purchasable())) {
                    continue;
                }

                if (apply_filters('DejavoSE_exclude_product', false, $_product)) {
                    continue;
                }

                echo '<div class="DejavoSE-product">';
                echo '<div class="DejavoSE-product-inner">';
                do_action('DejavoSE_before_product_inner', $_product);

                echo '<div class="DejavoSE-product-thumb">';
                do_action('DejavoSE_before_product_thumbnail', $_product);

                if ($link !== 'no') {
                    echo sprintf('<a ' . ($link === 'yes_popup' ? 'class="DejavoQV-btn" data-id="' . $_product_id . '"' : '') . ' href="%s" ' . ($link === 'yes_blank' ? 'target="_blank"' : '') . '>%s</a>', $_product->get_permalink(), $_product->get_image());
                } else {
                    echo $_product->get_image();
                }

                do_action('DejavoSE_after_product_thumbnail', $_product);
                echo '</div><!-- /DejavoSE-product-thumb -->';

                echo '<div class="DejavoSE-product-info">';
                do_action('DejavoSE_before_product_info', $_product);

                echo '<div class="DejavoSE-product-name">';
                do_action('DejavoSE_before_product_name', $_product);

                if ($link !== 'no') {
                    echo sprintf('<a ' . ($link === 'yes_popup' ? 'class="DejavoQV-btn" data-id="' . $_product_id . '"' : '') . ' href="%s" ' . ($link === 'yes_blank' ? 'target="_blank"' : '') . '>%s</a>', $_product->get_permalink(), $_product->get_name());
                } else {
                    echo $_product->get_name();
                }

                do_action('DejavoSE_after_product_name', $_product);
                echo '</div><!-- /DejavoSE-product-name -->';

                echo '<div class="DejavoSE-product-price">' . $_product->get_price_html() . '</div>';

                do_action('DejavoSE_after_product_info', $_product);
                echo '</div><!-- /DejavoSE-product-info -->';

                echo '<div class="DejavoSE-product-actions">';
                do_action('DejavoSE_product_actions', $_product);
                echo '</div><!-- /DejavoSE-product-actions -->';

                do_action('DejavoSE_after_product_inner', $_product);
                echo '</div><!-- /DejavoSE-product-inner -->';
                echo '</div><!-- /DejavoSE-product -->';
            }

            do_action('DejavoSE_after_products', $keyword, $category);

            echo '</div>';
        }


        function search_sku($query)
        {
            if ($query->is_search && isset($query->query['is_DejavoSE'])) {
                global $wpdb;

                $sku = $query->query['s'];
                $ids = $wpdb->get_col($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value = %s;", $sku));

                if (!$ids) {
                    return;
                }

                unset($query->query['s'], $query->query_vars['s']);
                $query->query['post__in'] = [];

                foreach ($ids as $id) {
                    $post = get_post($id);

                    if ($post->post_type === 'product_variation') {
                        $query->query['post__in'][] = $post->post_parent;
                        $query->query_vars['post__in'][] = $post->post_parent;
                    } else {
                        $query->query_vars['post__in'][] = $post->ID;
                    }
                }
            }
        }

        function get_search_area()
        {
            $popular = apply_filters('DejavoSE_popular_keywords', trim(self::get_setting('popular_keywords')));
            $keywords = explode(',', $popular);
            $popular_keywords = [];

            if (!empty($keywords)) {
                foreach ($keywords as $keyword) {
                    if (!empty(trim($keyword))) {
                        $popular_keywords[] = '<a href="#DejavoSE">' . esc_html(trim($keyword)) . '</a>';
                    }
                }
            }

            ?>
            <div id="DejavoSE-area" class="DejavoSE-area">

                <div class="DejavoSE-area-mid DejavoSE-search">

                    <?php if (!empty($popular_keywords)) { ?>
                        <div class="DejavoSE-popular-keywords">
                            <span class="DejavoSE-popular-keywords-label"><?php esc_html_e('Popular keywords:', 'dejavo'); ?></span>
                            <?php echo implode(', ', $popular_keywords); ?>
                        </div>
                    <?php } ?>

                    <div class="DejavoSE-search-result">
                        <?php do_action('DejavoSE_placeholder_result'); ?>
                    </div>
                </div>
            </div>
            <?php
        }

        function footer()
        {
            if (is_admin()) {
                return;
            }

            self::get_search_area();


        }


        function item_compare($product)
        {
            if ($product && class_exists('DejavoCP')) {
                echo do_shortcode('[DejavoCP id="' . $product->get_id() . '"]');
            }
        }

        function item_wishlist($product)
        {
            if ($product && class_exists('DejavoWL')) {
                echo do_shortcode('[DejavoWL id="' . $product->get_id() . '"]');
            }
        }

        function item_add_to_cart($product)
        {
            if ($product) {
                echo '<div class="atc-btn">' . do_shortcode('[add_to_cart style="" show_price="false" id="' . $product->get_id() . '"]') . '</div>';
            }
        }



        public static function get_settings()
        {
            return apply_filters('DejavoSE_get_settings', self::$settings);
        }

        public static function get_setting($name, $default = false)
        {
            if (!empty(self::$settings) && isset(self::$settings[$name])) {
                $setting = self::$settings[$name];
            } else {
                $setting = get_option('DejavoSE_' . $name, $default);
            }

            return apply_filters('DejavoSE_get_setting', $setting, $name, $default);
        }

        public static function generate_key()
        {
            $key = '';
            $key_str = apply_filters('DejavoSE_key_characters', 'abcdefghijklmnopqrstuvwxyz0123456789');
            $key_str_len = strlen($key_str);

            for ($i = 0; $i < apply_filters('DejavoSE_key_length', 4); $i++) {
                $key .= $key_str[random_int(0, $key_str_len - 1)];
            }

            if (is_numeric($key)) {
                $key = self::generate_key();
            }

            return apply_filters('DejavoSE_generate_key', $key);
        }


    }

    return DejavoSearch::instance();


}
        


