<?php


class Woo_Import_Export
{


    /**
     * Woo_Import_Export constructor.
     */
    public function __construct()
    {

        global $wpdb;



        add_action('wp_ajax_woie_export_posts_data', array($this, 'woie_export_posts_data'));
        add_action('wp_ajax_woie_import_posts_data_file', array($this, 'woie_import_posts_data_file'));
        add_action('wp_ajax_woie_import_posts_data', array($this, 'woie_import_posts_data'));







    }

    public function woie_import_posts_data_file(){

        $result_array = array(
            'status' => false,
            'insert_count' => 0,
            'skip_count' => 0,
            'skip_data' => array(),
            'insert_data' => array(),
        );


        if(!empty($_FILES) && isset($_FILES['woie_import_file_txt'])){

            if(!isset($_POST['woie_import_nonce']) || !wp_verify_nonce($_POST['woie_import_nonce'], 'woie_import_file_action')){

                wp_die(__('Sorry, your nonce did not verify.', 'woo-ie'));


            }else{


                $woie_import_string = sanitize_woie_data(file_get_contents($_FILES['woie_import_file_txt']['tmp_name']));

                $result_array = $this->woie_import_data_from_txt($woie_import_string);




            }
        }

        wp_send_json($result_array);

    }


    public function woie_get_term_by_slug_or_name($name , $slug , $tax){

        global $wpdb;

        if(!$name && !$slug){

            return false;

        }

        $name = sanitize_woie_data($name);
        $slug = sanitize_woie_data($slug);
        $tax = sanitize_woie_data($tax);



        $query = "SELECT $wpdb->terms.slug FROM $wpdb->terms LEFT JOIN $wpdb->term_taxonomy wtt on $wpdb->terms.term_id = wtt.term_id
                    WHERE ($wpdb->terms.name = '$name' OR $wpdb->terms.slug = '$slug') AND wtt.taxonomy = '$tax'";


        return $wpdb->get_var($query);
    }


    public function woie_get_terms_by_post($post_id, $all_terms){

        global $wpdb;

        if(!$post_id || empty($all_terms)){
            return array();
        }

        $post_id = sanitize_woie_data($post_id);

        $terms_query = "SELECT wtt.term_id FROM $wpdb->term_relationships LEFT JOIN $wpdb->term_taxonomy wtt on $wpdb->term_relationships.term_taxonomy_id = wtt.term_taxonomy_id where object_id = $post_id";

        $terms_against_id = $wpdb->get_results($terms_query);

        $terms_array = array_map(function($term_obj){
            return $term_obj->term_id;
        }, $terms_against_id);

        $current_id_terms = array_filter($all_terms, function($object) use($terms_array){

            return in_array($object->term_id, $terms_array);

        });

        return $current_id_terms;

    }


    public function woie_is_post_exist($post_title, $post_name){

        global $wpdb;

        $query = "SELECT ID FROM $wpdb->posts WHERE post_title = '$post_title' AND post_name = '$post_name'";
        $result = $wpdb->get_var($query);

        return $result > 0;

    }

    public function woie_import_data_from_txt($woie_import_string){

        $result_array = array(
            'status' => false,
            'insert_count' => 0,
            'skip_count' => 0,
            'skip_data' => array(),
            'insert_data' => array(),
        );

        $woie_import_json = base64_decode($woie_import_string);
        $woie_import_array = json_decode($woie_import_json, true);


        if(isset($woie_import_array['posts']) && isset($woie_import_array['post_meta'])){

            $woie_posts = $woie_import_array['posts'];
            $woie_post_meta = $woie_import_array['post_meta'];
            $woie_post_terms = $woie_import_array['post_terms'];
            $woie_post_id_meta = array();
            $woie_post_meta_count = array();

            if(!empty($woie_post_meta)){
                foreach ($woie_post_meta as $single_meta){

                    $woie_post_id_meta[$single_meta['post_id']][] = array(
                        'meta_id' => $single_meta['meta_id'],
                        'meta_key' => $single_meta['meta_key'],
                        'meta_value' => $single_meta['meta_value']

                    );

                    $woie_post_meta_count[$single_meta['meta_key']] = isset($woie_post_meta_count[$single_meta['meta_key']]) ? ($woie_post_meta_count[$single_meta['meta_key']]+1) : 1;


                }
            }


            if(!empty($woie_posts)){

                $skip_posts = array();
                $insert_posts = array();

                foreach ($woie_posts as $index => $post){

                    $current_post_id = $post['ID'];

                    $is_post_exist = $this->woie_is_post_exist($post['post_title'], $post['post_name']);


                    if(!$is_post_exist){

                        unset($post['ID']);
                        $new_post_id = wp_insert_post($post);

                        if(is_int($new_post_id)){

                            $current_post_meta = $woie_post_id_meta[$current_post_id];
                            $current_post_terms = array_key_exists($current_post_id, $woie_post_terms) ? $woie_post_terms[$current_post_id] : array() ;


                            if(!empty($current_post_terms)){

                                foreach ($current_post_terms as $term_index => $term_array){


                                    $term_name = $term_array['name'];
                                    $term_slug = $term_array['slug'];
                                    $term_taxonomy = $term_array['taxonomy'];



                                    $term_slug_current = $this->woie_get_term_by_slug_or_name($term_name, $term_slug, $term_taxonomy);



                                    if($term_slug_current){
                                        wp_set_object_terms($new_post_id, $term_slug_current, $term_taxonomy, true);

                                    }else{

                                        wp_set_object_terms($new_post_id, $term_name, $term_taxonomy, true);

                                    }

                                }

                            }




                            $update_meta_key = array();



                            if(!empty($current_post_meta)){
                                foreach ($current_post_meta as $meta_index => $meta_array){
                                    $meta_value = maybe_unserialize($meta_array['meta_value']);
                                    if(!in_array($meta_array['meta_key'], $update_meta_key)){


                                        update_post_meta($new_post_id, $meta_array['meta_key'], $meta_value);

                                    }else{

                                        add_post_meta($new_post_id, $meta_array['meta_key'], $meta_value);

                                    }

                                    $update_meta_key[] = $meta_array['meta_key'];

                                }


                            }

                            $insert_posts[] = $post['post_title'];


                        }




                    }else{


                        $skip_posts[] = $post['post_title'];

                    }




                }



                $skip_count = count($skip_posts);
                $insert_count= count($insert_posts);

                $result_array['status'] = true;
                $result_array['alert_string'] = _n("$skip_count post is skipped and ", "$skip_count posts are skipped and ", $skip_count, 'woo-ie' );
                $result_array['alert_string'] .= _n("$insert_count new post is inserted", "$insert_count new posts are inserted.", $insert_count, 'woo-ie' );
                $result_array['skip_data'] = $skip_posts;
                $result_array['skip_count'] = $skip_count;
                $result_array['insert_count'] = $insert_count;
                $result_array['insert_data'] = $insert_posts;
            }



        }


        return $result_array;

    }


    public function woie_import_posts_data(){


        $result_array = array(
            'status' => false,
            'insert_count' => 0,
            'skip_count' => 0,
            'skip_data' => array(),
            'insert_data' => array(),
        );


        if(!empty($_POST) && isset($_POST['woie_import_string'])){

            if(!isset($_POST['woie_nonce']) || !wp_verify_nonce($_POST['woie_nonce'], 'woie_update_options_nonce')){

                wp_die(__('Sorry, your nonce did not verify.', 'woo-ie'));


            }else{


                $woie_import_string = sanitize_woie_data($_POST['woie_import_string']);

                $result_array = $this->woie_import_data_from_txt($woie_import_string);




            }
        }

        wp_send_json($result_array);

    }

    public function woie_settings_free($woie_settings_obj){

       $woie_args_obj = $woie_settings_obj['args'];

       $woie_args_obj['numberposts'] = -1;

        return $woie_args_obj;

    }

    public function woie_export_posts_data(){

        global $wpdb, $woie_dir, $woie_url, $post_terms;

        $result_array = array(
            'status' => false,
            'data' => '',
            'file_link' => ''
        );
        if(!empty($_POST) && isset($_POST['woie_settings_obj'])){

            if(!isset($_POST['woie_nonce']) || !wp_verify_nonce($_POST['woie_nonce'], 'woie_update_options_nonce')){

                wp_die(__('Sorry, your nonce did not verify.', 'woo-ie'));


            }else{


                $woie_settings_obj = sanitize_woie_data($_POST['woie_settings_obj']);
				
				//pree($woie_settings_obj);exit;
				
				update_option('_woie_settings_obj', $woie_settings_obj);

                if(function_exists('woie_settings_pro')){

                    $woie_args_obj = woie_settings_pro($woie_settings_obj);

                }else{

                    $woie_args_obj = $this->woie_settings_free($woie_settings_obj);

                }
				
				//pree($woie_args_obj);exit;

                $all_posts = get_posts($woie_args_obj);
				
                $all_available_terms = get_terms();

                $all_post_ids = array_map(function($single_post) use($all_available_terms){

                    global $post_terms;

                    $current_post_terms = $this->woie_get_terms_by_post($single_post->ID, $all_available_terms);

                    if(!empty($current_post_terms)){

                        $post_terms[$single_post->ID] = $current_post_terms;

                    }


                    return $single_post->ID;

                }, $all_posts);

                $all_post_ids_str = implode(', ', $all_post_ids);

                $get_meta = "SELECT * FROM $wpdb->postmeta WHERE post_id IN ($all_post_ids_str)";
                $meta_results = $wpdb->get_results($get_meta);

                $data_array = array(

                    'posts' => $all_posts,
                    'post_meta' => $meta_results,
                    'post_terms' => $post_terms,
					//'ids' => $all_post_ids_str

                );
				//$newobj = new clasABC;
				//$data_array = $newobj->update_data_array($data_array);

                $data_json = json_encode($data_array);
                $data_64 = base64_encode($data_json);

                $result_array['status'] = true;


                if($woie_settings_obj['type'] == 'file'){

                    $file_name = '/temp/backup_'.time().'.txt';
                    $file_link = $woie_url.$file_name;

                    $file_path = $woie_dir.$file_name;
                    if(file_exists($woie_dir.'/temp')){

                        file_put_contents($file_path, $data_64);

                    }else{

                        mkdir($woie_dir.'/temp');
                        file_put_contents($file_path, $data_64);

                    }

                    $result_array['file_link'] = $file_link;

                }else{

                    $result_array['data'] = $data_64;



                }





            }



        }


        wp_send_json($result_array);

    }


}