<?php

if (!defined('ABSPATH')) exit; //Exit if accessed directly

new SWAP_Metaboxes();

class SWAP_Metaboxes
{

    function __construct()
    {
        add_action('add_meta_boxes', array($this, 'swap_to_register_meta_boxes'));
        add_action('admin_enqueue_scripts', array($this, 'swap_to_scripts'), 100);
        add_action('save_post', array($this, 'swap_to_save'), 10, 3);
        add_action('wp_ajax_swap_curriculum', array($this, 'swap_search_posts'));
        add_action('wp_ajax_swap_curriculum_create_item', array($this, 'swap_curriculum_create_item'));

        add_action('wp_ajax_swap_save_questions', array($this, 'swap_save_questions'));
        add_action('wp_ajax_swap_save_title', array($this, 'swap_save_title'));
        add_action('wp_ajax_swap_get_image_url', 'SWAP_Metaboxes::get_image_url');

        add_filter('swap_multiselect_options_product_cat', 'SWAP_Metaboxes::product_cat_options');
        add_filter('swap_multiselect_options_product_category', 'SWAP_Metaboxes::product_category_options');
		add_filter('swap_multiselect_options_product_category', 'SWAP_Metaboxes::product_category_options');
    }

    public static function product_cat_options()
    {
        $r = array();
        $product_terms = get_terms(array(
            'taxonomy' => 'product_category',
            'hide_empty' => false,
        ));

        if (!empty($product_terms) and !is_wp_error($product_terms)) {
            foreach ($product_terms as $product_term) {
                $r[] = array(
                    'name' => $product_term->name,
                    'value' => $product_term->term_id,
                );
            }
        }

        return $r;
    }

    public static function product_accessories_options() {
        $r = array();

        $query_args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
          
        );

        $q = new WP_Query($query_args);

        if($q->have_posts()) {
            while($q->have_posts()) {
                $q->the_post();

                $r[] = array(
                    'name' => get_the_title(),
                    'value' => get_the_ID(),
                );

            }
        }

        return $r;
    }
	
	public static function product_category_options() {
    $r = array();
    $added_categories = array(); 
    $query_args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
    );

    $q = new WP_Query($query_args);

    if ($q->have_posts()) {
        while ($q->have_posts()) {
            $q->the_post();

            $categories = get_the_terms(get_the_ID(), 'product_category'); 

            if ($categories && !is_wp_error($categories)) {
                foreach ($categories as $category) {
                    
                    if (!in_array($category->term_id, $added_categories)) {
                        $r[] = array(
                            'name'  => $category->name,
                            'value' => $category->term_id,
                        );

                        
                        $added_categories[] = $category->term_id;
                    }
                }
            } 
        }
        wp_reset_postdata(); 
    }

    return $r;
}


    function boxes()
    {
        return apply_filters('swap_to_boxes', array(
            'swap_default_settings' => array(
                'post_type' => array('post', 'page'),
                'label' => esc_html__('Page Settings', 'swap_theme_options'),
            ),
            'swap_testimonials' => array(
                'post_type' => array('testimonials'),
                'label' => esc_html__('Testimonial Settings', 'swap_theme_options'),
            ),
          
            'swap_projects' => array(
                'post_type' => array('projects'),
                'label' => esc_html__('Projects Settings', 'swap_theme_options'),
            ),
            'swap_blog' => array(
                'post_type' => array('Blog'),
                'label' => esc_html__('Blog Settings', 'swap_theme_options'),
            ),
			 'swap_events' => array(
                'post_type' => array('events'),
                'label' => esc_html__('Event Settings', 'swap_theme_options'),
            ),
           'swap_userstories' => array(
                'post_type' => array('userstories'),
                'label' => esc_html__('Userstories Settings', 'swap_theme_options'),
            ),
            
        ));
    }

    function get_users()
    {
        $users = array(
            '' => esc_html__('Choose User', 'swap_theme_options')
        );

        if (!is_admin()) return $users;

        $users_data = get_users();
        foreach ($users_data as $user) {
            $users[$user->ID] = $user->data->user_nicename;
        }

        return $users;
    }

    function fields()
    {
        $single_product_style = 'style_1';
        $options = get_option( 'swap_to_settings', array() );
        if(!empty($options) && !empty($options['single_product_style'])) {
            $single_product_style = $options['single_product_style'];
        }

        return apply_filters('swap_to_fields', array(
            'swap_default_settings' => array(
                'page_settings' => array(
                    'name' => esc_html__('Page Settings', 'swap_theme_options'),
                    'fields' => array(
                        'page_color' => array(
                            'label' => esc_html__('Page Background color', 'swap_theme_options'),
                            'type' => 'color',
                        ),
                          'title_bg_image' => array(
                            'label' => esc_html__('Page Title Background Image', 'swap_theme_options'),
                            'type' => 'image',
                        ),
                     
                      
                    )
                ),
            ),

            'swap_testimonials' => array(
                'page_settings' => array(
                    'name' => esc_html__('Testimonial Settings', 'swap_theme_options'),
                    'fields' => array(
                        'author' => array(
                            'label' => esc_html__('Testimonial Author', 'swap_theme_options'),
                            'type' => 'text',
                        ),
                        'author_info' => array(
                            'label' => esc_html__('Testimonial Author Info', 'swap_theme_options'),
                            'type' => 'text',
                        ),
                                             
                    )
                ),
            ),

            'swap_blog' => array(
                'page_settings' => array(
                    'name' => esc_html__('Blog Settings', 'swap_theme_options'),
                    'fields' => array(
                          'page_color' => array(
                            'label' => esc_html__('Page Background color', 'swap_theme_options'),
                            'type' => 'color',
                        ),
                          'title_bg_image' => array(
                            'label' => esc_html__('Page Title Background Image', 'swap_theme_options'),
                            'type' => 'image',
                        ),
                       
                      
                    )
                ),
            ),
			  'swap_events' => array(
                'page_settings' => array(
                    'name' => esc_html__('Event Settings', 'swap_theme_options'),
                    'fields' => array(
                          'page_color' => array(
                            'label' => esc_html__('Page Background color', 'swap_theme_options'),
                            'type' => 'color',
                        ),
                          'title_bg_image' => array(
                            'label' => esc_html__('Page Title Background Image', 'swap_theme_options'),
                            'type' => 'image',
                        ),
                       
                      'event_category' => array(
                            'label' => esc_html__('Event Category Name', 'swap_theme_options'),
                            'type' => 'text',
                        ),
                    )
                ),
            ),
   'swap_events' => array(
                'page_settings' => array(
                    'name' => esc_html__('Event Settings', 'swap_theme_options'),
                    'fields' => array(
                          'page_color' => array(
                            'label' => esc_html__('Page Background color', 'swap_theme_options'),
                            'type' => 'color',
                        ),
                          'title_bg_image' => array(
                            'label' => esc_html__('Page Title Background Image', 'swap_theme_options'),
                            'type' => 'image',
                        ),
                       
                      'event_category' => array(
                            'label' => esc_html__('Event Category Name', 'swap_theme_options'),
                            'type' => 'text',
                        ),
                    )
                ),
            ),
   				'swap_userstories' => array(
                'page_settings' => array(
                    'name' => esc_html__('Userstories Settings', 'swap_theme_options'),
                    'fields' => array(
                          'page_color' => array(
                            'label' => esc_html__('Page Background color', 'swap_theme_options'),
                            'type' => 'color',
                        ),
                          'title_bg_image' => array(
                            'label' => esc_html__('Page Title Background Image', 'swap_theme_options'),
                            'type' => 'image',
                        ),
                       
                      'user_name' => array(
                            'label' => esc_html__('User Name', 'swap_theme_options'),
                            'type' => 'text',
                        ),
                    )
                ),
            ),
   

            'swap_projects' => array(
                'product_settings' => array(
                    'name' => esc_html__('Projects Settings', 'swap_theme_options'),
                    'fields' => array(
                            'page_color' => array(
                            'label' => esc_html__('Page Background color', 'swap_theme_options'),
                            'type' => 'color',
                        ),
                           'title_bg_image' => array(
                            'label' => esc_html__('Product Title Background Image', 'swap_theme_options'),
                            'type' => 'image',
                        ),
                        
                       'location_name' => array(
                            'label' => esc_html__('Location Name', 'swap_theme_options'),
                            'type' => 'text',
                        ),
                     
                    )
                ),
              
                
            ),
         

        ));
    }

    function get_fields($metaboxes)
    {
        $fields = array();
        foreach ($metaboxes as $metabox_name => $metabox) {
            foreach ($metabox as $section) {
                foreach ($section['fields'] as $field_name => $field) {
                    $sanitize = (!empty($field['sanitize'])) ? $field['sanitize'] : 'swap_to_save_field';
                    $fields[$field_name] = !empty($_POST[$field_name]) ? call_user_func(array($this, $sanitize), $_POST[$field_name], $field_name) : '';
                }
            }
        }

        return $fields;
    }

    function swap_to_save_field($value)
    {
        return $value;
    }

    function swap_to_save_number($value)
    {
        return intval($value);
    }

    function swap_to_save_dates($value, $field_name)
    {
        global $post_id;

        $dates = explode(',', $value);
        if (!empty($dates) and count($dates) > 1) {
            update_post_meta($post_id, $field_name . '_start', $dates[0]);
            update_post_meta($post_id, $field_name . '_end', $dates[1]);
        }

        return $value;
    }

    function swap_to_register_meta_boxes()
    {
        $boxes = $this->boxes();
        foreach ($boxes as $box_id => $box) {
            $box_name = $box['label'];
            add_meta_box($box_id, $box_name, array($this, 'swap_to_display_callback'), $box['post_type'], 'normal', 'high', $this->fields());
        }
    }

    function swap_to_display_callback($post, $metabox)
    {
        $meta = $this->convert_meta($post->ID);
        foreach ($metabox['args'] as $metabox_name => $metabox_data) {
            foreach ($metabox_data as $section_name => $section) {
                foreach ($section['fields'] as $field_name => $field) {
                    $default_value = (!empty($field['value'])) ? $field['value'] : '';
                    $value = (isset($meta[$field_name])) ? $meta[$field_name] : $default_value;
                    if (!empty($value)) {
                        switch ($field['type']) {
                            case 'dates' :
                                $value = explode(',', $value);
                                break;
                            case 'answers' :
                                $value = unserialize($value);
                                break;
                        }
                    }
                    $metabox['args'][$metabox_name][$section_name]['fields'][$field_name]['value'] = $value;
                }
            }
        }
        include SWAP_TO_DIR . '/post_type/metaboxes/metabox-display.php';
    }

    function convert_meta($post_id)
    {
        $meta = get_post_meta($post_id);
        $metas = array();
        foreach ($meta as $meta_name => $meta_value) {
            $metas[$meta_name] = $meta_value[0];
        }

        return $metas;
    }

    function swap_to_scripts($hook)
    {
        if($hook !== 'toplevel_page_dokan'){
            $v = time();
            $base = SWAP_TO_URL . '/post_type/metaboxes/assets/';
            wp_enqueue_media();
            wp_enqueue_script('jquery');
            wp_enqueue_script('vue.js', $base . 'js/vue.min.js', array('jquery'), $v);
            wp_enqueue_script('vue-resource.js', $base . 'js/vue-resource.min.js', array('vue.js'), $v);
            wp_enqueue_script('vue2-datepicker.js', $base . 'js/vue2-datepicker.min.js', array('vue.js'), $v);
            wp_enqueue_script('vue-select.js', $base . 'js/vue-select.js', array('vue.js'), $v);
            wp_enqueue_script('vue2-editor.js', $base . 'js/vue2-editor.min.js', array('vue.js'), $v);
            wp_enqueue_script('vue2-color.js', $base . 'js/vue-color.min.js', array('vue.js'), $v);
            wp_enqueue_script('sortable.js', $base . 'js/sortable.min.js', array('vue.js'), $v);
            wp_enqueue_script('vue-multiselect.js', $base . 'js/vue-multiselect.min.js', array('vue.js'), $v);
            wp_enqueue_script('vue-draggable.js', $base . 'js/vue-draggable.min.js', array('sortable.js'), $v);
            wp_enqueue_script('swap_to_mixins.js', $base . 'js/mixins.js', array('vue.js'), $v);
            wp_enqueue_script('swap_to_metaboxes.js', $base . 'js/metaboxes.js', array('vue.js'), $v);
            wp_enqueue_script('fonticonpicker', $base . 'js/jquery.fonticonpicker.min.js', array(), $v);

            wp_enqueue_style('vue-multiselect.css', $base . 'css/vue-multiselect.min.css', array(), $v);
            wp_enqueue_style('swap-to-metaboxes.css', $base . 'css/main.css', array(), $v);
            wp_enqueue_style('linear-icons', $base . 'css/linear-icons.css', array('swap-to-metaboxes.css'), $v);
            wp_enqueue_style('fonticonpicker', $base . 'css/jquery.fonticonpicker.min.css', array(), $v);
        }
    }

    function swap_to_post_types()
    {
        return apply_filters('swap_to_post_types', array(
            'page',
            'post',
            'projects',
            'testimonials',
            'blog',
			'events',
			'userstories'
           
        ));
    }

    function swap_to_save($post_id, $post)
    {

        $post_type = get_post_type($post_id);

        if (!in_array($post_type, $this->swap_to_post_types())) return;

        if(!empty($_POST) and !empty($_POST['action']) and $_POST['action'] === 'editpost') {

            $fields = $this->get_fields($this->fields());

            foreach ($fields as $field_name => $field_value) {
                update_post_meta($post_id, $field_name, $field_value);
            }
        }


    }

    function swap_search_posts()
    {
        $r = array();

        $args = array(
            'posts_per_page' => 10,
        );

        if (!empty($_GET['s'])) {
            $args['s'] = sanitize_text_field($_GET['s']);
        }

        if (!empty($_GET['post_types'])) {
            $args['post_type'] = explode(',', sanitize_text_field($_GET['post_types']));
        }

        if (!empty($_GET['ids'])) {
            $args['post__in'] = explode(',', sanitize_text_field($_GET['ids']));
        }

        if (!empty($_GET['exclude_ids'])) {
            $args['post__not_in'] = explode(',', sanitize_text_field($_GET['exclude_ids']));
        }

        if (!empty($_GET['orderby'])) {
            $args['orderby'] = sanitize_text_field($_GET['orderby']);
        }

        $q = new WP_Query($args);
        if ($q->have_posts()) {
            while ($q->have_posts()) {
                $q->the_post();

                $response = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title(),
                );

                if (in_array('swap-questions', $args['post_type'])) {
                    $response = array_merge($response, $this->question_fields($response['id']));
                }

                $r[] = $response;
            }

            wp_reset_postdata();
            wp_reset_query();
        }

        $insert_sections = array();
        foreach ($args['post__in'] as $key => $post) {
            if (!is_numeric($post)) {
                $insert_sections[$key] = array('id' => $post, 'title' => $post);
            }
        }

        foreach ($insert_sections as $position => $inserted) {
            array_splice($r, $position, 0, array($inserted));
        }

        wp_send_json($r);
    }

    function get_question_fields()
    {
        return array(
            'type' => array(
                'default' => 'single_choice',
            ),
            'answers' => array(
                'default' => array(),
            ),
            'question' => array(),
            'question_explanation' => array(),
            'question_hint' => array(),
        );
    }

    function question_fields($post_id)
    {
        $fields = $this->get_question_fields();
        $meta = array();

        foreach ($fields as $field_key => $field) {
            $meta[$field_key] = get_post_meta($post_id, $field_key, true);
            $default = (isset($field['default'])) ? $field['default'] : '';
            $meta[$field_key] = (!empty($meta[$field_key])) ? $meta[$field_key] : $default;
        }

        return $meta;
    }

    function swap_curriculum_create_item()
    {
        $r = array();
        $available_post_types = array('swap-lessons', 'swap-quizzes', 'swap-questions');

        if (!empty($_GET['post_type'])) $post_type = sanitize_text_field($_GET['post_type']);
        if (!empty($_GET['title'])) $title = sanitize_text_field($_GET['title']);

        /*Check if data passed*/
        if (empty($post_type) and empty($title)) return;

        /*Check if available post type*/
        if (!in_array($post_type, $available_post_types)) return;

        $item = array(
            'post_type' => $post_type,
            'post_title' => wp_strip_all_tags($title),
            'post_status' => 'publish',
        );

        $r['id'] = wp_insert_post($item);
        $r['title'] = get_the_title($r['id']);

        if ($post_type == 'swap-questions') {
            $r = array_merge($r, $this->question_fields($r['id']));
        }

        wp_send_json($r);

    }

    function swap_save_questions()
    {
        $r = array();
        $request_body = file_get_contents('php://input');

        if (!empty($request_body)) {

            $fields = $this->get_question_fields();


            $data = json_decode($request_body, true);

            foreach ($data as $question) {

                if (empty($question['id'])) continue;
                $post_id = $question['id'];

                foreach ($fields as $field_key => $field) {
                    if (!empty($question[$field_key])) {
                        $r[$field_key] = update_post_meta($post_id, $field_key, $question[$field_key]);
                    }
                }
            }
        }
        wp_send_json($r);
    }

    function swap_save_title()
    {
        if (empty($_GET['id']) and !empty($_GET['title'])) return false;

        $post = array(
            'ID' => intval($_GET['id']),
            'post_title' => sanitize_text_field($_GET['title']),
        );

        wp_update_post($post);

        wp_send_json($post);
    }

    public static function get_image_url()
    {
        if (empty($_GET['image_id'])) die;
        wp_send_json(wp_get_attachment_url(intval($_GET['image_id'])));
    }
}

function swap_to_metaboxes_deps($field, $section_name)
{
    $dependency = '';
    if (empty($field['dependency'])) return $dependency;

    $key = $field['dependency']['key'];
    $compare = $field['dependency']['value'];

    $compared_value = "data['{$section_name}']['fields']['{$key}']['value']";

    if ($compare === 'not_empty') {
        $dependency = "v-if=data['{$section_name}']['fields']['{$key}']['value']";
    } else {
        $dependency = "v-if=\"data['{$section_name}']['fields']['{$key}']['value'] === '{$compare}'\"";
    }

    return $dependency;
}
