<?php
defined('ABSPATH') || exit;
//VERSION = '6.0.1';
if (dej_opt('dej_show_compare', '1')) {
class DejavoCP
{
    protected static $settings = [];
    protected static $fields = [];
    protected static $instance = null;

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

        return self::$instance;
    }

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

        // add query var
        add_filter('query_vars', [$this, 'query_vars']);

        // init
        add_action('init', [$this, 'init']);
        add_action('wp_login', [$this, 'login'], 10, 2);
        add_action('wp_footer', [$this, 'footer']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);

        // ajax search
        add_action('wp_ajax_DejavoCP_search', [$this, 'search']);
        add_action('wp_ajax_nopriv_DejavoCP_search', [$this, 'search']);

        // ajax load data
        add_action('wp_ajax_DejavoCP_load_data', [$this, 'load_data']);
        add_action('wp_ajax_nopriv_DejavoCP_load_data', [$this, 'load_data']);

        // ajax share
        add_action('wp_ajax_DejavoCP_share', [$this, 'share']);
        add_action('wp_ajax_nopriv_DejavoCP_share', [$this, 'share']);

        // ajax add field
        add_action('wp_ajax_DejavoCP_add_field', [$this, 'ajax_add_field']);

        // add to compare
        add_action('template_redirect', [$this, 'add_by_link']);

        // settings page
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_menu', [$this, 'admin_menu']);


        // my account
        if (self::get_setting('page_myaccount', 'yes') === 'yes') {
            add_filter('woocommerce_account_menu_items', [$this, 'account_items'], 99);
            add_action('woocommerce_account_compare_endpoint', [$this, 'account_endpoint'], 99);
        }

    }

    function query_vars($vars)
    {
        $vars[] = 'DejavoCP_id';

        return $vars;
    }

    function init()
    {
        // fields
        self::$fields = [
            'image' => __('Image', 'dejavo'),
            'sku' => __('SKU', 'dejavo'),
            'rating' => __('Rating', 'dejavo'),
            'price' => __('Price', 'dejavo'),
            'stock' => __('Stock', 'dejavo'),
            'availability' => __('Availability', 'dejavo'),
            'add_to_cart' => __('Add to cart', 'dejavo'),
            'description' => __('Description', 'dejavo'),
            'weight' => __('Weight', 'dejavo'),
            'dimensions' => __('Dimensions', 'dejavo'),
            'additional' => __('Additional information', 'dejavo')
        ];

        // rewrite
        if ($page_id = self::get_page_id()) {
            $page_slug = get_post_field('post_name', $page_id);

            if ($page_slug !== '') {
                add_rewrite_rule('^' . $page_slug . '/([\w]+)/?', 'index.php?page_id=' . $page_id . '&DejavoCP_id=$matches[1]', 'top');
                add_rewrite_rule('(.*?)/' . $page_slug . '/([\w]+)/?', 'index.php?page_id=' . $page_id . '&DejavoCP_id=$matches[2]', 'top');
            }
        }

        // my account page
        if (self::get_setting('page_myaccount', 'yes') === 'yes') {
            add_rewrite_endpoint('compare', EP_PAGES);
        }

        // shortcode
        add_shortcode('DejavoCP_list', [$this, 'shortcode_list']);
        add_shortcode('DejavoCP_quick_table', [$this, 'shortcode_quick_table']);

    }

    function login($user_login, $user)
    {
        if (isset($user->data->ID)) {
            $hash = self::get_setting('hash', '6');
            $user_products = get_user_meta($user->data->ID, 'DejavoCP_products', true);
            $user_fields = get_user_meta($user->data->ID, 'DejavoCP_fields_' . $hash, true);

            if (!empty($user_products)) {
                setcookie('DejavoCP_products_' . md5('DejavoCP' . $user->data->ID), $user_products, time() + 604800, '/');
            }

            if (!empty($user_fields)) {
                setcookie('DejavoCP_fields_' . $hash . '_' . md5('DejavoCP' . $user->data->ID), $user_fields, time() + 604800, '/');
            }
        }
    }

    function enqueue_scripts()
    {
        // print
        if (self::get_setting('bar_print', 'no') === 'yes') {
            wp_enqueue_script('print', DEJ_TUI . '/assets/libs/print/jQuery.print.js', ['jquery'], DEJ_VERSION, true);
        }

        // table head fixer
        wp_enqueue_script('table-head-fixer', DEJ_TUI . '/assets/libs/table-head-fixer/table-head-fixer.js', ['jquery'], DEJ_VERSION, true);


        // notiny
        if (self::get_setting('button_action', 'show_table') === 'show_message') {
            wp_enqueue_style('notiny', DEJ_TUI . '/assets/libs/notiny/notiny.css');
            wp_enqueue_script('notiny', DEJ_TUI . '/assets/libs/notiny/notiny.js', ['jquery'], DEJ_VERSION, true);
        }

        // frontend css & js
        wp_enqueue_style('DejavoCP-frontend', DEJ_TUI . '/assets/css/compare.css', [], DEJ_VERSION);
        wp_enqueue_script('DejavoCP-frontend', DEJ_TUI . '/assets/js/compare.min.js', [
            'jquery',
            'jquery-ui-sortable'
        ], DEJ_VERSION, true);


        wp_localize_script('DejavoCP-frontend', 'DejavoCP_vars', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'hash' => self::get_setting('hash', '6'),
                'user_id' => md5('DejavoCP' . get_current_user_id()),
                'page_url' => self::get_page_url(),
                'open_button' => esc_attr(self::get_setting('open_button', '')),
                'open_button_action' => self::get_setting('open_button_action', 'open_popup'),
                'menu_action' => self::get_setting('menu_action', 'open_popup'),
                'button_action' => self::get_setting('button_action', 'show_table'),
                'message_position' => self::get_setting('message_position', 'right-top'),
                'message_added' => esc_html__('{name} has been added to Compare list.', 'dejavo'),
                'message_removed' => esc_html__('{name} has been removed from the Compare list.', 'dejavo'),
                'message_exists' => esc_html__('{name} is already in the Compare list.', 'dejavo'),
                'open_bar' => self::get_setting('open_bar_immediately', 'no'),
                'bar_bubble' => self::get_setting('bar_bubble', 'no'),
                'adding' => self::get_setting('adding', 'prepend'),
                'click_again' => self::get_setting('click_again', 'no'),
                'hide_empty' => self::get_setting('hide_empty', 'no'),
                'click_outside' => self::get_setting('click_outside', 'yes'),
                'freeze_column' => self::get_setting('freeze_column', 'yes'),
                'freeze_row' => self::get_setting('freeze_row', 'yes'),
                'limit' => self::get_setting('limit', '20'),
                'remove_all' => __('Do you want to remove all products from the compare?', 'dejavo'),
                'limit_notice' => esc_html__('You can add a maximum of {limit} products to the comparison table.', 'dejavo'),
                'copied_text' => esc_html__('Share link %s was copied to clipboard!', 'dejavo'),
                'button_text' => '<i class="dej-shuffle"></i>',
                'button_text_added' => '<i class="dej-check"></i>',
            ]
        );
    }


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

    function admin_menu()
    {
        add_submenu_page('future', __('Compare', 'dejavo'), __('Compare', 'dejavo'), 'manage_options', 'future-DejavoCP', 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 __('Compare', 'dejavo'); ?></h1>

                <?php if (isset($_GET['settings-updated']) && $_GET['settings-updated']) {
                    flush_rewrite_rules();
                    ?>
                    <div class="notice notice-success is-dismissible">
                        <p><?php esc_html_e('Settings updated.', 'dejavo'); ?></p>
                    </div>
                <?php } ?>
                <div class="dejavo_settings_page_content">
                    <?php
                    $adding = self::get_setting('adding', 'prepend');
                    $hide_checkout = self::get_setting('hide_checkout', 'yes');
                    $hide_empty = self::get_setting('hide_empty', 'no');
                    $button_action = self::get_setting('button_action', 'show_table');
                    $message_position = self::get_setting('message_position', 'right-top');
                    $click_again = self::get_setting('click_again', 'no');
                    $link = self::get_setting('link', 'yes');
                    $remove = self::get_setting('remove', 'yes');
                    $freeze_column = self::get_setting('freeze_column', 'yes');
                    $freeze_row = self::get_setting('freeze_row', 'yes');
                    $close_button = self::get_setting('close_button', 'yes');
                    $bar_bubble = self::get_setting('bar_bubble', 'no');
                    $bar_print = self::get_setting('bar_print', 'no');
                    $bar_share = self::get_setting('bar_share', 'yes');
                    $bar_add = self::get_setting('bar_add', 'yes');
                    $bar_remove = self::get_setting('bar_remove', 'yes');
                    $bar_pos = self::get_setting('bar_pos', 'bottom');
                    $bar_align = self::get_setting('bar_align', 'right');
                    $click_outside = self::get_setting('click_outside', 'yes');
                    $page_myaccount = self::get_setting('page_myaccount', 'yes');
                    $menu_action = self::get_setting('menu_action', 'open_popup');
                    $open_button_action = self::get_setting('open_button_action', 'open_popup');
                    ?>
                    <form method="post" action="options.php">
                        <input type="hidden" name="DejavoCP_settings[hash]"
                               value="<?php echo esc_attr(self::generate_key(4, true)); ?>"/>
                        <table class="form-table">
                            <tr class="heading">
                                <th colspan="2">
                                    <?php esc_html_e('General', 'dejavo'); ?>
                                </th>
                            </tr>
                            <tr>
                                <th><?php esc_html_e('Product adding', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[adding]">
                                        <option value="prepend" <?php selected($adding, 'prepend'); ?>><?php esc_html_e('Prepend', 'dejavo'); ?></option>
                                        <option value="append" <?php selected($adding, 'append'); ?>><?php esc_html_e('Append', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('The new product will be added to the first or last of the list?', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Hide on cart & checkout page', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[hide_checkout]">
                                        <option value="yes" <?php selected($hide_checkout, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($hide_checkout, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Hide the comparison table and comparison bar on the cart & checkout page?', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Hide if empty', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[hide_empty]">
                                        <option value="yes" <?php selected($hide_empty, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($hide_empty, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Hide the comparison table and comparison bar if haven\'t any product.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Limit', 'dejavo'); ?></th>
                                <td>
                                    <input type="number" min="1" max="100" step="1" name="DejavoCP_settings[limit]"
                                           value="<?php echo self::get_setting('limit', '100'); ?>"/>
                                    <span class="description"><?php esc_html_e('The maximum of products can be added to the comparison table.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Comparison page', 'dejavo'); ?></th>
                                <td>
                                    <?php wp_dropdown_pages([
                                        'selected' => self::get_setting('page_id', ''),
                                        'name' => 'DejavoCP_settings[page_id]',
                                        'show_option_none' => __('Choose a page', 'dejavo'),
                                        'option_none_value' => '',
                                    ]); ?>
                                    <span class="description"><?php printf(__('Add shortcode %s to display the comparison table on this page.', 'dejavo'), '<code>[DejavoCP_list]</code>'); ?></span>
                                </td>
                            </tr>
                            <tr class="heading">
                                <th>
                                    <?php esc_html_e('Compare button', 'dejavo'); ?>
                                </th>
                                <td></td>
                            </tr>

                            <tr>
                                <th scope="row"><?php esc_html_e('Action', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[button_action]" class="DejavoCP_button_action">
                                        <option value="show_bar" <?php selected($button_action, 'show_bar'); ?>><?php esc_html_e('Open comparison bar', 'dejavo'); ?></option>
                                        <option value="show_table" <?php selected($button_action, 'show_table'); ?>><?php esc_html_e('Open comparison table', 'dejavo'); ?></option>
                                        <option value="show_message" <?php selected($button_action, 'show_message'); ?>><?php esc_html_e('Show message', 'dejavo'); ?></option>
                                        <option value="none" <?php selected($button_action, 'none'); ?>><?php esc_html_e('Add to compare solely', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Action triggered by clicking on the compare button.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr class="DejavoCP_button_action_hide DejavoCP_button_action_show_message">
                                <th scope="row"><?php esc_html_e('Message position', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[message_position]">
                                        <option value="right-top" <?php selected($message_position, 'right-top'); ?>><?php esc_html_e('right-top', 'dejavo'); ?></option>
                                        <option value="right-bottom" <?php selected($message_position, 'right-bottom'); ?>><?php esc_html_e('right-bottom', 'dejavo'); ?></option>
                                        <option value="fluid-top" <?php selected($message_position, 'fluid-top'); ?>><?php esc_html_e('center-top', 'dejavo'); ?></option>
                                        <option value="fluid-bottom" <?php selected($message_position, 'fluid-bottom'); ?>><?php esc_html_e('center-bottom', 'dejavo'); ?></option>
                                        <option value="left-top" <?php selected($message_position, 'left-top'); ?>><?php esc_html_e('left-top', 'dejavo'); ?></option>
                                        <option value="left-bottom" <?php selected($message_position, 'left-bottom'); ?>><?php esc_html_e('left-bottom', 'dejavo'); ?></option>
                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row"><?php esc_html_e('Remove when clicking again', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[click_again]">
                                        <option value="yes" <?php selected($click_again, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($click_again, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Do you want to remove product when clicking again?', 'dejavo'); ?></span>
                                </td>
                            </tr>

                            <tr class="heading">
                                <th>
                                    <?php esc_html_e('Comparison table', 'dejavo'); ?>
                                </th>
                                <td></td>
                            </tr>
                            <tr>
                                <th><?php esc_html_e('Link to individual product', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_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('"Remove" button', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[remove]">
                                        <option value="yes" <?php selected($remove, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($remove, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Show remove button beside product name.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Freeze first column', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[freeze_column]">
                                        <option value="yes" <?php selected($freeze_column, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($freeze_column, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Freeze the first column (fields and attributes title) when scrolling horizontally.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Freeze first row', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[freeze_row]">
                                        <option value="yes" <?php selected($freeze_row, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($freeze_row, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Freeze the first row (product name) when scrolling vertically.', 'dejavo'); ?></span>
                                </td>
                            </tr>

                            <th scope="row"><?php esc_html_e('Close button', 'dejavo'); ?></th>
                            <td>
                                <select name="DejavoCP_settings[close_button]">
                                    <option value="yes" <?php selected($close_button, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                    <option value="no" <?php selected($close_button, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                </select>
                                <span class="description"><?php esc_html_e('Enable the close button at top-right conner of comparison table?', 'dejavo'); ?></span>
                            </td>
                            </tr>
                            <tr class="heading">
                                <th>
                                    <?php esc_html_e('Comparison bar', 'dejavo'); ?>
                                </th>
                                <td></td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Open immediately', 'dejavo'); ?></th>
                                <td>
                                    <input type="checkbox" name="DejavoCP_settings[open_bar_immediately]"
                                           value="yes" <?php echo esc_attr(self::get_setting('open_bar_immediately', 'no') === 'yes' ? 'checked' : ''); ?>/>
                                    <span class="description"><?php esc_html_e('Check it if you want to open the comparison bar immediately on page loaded.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Bubble', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[bar_bubble]">
                                        <option value="yes" <?php selected($bar_bubble, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($bar_bubble, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Use the bubble instead of a fully comparison bar.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('"Print" button', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[bar_print]">
                                        <option value="yes" <?php selected($bar_print, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($bar_print, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Show the print button.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('"Share" button', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[bar_share]">
                                        <option value="yes" <?php selected($bar_share, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($bar_share, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Show the share button.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('"Add more" button', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[bar_add]">
                                        <option value="yes" <?php selected($bar_add, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($bar_add, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Add the button to search product and add to compare list immediately.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('"Add more" count', 'dejavo'); ?></th>
                                <td>
                                    <input type="number" min="1" max="100" name="DejavoCP_settings[search_count]"
                                           value="<?php echo self::get_setting('search_count', 10); ?>"/>
                                    <span class="description"><?php esc_html_e('The result count of search function when clicking on "Add more" button.', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('"Remove all" button', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[bar_remove]">
                                        <option value="yes" <?php selected($bar_remove, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($bar_remove, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Add the button to remove all products from compare immediately.', 'dejavo'); ?></span>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row"><?php esc_html_e('Position', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[bar_pos]">
                                        <option value="bottom" <?php selected($bar_pos, 'bottom'); ?>><?php esc_html_e('Bottom', 'dejavo'); ?></option>
                                        <option value="top" <?php selected($bar_pos, 'top'); ?>><?php esc_html_e('Top', 'dejavo'); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Align', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[bar_align]">
                                        <option value="right" <?php selected($bar_align, 'right'); ?>><?php esc_html_e('Right', 'dejavo'); ?></option>
                                        <option value="left" <?php selected($bar_align, 'left'); ?>><?php esc_html_e('Left', 'dejavo'); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Click outside to hide', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[click_outside]">
                                        <option value="yes" <?php selected($click_outside, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="yes_empty" <?php selected($click_outside, 'yes_empty'); ?>><?php esc_html_e('Yes if empty', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($click_outside, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                </td>
                            </tr>


                            <tr class="heading">
                                <th>
                                    <?php esc_html_e('Menu', 'dejavo'); ?>
                                </th>
                                <td></td>
                            </tr>

                            <tr>
                                <th scope="row"><?php esc_html_e('Action', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[menu_action]">
                                        <option value="open_page" <?php selected($menu_action, 'open_page'); ?>><?php esc_html_e('Open comparison page', 'dejavo'); ?></option>
                                        <option value="open_popup" <?php selected($menu_action, 'open_popup'); ?>><?php esc_html_e('Open comparison table', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Action when clicking on the "compare menu".', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Add Comparison page to My Account', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[page_myaccount]">
                                        <option value="yes" <?php selected($page_myaccount, 'yes'); ?>><?php esc_html_e('Yes', 'dejavo'); ?></option>
                                        <option value="no" <?php selected($page_myaccount, 'no'); ?>><?php esc_html_e('No', 'dejavo'); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Custom menu action', 'dejavo'); ?></th>
                                <td>
                                    <select name="DejavoCP_settings[open_button_action]">
                                        <option value="open_page" <?php selected($open_button_action, 'open_page'); ?>><?php esc_html_e('Open comparison page', 'dejavo'); ?></option>
                                        <option value="open_popup" <?php selected($open_button_action, 'open_popup'); ?>><?php esc_html_e('Open comparison table', 'dejavo'); ?></option>
                                    </select>
                                    <span class="description"><?php esc_html_e('Action when clicking on the "custom menu".', 'dejavo'); ?></span>
                                </td>
                            </tr>
                            <tr class="submit">
                                <th colspan="2">
                                    <?php settings_fields('DejavoCP_settings'); ?><?php submit_button(); ?>
                                </th>
                            </tr>
                        </table>
                    </form>
                </div>
            </div>
            <?php
        }
    }

    function load_data()
    {
        $data = [];

        if (isset($_REQUEST['get_data']) && (sanitize_key($_REQUEST['get_data']) === 'bar')) {
            $data['bar'] = self::get_bar();
        }

        if (isset($_REQUEST['get_data']) && (sanitize_key($_REQUEST['get_data']) === 'table')) {
            $data['bar'] = self::get_bar();
            $data['table'] = self::get_table(true, null, 'table');
        }


        wp_send_json($data);
    }

    function get_bar()
    {
        // get items
        $bar = '';
        $products = [];
        $cookie = 'DejavoCP_products_' . md5('DejavoCP' . get_current_user_id());

        if (isset($_COOKIE[$cookie]) && !empty($_COOKIE[$cookie])) {
            $products = explode(',', sanitize_text_field($_COOKIE[$cookie]));
        }

        if (!empty($products)) {
            foreach ($products as $product_id) {
                $product_obj = wc_get_product($product_id);

                if (!$product_obj || $product_obj->get_status() !== 'publish') {
                    continue;
                }

                $product_name = $product_obj->get_name();

                $bar .= '<div class="DejavoCP-bar-item" data-id="' . esc_attr($product_id) . '">';
                $bar .= '<span class="DejavoCP-bar-item-img hint--top" role="button" aria-label="' . esc_attr(wp_strip_all_tags($product_name)) . '">' . $product_obj->get_image('thumbnail') . '</span>';
                $bar .= '<span class="DejavoCP-bar-item-remove hint--top" role="button" aria-label="' . __('Remove', 'dejavo') . '" data-id="' . $product_id . '"><i class="dej-cross-small"></i></span></div>';
            }
        }

        return $bar;
    }

    function get_table($ajax = true, $products = null, $context = '')
    {


        // get items
        $table = '';
        $products_data = [];
        $is_share = false;

        if (is_null($products)) {
            $products = [];

            if (get_query_var('DejavoCP_id')) {


                $is_share = true;
                $key = get_query_var('DejavoCP_id');
                $products = explode(',', get_option('DejavoCP_list_' . $key) ?: '');
            } else {
                $cookie = 'DejavoCP_products_' . md5('DejavoCP' . get_current_user_id());

                if (isset($_COOKIE[$cookie]) && !empty($_COOKIE[$cookie])) {
                    if (is_user_logged_in()) {
                        update_user_meta(get_current_user_id(), 'DejavoCP_products', sanitize_text_field($_COOKIE[$cookie]));
                    }

                    $products = explode(',', sanitize_text_field($_COOKIE[$cookie]));
                }
            }

        }

        if (is_array($products) && (count($products) > 0)) {
            $link = self::get_setting('link', 'yes');
            $remove = self::get_setting('remove', 'yes') === 'yes';
            $fields = self::get_fields($context);

            global $post;

            foreach ($products as $product_id) {
                $post = get_post($product_id);
                setup_postdata($post);

                $product = wc_get_product($product_id);
                $parent_product = false;

                if (!$product || $product->get_status() !== 'publish') {
                    continue;
                }

                if ($product->is_type('variation') && ($parent_product_id = $product->get_parent_id())) {
                    $parent_product = wc_get_product($parent_product_id);
                }

                $products_data[$product_id]['id'] = $product_id;

                $product_name = $product->get_name();

                if ($link !== 'no') {
                    $products_data[$product_id]['name'] = '<a ' . ($link === 'yes_popup' ? 'class="woosq-link" data-id="' . $product_id . '" data-context="DejavoCP"' : '') . ' href="' . $product->get_permalink() . '" draggable="false" ' . ($link === 'yes_blank' ? 'target="_blank"' : '') . '>' . wp_strip_all_tags($product_name) . '</a>';
                } else {
                    $products_data[$product_id]['name'] = wp_strip_all_tags($product_name);
                }

                if ($remove && !$is_share) {
                    $products_data[$product_id]['name'] .= ' <span class="DejavoCP-remove" data-id="' . $product_id . '">' . __('remove', 'dejavo') . '</span>';
                }

                foreach ($fields as $key => $field) {
                    $field = array_merge([
                        'type' => '',
                        'name' => '',
                        'label' => ''
                    ], $field);
                    $field_type = $field['type'];
                    $field_name = $field['name'];

                    if ($field_type === 'default') {
                        // default fields
                        switch ($field_name) {
                            case 'image':
                                $image = $product->get_image('medium', [
                                    'draggable' => 'false',
                                    'loading' => self::get_setting('bar_print', 'no') === 'yes' ? false : 'lazy'
                                ]);

                                if ($link !== 'no') {
                                    $products_data[$product_id]['image'] = '<a ' . ($link === 'yes_popup' ? 'class="woosq-link" data-id="' . $product_id . '" data-context="DejavoCP"' : '') . ' href="' . $product->get_permalink() . '" draggable="false" ' . ($link === 'yes_blank' ? 'target="_blank"' : '') . '>' . $image . '</a>';
                                } else {
                                    $products_data[$product_id]['image'] = $image;
                                }

                                break;
                            case 'sku':
                                $products_data[$product_id]['sku'] = $product->get_sku();
                                break;
                            case 'price':
                                $products_data[$product_id]['price'] = $product->get_price_html();
                                break;
                            case 'stock':
                                $products_data[$product_id]['stock'] = wc_get_stock_html($product);
                                break;
                            case 'add_to_cart':
                                $products_data[$product_id]['add_to_cart'] = do_shortcode('[add_to_cart style="" show_price="false" id="' . $product_id . '"]');
                                break;
                            case 'description':
                                $description = $product->get_short_description();

                                if ($product->is_type('variation')) {
                                    $description = $product->get_description();

                                    if (empty($description) && $parent_product) {
                                        $description = $parent_product->get_short_description();
                                    }
                                }

                                $products_data[$product_id]['description'] = $description;

                                break;


                            case 'rating':
                                $products_data[$product_id]['rating'] = wc_get_rating_html($product->get_average_rating());
                                break;
                            case 'availability':
                                $product_availability = $product->get_availability();
                                $products_data[$product_id]['availability'] = $product_availability['availability'];
                                break;
                            case 'additional':
                                ob_start();
                                wc_display_product_attributes($product);
                                $additional = ob_get_clean();
                                $products_data[$product_id]['additional'] = $additional;
                                break;

                        }
                    }

                    if ($field_type === 'shortcode') {
                        $products_data[$product_id]['sc_' . $key] = do_shortcode(str_replace('{product_id}', $product_id, $field_name));
                    }
                }
            }

            wp_reset_postdata();

            $count = count($products_data);
            $table_class = 'DejavoCP_table has-' . $count;
            $minimum_columns = 3;

            if ($minimum_columns > $count) {
                for ($i = 1; $i <= ($minimum_columns - $count); $i++) {
                    $products_data['p' . $i]['name'] = '';
                }
            }

            $table .= '<table ' . ($ajax ? 'id="DejavoCP_table"' : '') . ' class="' . esc_attr($table_class) . '"><thead><tr>';


            $table .= '<th class="th-label"></th>';


            foreach ($products_data as $product_data) {
                if ($product_data['name'] !== '') {
                    $table .= '<th>' . $product_data['name'] . '</th>';
                } else {
                    $table .= '<th class="th-placeholder"></th>';
                }
            }

            $table .= '</tr></thead><tbody>';

            if ($context === 'table') {
                $cookie_fields = self::get_cookie_fields(array_keys($fields));
                $fields = array_merge(array_flip($cookie_fields), $fields);
            } else {
                $cookie_fields = array_keys($fields);
            }

            // display product name for printing
            if (self::get_setting('bar_print', 'no') === 'yes') {
                $table .= '<tr class="tr-name tr-print"><td class="td-label">' . __('Name', 'dejavo') . '</td>';

                foreach ($products_data as $product_data) {
                    if ($product_data['name'] !== '') {
                        $table .= '<td>' . $product_data['name'] . '</td>';
                    } else {
                        $table .= '<td class="td-placeholder"></td>';
                    }
                }

                $table .= '</tr>';
            }

            $tr = 1;

            foreach ($fields as $key => $field) {
                $field = array_merge([
                    'type' => '',
                    'name' => '',
                    'label' => ''
                ], $field);
                $field_type = $field['type'];
                $field_name = $field['name'];
                $field_label = $field['label'];
                $field_key = $field_name;

                if ($field_type === 'default') {
                    $field_label = self::$fields[$field_name];
                }

                if ($field_type === 'attribute') {
                    $field_label = wc_attribute_label($field_name);
                }

                if ($field_type === 'custom_attribute') {
                    $field_key = 'ca_' . sanitize_title(trim($field_name));
                    $field_label = !empty($field['label']) ? $field['label'] : $field_name;
                }

                if ($field_type === 'custom_field') {
                    $field_key = 'cf_' . sanitize_title(trim($field_name));
                    $field_label = !empty($field['label']) ? $field['label'] : $field_name;
                }

                if ($field_type === 'shortcode') {
                    $field_key = 'sc_' . $key;
                    $field_label = !empty($field['label']) ? $field['label'] : $field_name;
                }

                $row = '<tr class="tr-default tr-' . ($tr % 2 ? 'odd' : 'even') . ' tr-' . esc_attr($key) . ' tr-' . esc_attr($field_key) . ' ' . (!in_array($key, $cookie_fields) ? 'tr-hide' : '') . '"><td class="td-label">' . esc_html($field_label) . '</td>';

                foreach ($products_data as $product_id => $product_data) {
                    if ($product_data['name'] !== '') {
                        if (isset($product_data[$field_key])) {
                            $field_value = $product_data[$field_key];
                        } else {
                            $field_value = '';
                        }

                        $row .= '<td>' . apply_filters('DejavoCP_field_value', $field_value, $field_key, $product_id, $product_data) . '</td>';
                    } else {
                        $row .= '<td class="td-placeholder"></td>';
                    }
                }

                $row .= '</tr>';
                $tr++;

                if (!empty($row)) {
                    $table .= $row;
                }
            }

            $table .= '</tbody></table>';
        } else {
            $table = '<div class="DejavoCP-no-result">' . __('No product is added to the comparison table.', 'dejavo') . '</div>';
        }

        return $table;
    }

    function add_by_link()
    {
        if (!isset($_REQUEST['add-to-compare']) && !isset($_REQUEST['add_to_compare'])) {
            return false;
        }

        $product_id = absint(isset($_REQUEST['add_to_compare']) ? $_REQUEST['add_to_compare'] : 0);
        $product_id = absint(isset($_REQUEST['add-to-compare']) ? $_REQUEST['add-to-compare'] : $product_id);

        if (!$product_id) {
            return false;
        }

        $user_id = get_current_user_id();
        $cookie = 'DejavoCP_products_' . md5('DejavoCP' . $user_id);
        $user_products = isset($_COOKIE[$cookie]) ? explode(',', sanitize_text_field($_COOKIE[$cookie])) : [];

        // move product to the first
        array_unshift($user_products, $product_id);
        $user_products = array_unique($user_products);

        if ($user_id) {
            // update user meta
            update_user_meta($user_id, 'DejavoCP_products', implode(',', $user_products));
        }

        setcookie($cookie, implode(',', $user_products), time() + 604800, '/');

        // redirect to compare page
        wp_safe_redirect(self::get_page_url());
    }


    function search()
    {
        $keyword = sanitize_text_field($_POST['keyword']);
        $products = $related = [];
        $cookie = 'DejavoCP_products_' . md5('DejavoCP' . get_current_user_id());

        if (isset($_COOKIE[$cookie]) && !empty($_COOKIE[$cookie])) {
            $products = explode(',', sanitize_text_field($_COOKIE[$cookie]));
        }

        $args['status'] = ['publish'];
        $args['limit'] = self::get_setting('search_count', 10);


        if (empty($keyword)) {
            // default products
            if (!empty($products)) {
                foreach ($products as $pid) {
                    if ($rl = wc_get_related_products($pid)) {
                        $related = array_merge($related, $rl);
                    }
                }
            }

            foreach ($related as $k => $r) {
                if (in_array($r, $products)) {
                    // exclude added products
                    unset($related[$k]);
                }
            }

            $related = array_unique($related);

            if (!empty($related)) {
                $args['include'] = $related;
            }
        } else {
            $args['s'] = $keyword;
        }

        $prs = wc_get_products($args);

        if (!empty($prs)) {
            echo '<ul>';

            foreach ($prs as $pr) {

                echo '<li>';
                echo '<div class="item-inner">';
                echo '<div class="item-image">' . $pr->get_image('thumbnail') . '</div>';
                echo '<div class="item-name">' . $pr->get_name() . '</div>';
                echo '<div class="item-add DejavoCP-item-add" data-id="' . $pr->get_id() . '"><span>+</span></div>';
                echo '</div>';
                echo '</li>';
            }

            echo '</ul>';
        } else {
            echo '<ul><span>' . sprintf(esc_html__('No results found for "%s"', 'dejavo'), $keyword) . '</span></ul>';
        }

        wp_die();
    }


    public static function cp_btn($id)
    {
        $output = '';
        if ($id) {
            $class = 'DejavoCP-btn DejavoCP-btn-' . $id;
            $output = '<a rel="nofollow" href="' . esc_url('?add-to-compare=' . $id) . '" class="' . esc_attr($class) . '" data-id="' . $id . '"><i class="dej-shuffle"></i></a>';
        }
        return $output;
    }

    function shortcode_list($attrs)
    {
        $attrs = shortcode_atts([
            'products' => null,
        ], $attrs);

        if ($attrs['products']) {
            $attrs['products'] = array_map('absint', explode(',', $attrs['products']));
        }

        return '<div class="DejavoCP_list DejavoCP-list DejavoCP_page DejavoCP-page">' . self::get_table(false, $attrs['products'], 'page') . '</div>';
    }

    function footer()
    {
        if (is_admin() || get_query_var('DejavoCP_id')) {
            return;
        }

        $class = 'DejavoCP-area';
        $class .= ' DejavoCP-bar-' . self::get_setting('bar_pos', 'bottom') . ' DejavoCP-bar-' . self::get_setting('bar_align', 'right') . ' DejavoCP-bar-click-outside-' . str_replace('_', '-', self::get_setting('click_outside', 'yes'));

        if (self::get_setting('hide_checkout', 'yes') === 'yes') {
            $class .= ' DejavoCP-hide-checkout';
        }

        if (self::get_setting('hide_empty', 'no') === 'yes') {
            $class .= ' DejavoCP-hide-empty';
        }


        if (self::get_setting('bar_add', 'yes') === 'yes') {
            ?>
            <div class="DejavoCP-popup DejavoCP-search">
                <div class="DejavoCP-popup-inner">
                    <div class="DejavoCP-popup-content">
                        <div class="DejavoCP-popup-content-inner">
                            <div class="DejavoCP-popup-close"><i class="dej-cross-small"></i></div>
                            <div class="DejavoCP-search-input">
                                <input type="search" id="DejavoCP_search_input"
                                       placeholder="<?php echo __('Type any keyword to search...', 'dejavo'); ?>"/>
                            </div>
                            <div class="DejavoCP-search-result"></div>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }


        if (self::get_setting('bar_share', 'yes') === 'yes') {
            ?>
            <div class="DejavoCP-popup DejavoCP-share">
                <div class="DejavoCP-popup-inner">
                    <div class="DejavoCP-popup-content">
                        <div class="DejavoCP-popup-content-inner">
                            <div class="DejavoCP-popup-close"><i class="dej-cross-small"></i></div>
                            <div class="DejavoCP-share-content"></div>
                        </div>
                    </div>
                </div>
            </div>
        <?php }
        ?>
        <div id="DejavoCP-area" class="<?php echo esc_attr($class); ?>">
            <div class="DejavoCP-inner">
                <div class="DejavoCP-table">
                    <div class="DejavoCP-table-inner">
                        <?php if ('yes' === self::get_setting('close_button', 'yes')) { ?>
                            <a href="#close" id="DejavoCP-table-close" class="DejavoCP-table-close hint--right"
                               aria-label="<?php echo __('Close', 'dejavo'); ?>"><span
                                        class="DejavoCP-table-close-icon"><i class="dej-cross-small"></i></span></a>
                        <?php } ?>
                        <div class="DejavoCP-table-items"></div>
                    </div>
                </div>

                <div class="<?php echo esc_attr(self::get_setting('bar_bubble', 'no') === 'yes' ? 'DejavoCP-bar DejavoCP-bar-bubble' : 'DejavoCP-bar'); ?>">
                    <?php if (self::get_setting('click_outside', 'yes') !== 'no' && self::get_setting('bar_bubble', 'no') !== 'yes') { ?>
                        <div class="DejavoCP-bar-notice">
                            <?php echo __('Click outside to hide the comparison bar', 'dejavo'); ?>
                        </div>
                    <?php }

                    if (self::get_setting('bar_print', 'no') === 'yes') { ?>
                        <a href="#print" class="DejavoCP-bar-print hint--top"
                           aria-label="<?php echo __('Print', 'dejavo'); ?>"><i
                                    class="dej-print"></i></a>
                    <?php }

                    if (self::get_setting('bar_share', 'yes') === 'yes') { ?>
                        <a href="#share" class="DejavoCP-bar-share hint--top"
                           aria-label="<?php echo __('Share', 'dejavo'); ?>"><i
                                    class="dej-share"></i></a>
                    <?php }

                    if (self::get_setting('bar_add', 'yes') === 'yes') { ?>
                        <a href="#search" class="DejavoCP-bar-search hint--top"
                           aria-label="<?php echo __('Add product', 'dejavo'); ?>"><i class="dej-plus"></i></a>
                    <?php }

                    echo '<div class="DejavoCP-bar-items"></div>';

                    if (self::get_setting('bar_remove', 'yes') === 'yes') { ?>
                        <div class="DejavoCP-bar-remove hint--top" role="button"
                             aria-label="<?php echo __('Remove all', 'dejavo'); ?>"><i class="dej-trash"></i></div>
                    <?php } ?>

                    <div class="DejavoCP-bar-btn DejavoCP-bar-btn-text">
                        <div class="DejavoCP-bar-btn-icon-wrapper">
                            <div class="DejavoCP-bar-btn-icon-inner"><span></span><span></span><span></span>
                            </div>
                        </div>
                        <?php echo __('Compare', 'dejavo'); ?>
                    </div>
                </div>


            </div>
        </div>
        <?php
    }

    function get_cookie_fields($saved_fields)
    {
        $hash = self::get_setting('hash', '6');
        $cookie_fields = 'DejavoCP_fields_' . $hash . '_' . md5('DejavoCP' . get_current_user_id());

        if (isset($_COOKIE[$cookie_fields]) && !empty($_COOKIE[$cookie_fields])) {
            $fields = explode(',', sanitize_text_field($_COOKIE[$cookie_fields]));
        } else {
            $fields = $saved_fields;
        }

        return $fields;
    }


    function exists_key($key)
    {
        if (get_option('DejavoCP_list_' . $key)) {
            return true;
        }

        return false;
    }

    function account_items($items)
    {
        if (isset($items['customer-logout'])) {
            $logout = $items['customer-logout'];
            unset($items['customer-logout']);
        } else {
            $logout = '';
        }

        if (!isset($items['compare'])) {
            $items['compare'] = __('Compare', 'dejavo');
        }

        if ($logout) {
            $items['customer-logout'] = $logout;
        }

        return $items;
    }

    function account_endpoint()
    {
        echo do_shortcode('[DejavoCP_list]');
    }

    function shortcode_quick_table()
    {
        global $product;

        if (!$product) {
            return '';
        }

        $product_id = $product->get_id();
        $related = wc_get_related_products($product_id);

        if (empty($related)) {
            return '';
        }

        array_unshift($related, $product_id);

        $quick_table_class = 'DejavoCP-quick-table label-column-' . self::get_setting('quick_table_label', 'no');
        ob_start();
        ?>
        <section class="<?php echo esc_attr($quick_table_class); ?>">
            <?php
            echo '<h2>' . __('Quick Comparison', 'dejavo') . '</h2>';
            ?>
            <div class="DejavoCP-quick-table-products">
                <?php
                echo self::get_table(false, $related, 'quick_table');
                ?>
            </div>
        </section>
        <?php
        return ob_get_clean();
    }


    function share()
    {
        $products = '';
        $cookie = 'DejavoCP_products_' . md5('DejavoCP' . get_current_user_id());

        if (isset($_COOKIE[$cookie]) && !empty($_COOKIE[$cookie])) {
            $products = sanitize_text_field($_COOKIE[$cookie]);
        }

        if (!empty($products)) {
            $hash = md5($products);

            if (!$key = get_option('DejavoCP_hash_' . $hash)) {
                $key = self::generate_key();

                while (self::exists_key($key)) {
                    $key = self::generate_key();
                }

                update_option('DejavoCP_hash_' . $hash, $key);
                update_option('DejavoCP_list_' . $key, $products);
            }

            $url = self::get_share_url($key);

            if (!empty($url)) {
                ?>
                <div class="DejavoCP-share-text">
                    <?php echo __('Share link was generated! Now you can copy below link to share.', 'dejavo'); ?>
                </div>
                <div class="DejavoCP-share-link">
                    <input type="url" id="DejavoCP_copy_url" value="<?php echo esc_url($url); ?>" readonly/>
                </div>
                <?php
                echo self::share_links(urlencode($url));
            }
        } else {
            echo __('No product is added to the comparison table.', 'dejavo');
        }

        wp_die();
    }

    function ajax_add_field()
    {
        $type = isset($_POST['type']) ? sanitize_key($_POST['type']) : '';
        $field = isset($_POST['field']) ? sanitize_text_field(urldecode($_POST['field'])) : '';
        $setting = isset($_POST['setting']) ? sanitize_key($_POST['setting']) : '';

        if (!empty($type) && !empty($field) && !empty($setting)) {
            $key = self::generate_key(4, true);
            $title = '';

            switch ($type) {
                case 'default':
                    if (isset(self::$fields[$field])) {
                        $title = self::$fields[$field];
                    }

                    break;
                case 'attribute':
                    $title = wc_attribute_label($field);

                    break;
                case 'custom_attribute':
                    $title = __('Custom attribute', 'dejavo');

                    break;
                case 'custom_field':
                    $title = __('Custom field', 'dejavo');

                    break;
                case 'shortcode':
                    $title = __('Shortcode', 'dejavo');

                    break;
            }

            echo '<div class="DejavoCP-field DejavoCP-field-' . $key . ' DejavoCP-field-type-' . $type . '">';
            echo '<span class="move">' . __('move', 'dejavo') . '</span>';
            echo '<span class="info">';
            echo '<span class="title">' . esc_html($title) . '</span>';
            echo '<input class="DejavoCP-field-type" type="hidden" name="DejavoCP_settings[' . $setting . '][' . $key . '][type]" value="' . esc_attr($type) . '"/>';
            echo '<input class="DejavoCP-field-name" type="text" name="DejavoCP_settings[' . $setting . '][' . $key . '][name]" value="' . esc_attr($field) . '" placeholder="' . esc_attr__('name', 'dejavo') . '"/>';
            echo '<input class="DejavoCP-field-label" type="text" name="DejavoCP_settings[' . $setting . '][' . $key . '][label]" value="" placeholder="' . esc_attr__('label', 'dejavo') . '"/>';
            echo '</span>';
            echo '<span class="remove">&times;</span>';
            echo '</div>';
        }

        wp_die();
    }

    function get_page_id()
    {
        if (self::get_setting('page_id')) {
            return absint(self::get_setting('page_id'));
        }

        return false;
    }

    function get_share_url($key)
    {
        $url = home_url('/');

        if ($page_id = self::get_page_id()) {
            if (get_option('permalink_structure') !== '') {
                $url = trailingslashit(get_permalink($page_id)) . $key;
            } else {
                $url = get_permalink($page_id) . '&DejavoCP_id=' . $key;
            }
        }

        return $url;
    }

    function share_links($url)
    {
        $share_links = '';
        $links = ['facebook', 'twitter', 'pinterest', 'mail'];

        if (!empty($links)) {
            $share_links .= '<div class="DejavoCP-share-links">';
            $share_links .= '<span class="DejavoCP-share-label">' . __('Share on:', 'dejavo') . '</span>';
            $share_links .= (in_array('facebook', $links)) ? '<a class="DejavoCP-share-facebook" href="https://www.facebook.com/sharer.php?u=' . $url . '" target="_blank"><i class="dejbrand-facebook"></i></a>' : '';
            $share_links .= (in_array('twitter', $links)) ? '<a class="DejavoCP-share-twitter" href="https://twitter.com/share?url=' . $url . '" target="_blank"><i class="dejbrand-twitter"></i></a>' : '';
            $share_links .= (in_array('pinterest', $links)) ? '<a class="DejavoCP-share-pinterest" href="https://pinterest.com/pin/create/button/?url=' . $url . '" target="_blank"><i class="dejbrand-pinterest"></i></a>' : '';
            $share_links .= (in_array('mail', $links)) ? '<a class="DejavoCP-share-mail" href="mailto:?body=' . $url . '" target="_blank"><i class="dej-envelope"></i></a>' : '';
            $share_links .= '</div>';
        }

        return $share_links;
    }


    public static function DejavoCP_get_count()
    {
        $products = [];
        $cookie = 'DejavoCP_products_' . md5('DejavoCP' . get_current_user_id());

        if (isset($_COOKIE[$cookie]) && !empty($_COOKIE[$cookie])) {
            $products = explode(',', sanitize_text_field($_COOKIE[$cookie]));
        }

        return count($products);
    }

    public static function DejavoCP_get_page_url()
    {
        $page_id = self::get_setting('page_id');
        $page_url = !empty($page_id) ? get_permalink($page_id) : '#';

        return esc_url($page_url);
    }

    public static function get_page_url()
    {
        return self::DejavoCP_get_page_url();
    }

    public static function get_url()
    {
        return self::DejavoCP_get_page_url();
    }

    public static function get_count()
    {
        return self::DejavoCP_get_count();
    }

    public static function get_settings()
    {
        return self::$settings;
    }

    public static function get_fields($context = '')
    {
        if ($context === 'quick_table') {
            $saved_fields6 = self::get_setting('quick_fields6');

            if (empty($saved_fields6)) {
                // get old data - before 6.0

                if (is_array(self::get_setting('quick_fields'))) {
                    $saved_fields = self::get_setting('quick_fields');
                } else {
                    $saved_fields = array_keys(self::$fields);
                }

                foreach ($saved_fields as $saved_field) {
                    if (!in_array($saved_field, [
                        'attributes',
                        'custom_attributes',
                        'custom_fields'
                    ])) {
                        $sk = self::generate_key(4, true);

                        $saved_fields6[$sk] = [
                            'type' => 'default',
                            'name' => $saved_field
                        ];
                    }
                }
            }
        } else {
            $saved_fields6 = self::get_setting('fields6');

            if (empty($saved_fields6)) {
                // get old data - before 6.0

                if (is_array(self::get_setting('fields'))) {
                    $saved_fields = self::get_setting('fields');
                } else {
                    $saved_fields = array_keys(self::$fields);
                }

                foreach ($saved_fields as $saved_field) {
                    if (!in_array($saved_field, [
                        'attributes',
                        'custom_attributes',
                        'custom_fields'
                    ])) {
                        $sk = self::generate_key(4, true);

                        $saved_fields6[$sk] = [
                            'type' => 'default',
                            'name' => $saved_field
                        ];
                    }
                }
            }
        }

        return $saved_fields6;
    }

    public static function get_setting($name, $default = false)
    {
        $settings = self::get_settings();

        if (!empty($settings)) {
            if (isset($settings[$name])) {
                $setting = $settings[$name];
            } else {
                $setting = $default;
            }
        } else {
            $setting = get_option('DejavoCP_' . $name, $default);
        }

        return $setting;
    }

    public static function generate_key($length = 6, $lower = false)
    {
        $key = '';
        $key_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $key_str_len = strlen($key_str);

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

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

        if ($lower) {
            $key = strtolower($key);
        }

        return $key;
    }
}
return DejavoCP::instance();
}