<?php defined('ABSPATH') || exit;
//VERSION = '2.1.0';
if (dej_opt('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']);

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

    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'], DEJ_VERSION, true);
        }
        // css
        wp_enqueue_style('DejavoSE-frontend', DEJ_TUI . '/assets/css/ajax-search.css', [], DEJ_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'], DEJ_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', [
                'Dejavononce' => wp_create_nonce('Dejavononce')
            ]);
        }
    }


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

    function admin_menu()
    {
        add_submenu_page('future', __('جست و جو ایجکسی', 'dejavo'), __('جست و جو ایجکسی', 'dejavo'), 'manage_options', 'future-DejavoSE', array(
            $this,
            'admin_menu_content'
        ));
    }

    function admin_menu_content()
    {
        if (is_admin()) {
            add_thickbox();
            ?>
            <div class="dejavo_settings_page wrap">
                <h1 class="dejavo_settings_page_title"><?php echo __('جست و جو ایجکسی', 'dejavo') ?></h1>

                <?php if (isset($_GET['settings-updated']) && $_GET['settings-updated']) { ?>
                    <div class="notice notice-success is-dismissible">
                        <p><?php esc_html_e('تنظیمات ذخیره شد', 'dejavo'); ?></p>
                    </div>
                <?php } ?>

                <div class="dejavo_settings_page_content">
                    <?php
                    $link = self::get_setting('link', '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');
                    ?>
                    <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('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('با کاما جدا کنید', 'dejavo'); ?></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 class="submit">
                                <th colspan="2">
                                    <?php settings_fields('DejavoSE_settings'); ?><?php submit_button(); ?>
                                </th>
                            </tr>
                        </table>
                    </form>
                </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 = [];

        ob_start();

        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($args);
            $products = $query->posts;
        }

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

            if (!empty($category) && ($cat = get_term_by('id', absint($category), 'product_cat'))) {
                echo '<div class="DejavoSE-not-found"><span>' . sprintf(esc_html__('نتیجه ای برای "%s" در "%s" یافت نشذ.', 'dejavo'), $keyword, esc_html($cat->name)) . '</span></div>';
            } else {
                echo '<div class="DejavoSE-not-found"><span>' . sprintf(esc_html__('نتیجه ای برای "%s" یافت نشد.', 'dejavo'), $keyword) . '</span></div>';
            }

        }

        $return = ob_get_clean();

        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">';
        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"><div class="DejavoSE-product-inner"><div class="DejavoSE-product-thumb">';

            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();
            }

            echo '</div><!-- /thumb -->';
            echo '<div class="DejavoSE-product-info"><div class="DejavoSE-product-name">';

            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();
            }
            echo '</div><!-- /name -->';
            echo '<div class="DejavoSE-product-price">' . $_product->get_price_html() . '</div>';
            echo '</div><!-- /info -->';
            echo '<div class="DejSE-actions">';

            if (dej_opt('dej_show_compare', 1)) {
                echo DejavoCP::cp_btn($_product->get_id());
            }
            if (dej_opt('dej_show_wishlist', 1)) {
                echo DejavoWL::wl_btn($_product->get_id());
            }

            echo '<div class="atc-btn">' . do_shortcode('[add_to_cart style="" show_price="false" id="' . $_product->get_id() . '"]') . '</div>';

            echo '</div>';

            echo '</div><!-- /DejavoSE-product-inner -->';
            echo '</div><!-- /DejavoSE-product -->';
        }

        echo '</div>';
    }


    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('کلمات کلیدی محبوب:', 'dejavo'); ?></span>
                        <?php echo implode(', ', $popular_keywords); ?>
                    </div>
                <?php } ?>

                <div class="DejavoSE-search-result">
                </div>
            </div>
        </div>
        <?php
    }

    function footer()
    {
        if (is_admin()) {
            return;
        }
        self::get_search_area();
    }

    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 = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $key_str_len = strlen($key_str);

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

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

}
return DejavoSearch::instance();
}
