<?php
require get_template_directory().'/search/results_thumbnailgrid.php';
// searches for project titles and shows project titles and thumbnails

class LaySearch{

	public function __construct(){
        // save_post filter is triggered when saving projects, pages, lay_news, pages (all post types)
		add_action( 'save_post', array($this, 'search_save_post'), 10, 2 );

        // https://woocommerce.com/document/installed-taxonomies-post-types/
        // https://developer.wordpress.org/reference/hooks/edited_taxonomy/
		// update when tag was edited for projects
		add_action( 'edited_post_tag', array($this, 'search_save_post'), 10, 2 );
		add_action( 'delete_post_tag', array($this, 'search_save_post'), 10, 2 );
        add_action( 'edited_category', array($this, 'search_save_post'), 10, 2 );
		add_action( 'delete_category', array($this, 'search_save_post'), 10, 2 );
        // update when tag was edited for products
		add_action( 'edited_product_tag', array($this, 'search_save_post'), 10, 2 );
		add_action( 'delete_product_tag', array($this, 'search_save_post'), 10, 2 );
        add_action( 'edited_product_cat', array($this, 'search_save_post'), 10, 2 );
		add_action( 'delete_product_cat', array($this, 'search_save_post'), 10, 2 );
        // news categories
        add_action( 'edited_lay_news_category', array($this, 'search_save_post'), 10, 2 );
		add_action( 'delete_lay_news_category', array($this, 'search_save_post'), 10, 2 );

        // trash for projects
		add_action( 'delete_post', array($this, 'search_delete_post'), 10, 2 );
		add_action( 'trash_post', array($this, 'search_delete_post'), 10, 2 );
        // trash for products
        add_action( 'delete_product', array($this, 'search_delete_post'), 10, 2 );
		add_action( 'trash_product', array($this, 'search_delete_post'), 10, 2 );
        // trash for news
        add_action( 'delete_lay_news', array($this, 'search_delete_post'), 10, 2 );
		add_action( 'trash_lay_news', array($this, 'search_delete_post'), 10, 2 );

		add_filter( 'rest_cache_skip', array($this, 'skip_search_endpoint'), 10, 4 );
        add_action( 'rest_api_init', array($this, 'add_search_route') );
        
        add_action( 'wp_ajax_get_search_result', array( $this, 'get_search_result_thumbnailgrid' ) );
        add_action( 'wp_ajax_nopriv_get_search_result', array( $this, 'get_search_result_thumbnailgrid' ) );
    }
    
    public static function get_search_result_thumbnailgrid(){
        // an array of post ids
        $found_posts = $_POST['found_posts'];
        $found_posts = json_decode($found_posts, true);

        $config = array(
            'desktop' => array('colCount' => 4, 'colGutter' => 2, 'rowGutter' => 1),
            'tablet' => array('colCount' => 3, 'colGutter' => 3, 'rowGutter' => 3),
            'phone' => array('colCount' => 1, 'colGutter' => 5, 'rowGutter' => 5),
            'layoutType' => "masonry",
            'postids' => $found_posts
        );

        // of course i dont need to wrap config in an $el array, but:
        // i mimick gridder json structure, this way i won't have to rewrite results_thumbnailgrid.php to be too different from thumbnailgrid.php
        // this is just more of an ease to use thing
        $el = array('config' => $config);
        $thumbnailgrid = new LaySearch_Thumbnailgrid($el);
        $markup = $thumbnailgrid->getMarkup();
        echo $markup;
        wp_die();
    }
	
	public static function add_search_route(){
		register_rest_route( 'laytheme', '/search/', array(
			'methods' => 'GET',
            'callback' => 'LaySearch::getSearchPostArray',
            'permission_callback' => '__return_true'
		) );
	}

	public static function skip_search_endpoint( $WP_DEBUG, $request_uri, $server, $request ){
		if ( strpos($request_uri, '/laytheme/search/') !== false ){
			return true;
		}
		return false;
	}

	public static function search_save_post( ) {
        $newsActive = get_option('misc_options_activate_news_feature', '') == 'on' ? true : false;
        $wcActive = class_exists( 'WooCommerce' );
        $post_types_to_query = array('post');
        if( $newsActive ) {
            $post_types_to_query []= 'lay_news';
        }
        if($wcActive) {
            $post_types_to_query []= 'product';
        }
		$searchPostArray = array();
		$posts = get_posts(
            array(
                'post_type' => $post_types_to_query,
                'numberposts' => -1,
                'post_status' => 'publish'
            )
        );

		if ( $posts ) {
			foreach ( $posts as $post ) {
                $cats = array();
                switch( $post->post_type ) {
                    case 'product':
                        if( class_exists( 'WooCommerce' ) ) {
                            $cats = wp_get_object_terms($post->ID, 'product_cat', array( 'fields' => 'names' ));
                        }
                    break;
                    case 'lay_news':
                        $cats = wp_get_object_terms($post->ID, 'lay_news_category', array( 'fields' => 'names' ));
                    break;
                    case 'post':
                        $cats = wp_get_post_categories($post->ID, array( 'fields' => 'names' ));
                    break; 
                }

                $descr = '';
                switch( $post->post_type ) {
                    case 'product':
                        if( class_exists( 'WooCommerce' ) ) {
                            $descr = get_the_excerpt($post->ID);
                        }
                    break;
                    case 'lay_news':
                        // news dont have descr
                    break;
                    case 'post':
                        $descr = get_post_meta( $post->ID, 'lay_project_description', true );
                    break; 
                }
                $descr = wp_strip_all_tags($descr);

                $tags = array();
                switch( $post->post_type ) {
                    case 'product':
                        if( class_exists( 'WooCommerce' ) ) {
                            $tags = wp_get_object_terms($post->ID, 'product_tag');
                        }
                    break;
                    case 'lay_news':
                        // news dont have tags
                    break;
                    case 'post':
                        $tags = get_the_tags($post->ID);
                    break; 
                }
                $tagArray = array();
                if (is_array($tags) && $tags) {
					usort($tags, function($a, $b) {
						return $a->term_order - $b->term_order;
					});
					foreach($tags as $tag) {
						$tagArray []= $tag->name;
					}
                }

                array_push($searchPostArray, array(
                    'cats' => $cats,
                    'tags' => $tagArray,
                    'descr' => $descr,
                    'postid' => $post->ID,
                    'title' => get_the_title($post->ID),
					'slug' => $post->post_name,
				));
			}
		}

		update_option( 'lay-search-post-array', $searchPostArray);
	}

	public static function search_delete_post( $post_id ) {

		$searchPostArray = get_option( 'lay-search-post-array' );
		$needUpdate = false;
		if ( $searchPostArray == false ) {
			LaySearch::search_save_post($post_id);
		}
		
		if( is_array($searchPostArray) ) {
			for ($i = 0; $i < count($searchPostArray); $i++) {
				if ($searchPostArray[$i]['postid'] == $post_id) {
					$needUpdate = true;
					array_splice($searchPostArray, $i, 1);
					break;
				}
			}
		} 

		if ($needUpdate) {
			update_option( 'lay-search-post-array', $searchPostArray);
		}
	}

	public static function getSearchPostArray() {
		$searchPostArray = get_option( 'lay-search-post-array' );
		if ( $searchPostArray == false ) {
			LaySearch::search_save_post(-1);
		}
		return $searchPostArray;
	}
}
new LaySearch();
