<?php
if(!class_exists('nfpfilter_admin')){
    class nfpfilter_admin{
        private $basename = "WooCommerce Filter plus";
        private $shortname = "nfp";

        function __construct(){
            add_action('admin_enqueue_scripts', array($this,'nfpfilter_admin_scripts'));
            add_action('admin_menu', array($this,'filter_plus_add_admin'));
        }

        function nfpfilter_admin_scripts(){
            wp_enqueue_style('nfp_admin_style',NFP_URL.'admin/css/style.css');
            wp_register_script('nfp_admin_script',NFP_URL.'admin/js/admin.js');

            // Localize the script with new data
            $translation_array = array(
                'admin_uri' => admin_url().'admin.php?page=nfp-admin-panel.php',
                 'ajax_url' => admin_url( 'admin-ajax.php' )
            );
            wp_localize_script( 'nfp_admin_script', 'nfpVars', $translation_array );

            wp_enqueue_script( 'nfp_admin_script' );
        }


        /**
         * Creates the opening markup for each option.
         *
         * @param $value
         */

        private function create_opening_tag($value,$pre = false) {
            $group_class = $dependency_show  = $section_class =  $additional_attr = "";

            $section_class = "nfpfilter-section fix";
            if(isset($value['dependency'])){
                $dependency_show = get_option($value['dependency']['target_id']) === $value['dependency']['value'] ? "display:block" : "display: none";
                $section_class .= " is-dependent dependency-id-".$value['dependency']['target_id'];
                $additional_attr .= 'data-dependent-target="'.esc_attr($value['dependency']['target_id']).'" data-dependent-target-value="'.esc_attr($value['dependency']['value']).'"';
            }

            if (isset($value['grouping'])) {
                $group_class = "nfpfilter-grouping-rhs";
            }
            echo '<div '.($additional_attr).' style="'.esc_attr($dependency_show).'" class="'.esc_attr($section_class).'">'."\n";
            if ($group_class != "") {
                echo "<div class='esc_attr($group_class) fix'>\n";
            }
            if (isset($value['name'])) {
                $full_width_class = isset($value['full_width']) && $value['full_width'] == true ? 'full-width-content' : '';
                echo "<div class='nfpfilter-admin-left'><h3><label for='".esc_attr($value['id'])."'>" . esc_attr($value['name']) . "</h3></div><div class='nfpfilter-admin-right $full_width_class'>\n";
            }

            if (isset($value['note'])) {
                echo "<span class=\"note\">".esc_attr($value['note'])."</span><br />";
            }
        }


        /**
         * Creates the closing markup for each option.
         *
         * @param $value
         * @return void
         */
        private function create_closing_tag($value) {
            if (isset($value['desc'])) {
                echo '<div class="description">'.esc_html($value['desc']).'</div>';
            }
            if (isset($value['grouping'])) {
                echo "</div>\n";
            }
            //echo "</div><!-- suf-section -->\n";

            echo "</div><div style='clear: both;display: block'></div></div>\n";
        }

        function create_suf_header_3($value) {
            echo '<h3 class="nfpfilter-header-3">'.esc_html($value['name'])."</h3>\n";

        }


         /**
         * Creates the form.
         * @param $options
         */
        private function create_form($options) {

            if(!is_array($options)) return;
            $array_size = sizeof($options)-1;
            $headings = '';



            echo "<form id='nfpfilter_options_form' method='post' name='form'>\n";
            foreach ($options as $value) {

                switch ( $value['type'] ) {
                    case "heading":

                        $class = '';

                        if(empty($_GET['tab'])){
                         $class = ' active';
                         $_GET['tab'] = 'tab-nfp_basic';
                        }else{
                            $class = !empty($_GET['tab']) && $_GET['tab'] !== 'tab-'.$value['id'] ? '' : ' active ';
                        }

                        $headings .= '<li class="'.esc_attr($class).'">';
                        $headings .=  '<a href="#" data-target="tab-'.esc_attr($value['id']).'">'.esc_html($value['name']).'</a>';
                        $headings .= '</li>';

                        if($options[0]==$value){
                        echo '<div class="nfp-tab'.esc_attr($class).'" id="tab-'.esc_attr($value['id']).'">';
                        }else{
                            $class = !empty($_GET['tab']) && $_GET['tab'] == 'tab-'.esc_attr($value['id']) ? ' active' : '';
                            echo '</div><div class="nfp-tab'.esc_attr($class).'" id="tab-'.esc_attr($value['id']).'">';
                        }

                        break;

                    case "sub-section-3":
                        $this->create_suf_header_3($value);
                        break;

                    case "text";
                        $this->create_opening_tag($value);
                        $text = "";
                        $text = self::get_value($value);

                        echo '<input type="text" class="nfpfilter-admin-input" id="'.esc_attr($value['id']).'" name="'.esc_attr($value['id']).'" value="'.esc_attr($text).'" />'."\n";
                        $this->create_closing_tag($value);
                        break;
                        
                     case "button";
                        $this->create_opening_tag($value);
                        $text = "";

                        echo "<p><a id='".$value['id']."_btn' class='button'>".$value['label']."</a></p>";
                        echo '<div class="message"><span class="nfp-loading-spinner" style="display: none;"></span><span class="message-text"></span></div>';
                        $this->create_closing_tag($value);
                        break;   

                     case "text_increment";
                        $this->create_opening_tag($value);
                        $text = "";
                        if (get_option($value['id']) === false) {
                            $text = $value['std'];
                        }
                        else {
                            $text = get_option($value['id']);
                        }

                        echo '<div class="tax-holder">';
                        if(is_array($text)){
                            $counter = 0;
                            foreach($text as $single_text){
                                if(is_array($single_text)){
                                        echo '<p class="num-taxonomy">
                                        <input type="text" class="singular" placeholder="Singular name" name="'.esc_attr($value['id']).'['.$counter.'][singular]" value="'.esc_attr($single_text['singular']).'" />
                                        <input type="text" class="plural" placeholder="Plural name" name="'.esc_attr($value['id']).'['.$counter.'][plural]" value="'.esc_attr($single_text['plural']).'" />';
                                    echo '<button class="remove-text">-</button></p>'."\n";
                                }
                                 $counter ++;
                            }
                        }

                        echo '<p><button data-name="'.esc_attr($value['id']).'" class="button text-increment">'.esc_html__('Add','nfpfilter').'</button></p>';
                        echo '</div>';
                        $this->create_closing_tag($value);
                        break;

                    case "textarea":
                        $this->create_opening_tag($value);
                        echo '<textarea name="'.esc_attr($value['id']).'" id="'.esc_attr($value['id']).'" cols="90" rows="8" style="max-width: 100%">';
                        if ( get_option( $value['id'] ) != "") {
                           echo get_option( $value['id'] );
                       }
                       else {
                            echo $value['std'];
                        }
                        echo '</textarea>';
                        $this->create_closing_tag($value);
                        break;

                    case "checkbox":
                        $this->create_opening_tag($value);

                        $checked = self::get_value($value) == 'true' ? 'checked' : '';

                        echo '<input '.esc_attr($checked).' type="checkbox" class="nfpfilter-admin-input" id="'.esc_attr($value['id']).'" placeholder="enter your title" name="'.esc_attr($value['id']).'" value="true" />'."\n";
                        $this->create_closing_tag($value);
                        break;

                    case "radio":
                        $this->create_opening_tag($value);
                        foreach ($value['options'] as $option_value => $option_text) {
                            $checked = ' ';
                            if (get_option($value['id']) == $option_value) {
                                $checked = ' checked ';
                            }
                            else if (get_option($value['id']) === FALSE && $value['std'] == $option_value){
                                $checked = ' checked ';
                            }
                            else {
                                $checked = ' ';
                            }
                            echo '<div class="mnt-radio"><input type="radio" class="nfpfilter-admin-input" name="'.esc_attr($value['id']).'" value="'.
                                esc_attr($option_value).'" '.esc_attr($checked)."/>".esc_html($option_text)."</div>\n";
                        }
                        $this->create_closing_tag($value);
                        break;

                    case "select":
                         $this->create_opening_tag($value);
                         $option = self::get_value($value);
                        echo '<select name="'.esc_attr($value['id']).'" class="nfp-select2" id="'.esc_attr($value['id']).'" >'."\n";
                        echo "<option>".esc_html__('Select option','nfpfilter')."</option>\n";
                        foreach ($value['options'] as $option_value => $option_list) {
                            $checked = " ";
                            if ($option === $option_value) {
                                $checked = "selected";
                            }
                            echo "<option ".esc_attr($checked)." value='".esc_attr($option_value)."'>".esc_attr($option_list)."</option>\n";
                        }
                        echo "</select>\n";
                        $this->create_closing_tag($value);
                        break;

                        case "custom_shortcode_page":
                         $this->create_opening_tag($value);
                         ?>
<table style="width: 100%">
<tr>
<td colspan="3">
<?php esc_html_e("Shortcode: ",""); ?>
<code>
<?php echo esc_html("[nfpfilter_products]"); ?>

</code>
</td>
</tr>
<tr>
<td style="width: 200px;"><strong><?php esc_html_e("Params","nfpfilter"); ?></strong></td>
<td style="width: 200px;"><strong><?php esc_html_e("Default","nfpfilter"); ?></strong></td>
<td><strong><?php esc_html_e("Description","nfpfilter"); ?></strong></td>
</tr>
<tr>
<td><?php echo esc_html("per_page_dropdown"); ?></td>
<td><?php echo esc_html("NIL"); ?></td>
<td><?php esc_html_e("Insert comma seperated options for show per page dropdown. Code Sample ","nfpfilter"); ?><code>per_page_dropdown="10,20,30"</code><?php esc_html_e(". Don't use this param if you want to hide per page dropdown","nfpfilter"); ?></td>
</tr>

<tr>
<td><?php echo esc_html("per_page"); ?></td>
<td><?php echo esc_html("12"); ?></td>
<td><?php esc_html_e("Insert default product to show per page. Code Sample ","nfpfilter"); ?><code>per_page="15"</code></td>
</tr>

<tr>
<td><?php echo esc_html("orderby"); ?></td>
<td><?php echo esc_html("date"); ?></td>
<td><?php esc_html_e("Insert option for orderby. Available options are popularity, rating, date, price, price-desc. Code Sample ","nfpfilter"); ?><code><?php echo esc_html('orderby="price-desc'); ?></code></td>
</tr>

<tr>
<td><?php echo esc_html("columns"); ?></td>
<td><?php echo esc_html("3"); ?></td>
<td><?php esc_html_e("Insert column number for products. Code Sample ","nfpfilter"); ?><code><?php echo esc_html('columns="4'); ?></code></td>
</tr>

<tr>
<td><?php echo esc_html("sorting"); ?></td>
<td><?php echo esc_html("yes"); ?></td>
<td><?php esc_html_e("Show/hide sorting dropdown. Code Sample ","nfpfilter"); ?><code><?php echo esc_html('sorting="yes'); ?></code></td>
</tr>

<tr>
<td><?php echo esc_html("result_count"); ?></td>
<td><?php echo esc_html("yes"); ?></td>
<td><?php esc_html_e("Show/hide result count. Code Sample ","nfpfilter"); ?><code><?php echo esc_html('result_count="yes'); ?></code></td>
</tr>
</table>

<table style="width: 100%">
<tr>
<td colspan="3">
<?php esc_html_e("Shortcode: ","nfpfilter"); ?>
<code>
<?php echo esc_html("[nfpfilter_toggle_sidebar]"); ?>

</code>
</td>
</tr>
<tr>
<td style="width: 200px;"><strong><?php esc_html_e("Params","nfpfilter"); ?></strong></td>
<td style="width: 200px;"><strong><?php esc_html_e("Default","nfpfilter"); ?></strong></td>
<td><strong><?php esc_html_e("Description","nfpfilter"); ?></strong></td>
</tr>
<tr>
<td><?php echo esc_html("sidebar_id"); ?></td>
<td><?php esc_html_e("NIL","nfpfilter"); ?></td>
<td>
<?php esc_html_e("Insert sidebar id to show it in a page/post. Currently available ids are ","nfpfilter");
            global $wp_registered_sidebars;
            if(is_array($wp_registered_sidebars)){
            foreach($wp_registered_sidebars as $wp_registered_sidebar){
                echo '<code>'.$wp_registered_sidebar['id'].'</code>'.'&nbsp;';
            }
            }

            ?>
</td>
</tr>

<tr>
<td><?php echo esc_html("sidebar_style"); ?></td>
<td><?php echo esc_html("widget_and_button"); ?></td>
<td><?php esc_html_e('Choose style from "widget_and_button" , "hidden_widget_and_button" , "widget_only" and "absolute_widget_and_button". Code Sample ','nfpfilter'); ?><code><?php echo esc_html('sidebar_style="widget_and_button"'); ?></code></td>
</tr>
<tr>
<td><?php echo esc_html("button_float"); ?></td>
<td><?php echo esc_html("right"); ?></td>
<td><?php esc_html_e('Choose button float from left and right. Code Sample ','nfpfilter'); ?><code><?php echo esc_html('button_float="left"'); ?></code></td>
</tr>
</table>

<table style="width: 100%">
<tr>
<td>
<?php esc_html_e("Shortcode: ","nfpfilter"); ?>
<code>
<?php echo esc_html("[nfpfilter_toggle_button]"); ?>
</code>
<br>
<?php esc_html_e("It display toggle button. ","nfpfilter"); ?>
</td>
</tr>
</table>
<?php esc_html_e("To insert any shortcode inside a template file use do_shortcode() finction. Code example ","nfpfilter"); ?><code><?php echo esc_html("<?php echo do_shortcode([nfpfilter_toggle_button]); ?>"); ?></code>

                         <?php

                        $this->create_closing_tag($value);
                        break;
                }
            }
            if($options[$array_size]== $value){
                    echo '</div>'; // end of tab group
                 }
            ?>
            <div class="savebox">
                <input name="save" type="submit" value="Save" class="button button-primary" onclick="submit_form(this, document.forms['form'])" />
             </div>
            <input type="hidden" name="formaction" value="default" />
            <ul class="nfp-admin-menu">
               <?php echo $headings; ?>
            </ul>

         <script>
         function submit_form(element, form){
                    form['formaction'].value = element.name;
                     form.submit();
                 }

         </script>
         </form>
        <?php
        }

        function get_value($value){
            if (get_option($value['id']) === false) {
                $option = $value['std'];
            }
            else {
                $option = get_option($value['id']);
            }
            return $option;
        }

        public function filter_plus_add_admin() {
            add_menu_page(__("Filter plus","nfpfilter"),  __("Filter plus","nfpfilter"), 'manage_options', basename(__FILE__), array($this,'filter_plus_admin'));

            $options = $this->get_options();

            if ( isset($_GET['page']) && $_GET['page'] == basename(__FILE__) ) {
                if ( isset($_REQUEST['formaction']) && 'save' == $_REQUEST['formaction'] ) {
                    foreach ($options as $value) {
                        if( isset( $_REQUEST[ $value['id'] ] ) ) {
                            if(is_string($_REQUEST[ $value['id']])){
                                update_option( $value['id'], stripslashes ($_REQUEST[ $value['id'] ])  );
                            }else{
                                update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
                            }
                        }
                        else {
                            delete_option( $value['id'] );
                        }
                    }
                    $custom_js = 'jQuery(document).ready(function($){'.get_option('nfp_ajax_refresh').'});';
                    $custom_css = get_option('nfp_custom_css');
                    do_action('nfpfilter_push_scripts',$custom_js);
                    do_action('nfpfilter_push_scripts',$custom_css, 'css');
                }
            }
        }


        function filter_plus_admin() {
                if (isset($_REQUEST['saved']) && $_REQUEST['saved']) {
                    echo '<div id="message" class="updated fade"><p><strong>'.esc_html($this->basename).esc_html__('settings saved for this page','nfpfilter').'</strong></p></div>';
                }
                if (isset($_REQUEST['reset_all']) && $_REQUEST['reset_all']) {
                    echo '<div id="message" class="updated fade"><p><strong>'.esc_html($this->basename).esc_html__(' settings reset','nfpfilter').'</strong></p></div>';
                }
                ?>
                <div class="wrap">
                    <h1> <?php echo $this->basename; ?> <?php esc_html_e('settings','nfpfilter') ?></h1>
                    <div class="nfp-options">
                        <?php
                        $this->create_form($this->get_options());
                        ?>
                    </div><!-- mnt-options -->
                </div><!-- wrap -->
<?php
        } // end function filter_plus_admin()

        function get_options(){
            global $wp_registered_sidebars;
            $sidebars = array();
            foreach($wp_registered_sidebars as $wp_registered_sidebar){
                $sidebars[$wp_registered_sidebar['id']] = $wp_registered_sidebar['name'];
            }

            $options = array(
                array(
                    "name" => esc_html__("Archive settings","nfpfilter"),
                    "type" => "heading",
                    "id" => $this->shortname."_basic",
                    "std" => "",

                ),
                 array(
                    "name" => esc_html__("Insert sidebar into archive pages","nfpfilter"),
                    "type" => "checkbox",
                    "id" => $this->shortname."_insert_sidebar",
                    "std" => "",
                     "desc" => esc_html__("Check if you want the plugin to include a sidebar into product archive pages. This option is useful when you do not have a sidebar on archive pages. You can skip/uncheck this option if you do not want filter widgets on archive pages or you have a sidebar that you that you want to use for widgets.","nfpfilter")
                ),
                 array(
                    "name" => esc_html__("Select sidebar for archive pages","nfpfilter"),
                    "type" => "select",
                    "category" => "body-styles",
                    "id" => $this->shortname."_sidebar_archives",
                    "std" => "",
                    "options" => $sidebars,
                    "dependency" => array(
                        "target_id" => $this->shortname."_insert_sidebar",
                        "value" => "true"
                    ),
                ),
                 array(
                    "name" => esc_html__("Select a place to insert toggle button","nfpfilter"),
                    "type" => "select",
                    "category" => "body-styles",
                    "id" => $this->shortname."_toogle_position",
                    "std" => "always_show",
                    "options" => array(
                        "before_breadcrumb" => esc_html__("Before woocommerce breadcrumb","nfpfilter"),
                        "left_after_archive_description" => esc_html__("Left side after archive description","nfpfilter"),
                        "right_after_archive_description" => esc_html__("Right side after archive description","nfpfilter"),
                    ),
                    "dependency" => array(
                        "target_id" => $this->shortname."_insert_sidebar",
                        "value" => "true"
                    ),
                 ),
                  array(
                    "name" => esc_html__("Select archive sidebar style","nfpfilter"),
                    "type" => "select",
                    "category" => "body-styles",
                    "id" => $this->shortname."_sidebar_style",
                    "std" => "always_show",
                    "options" => array(
                        "show_widgets" => esc_html__("Show widgets","nfpfilter"),
                        "hide_widgets" => esc_html__("Hide widgets","nfpfilter"),
                        "absolute" => esc_html__("Absolute positioned widgets","nfpfilter"),
                    ),
                    "dependency" => array(
                        "target_id" => $this->shortname."_insert_sidebar",
                        "value" => "true"
                    ),
                 ),
                  array(
                    "name" => esc_html__("Default items per page","nfpfilter"),
                    "type" => "text",
                    "id" => $this->shortname."_default_per_page",
                    "std" => "12",
                ),
                  array(
                    "name" => esc_html__("Insert product per page downdown","nfpfilter"),
                    "type" => "text",
                    "id" => $this->shortname."_insert_perpage_options",
                    "std" => "10,20,30",
                    "desc" => esc_html__("Insert comma separated options for product per page dropdown. Keep blank to not to include. eg. 10,20,30","nfpfilter")
                ),
                  array(
                    "name" => esc_html__("Show out of stock badge","nfpfilter"),
                    "type" => "checkbox",
                    "id" => $this->shortname."_exclude_stockout_products",
                    "std" => "",
                ),
                 array(
                    "name" =>  esc_html__("Taxonomies","nfpfilter"),
                    "type" => "heading",
                    "id" => $this->shortname."_taxonomy",
                    "std" => "",

                ),
                  array("name" => esc_html__("Product taxonomies","nfpfilter"),
                    "desc" => "",
                    "id" => $this->shortname."_taxonomies",
                    "type" => "text_increment",
                    "parent" => "header-styles",
                     "desc" => esc_html__('Insert your required extra taxonomy for the filter purpose. You can as many taxonomy as you want. For example you want to add brands taxonomy. You can use "Brand" as singular name (without quotation) and "Brands" as plural name (without quotation)',"nfpfilter"),
                    "std" => ""),
                 array(
                    "name" =>  esc_html__("Advanced","nfpfilter"),
                    "type" => "heading",
                    "id" => $this->shortname."_ajax",
                    "std" => ""
                ),
                 array(
                    "name" => esc_html__("Enable ajax loading on filter","nfpfilter"),
                    "type" => "checkbox",
                    "id" => $this->shortname."_ajax_loading",
                    "std" => "true"
                 ),
            /*    array(
                    "name" => esc_html__("Custom wrap selector","nfpfilter"),
                    "type" => "text",
                    "id" => $this->shortname."_custom_wrap",
                    "std" => ""
                 ),*/
                 array(
                    "name" => esc_html__("Run a custom script on ajax load","nfpfilter"),
                    "type" => "textarea",
                    "id" => $this->shortname."_ajax_refresh",
                    "std" => ""
                 ),
                  array(
                    "name" => esc_html__("Custom css to override default css","nfpfilter"),
                    "type" => "textarea",
                    "id" => $this->shortname."_custom_css",
                    "std" => ""
                 ),
 				array(
                    "name" => esc_html__("Custom products class","nfpfilter"),
                    "type" => "text",
                    "id" => $this->shortname."_products_class",
                    "std" => "",
                    "desc" => esc_html__('This will override the class "products" for ajax purpose. Normally products parent should have a class like "products". However, some themes tend to change default classes. If you know your theme do so, you can override the class according to your theme, so this plugin can do ajax things properly.','nfpfilter'),
                 ),
                 array(
                    "name" => esc_html__("Custom pagination class","nfpfilter"),
                    "type" => "text",
                    "id" => $this->shortname."_pagination_class",
                    "std" => "",
                    "desc" => esc_html__('Update this according to your theme if it uses a custom pagination class','nfpfilter'),
                 ),
                 array(
                    "name" =>  esc_html__("Shortcodes","nfpfilter"),
                    "type" => "heading",
                    "id" => $this->shortname."_shortcodes",
                    "std" => ""
                ),
                array(
                    "name" =>  '',
                    "type" => "custom_shortcode_page",
                    "id" => $this->shortname."_custom_shortcode_page",
                    "full_width" => true
                ),
                  array(
                    "name" =>  esc_html__("Tools","nfpfilter"),
                    "type" => "heading",
                    "id" => $this->shortname."_tools",
                    "std" => ""
                ),
                array(
                    "name" =>  esc_html__("Setup discount rates for products","nfpfilter"),
                    "type" => "button",
                    "label" => "Run",
                    "id" => $this->shortname."_discount_filter_tool",
                    "desc" => esc_html__("This is a one time setup required when you first install the plugin. This setup will let the plugin function the discount filter. You can run this anytime but twice setup is not required.","nfpfilter"),
                ),
            );
            return $options;
        }

    }
    new nfpfilter_admin;
}



?>