<?php

namespace Reach\App\Menus;

use Reach\App\Interfaces\WordPressHooks;

/**
 * Class PostSearch
 *
 * @package Reach\App\Menus
 */
class PostSearch implements WordPressHooks {
    /**
     * Add class hooks.
     */
    public function addHooks() {
        add_filter( 'posts_join', [$this, 'cf_search_join'], 10);
        add_filter( 'posts_where', [$this, 'cf_search_where'], 10 );
        add_filter( 'posts_distinct', [$this, 'cf_search_distinct'], 10 );
        add_action( 'wp_enqueue_scripts', [$this, 'ja_global_enqueues'], 10 );
        add_action( 'wp_ajax_search_site', [$this, 'ja_ajax_search'], 10 );
        add_action( 'wp_ajax_nopriv_search_site', [$this, 'ja_ajax_search'], 10 );
        add_action( 'wp_head', [$this, 'autocomplete_rl'], 10);
    }

    public function cf_search_join( $join ) {
        global $wpdb;

        if ( is_search() ) {
            $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
        }

        return $join;
    }

    public function cf_search_where( $where ) {
        global $pagenow, $wpdb;
    
        if ( is_search() ) {
            $where = preg_replace(
                "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
                "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
        }
    
        return $where;
    }

    public function cf_search_distinct( $where ) {
        global $wpdb;
    
        if ( is_search() ) {
            return "DISTINCT";
        }
    
        return $where;
    }

    public function ja_global_enqueues() {
        wp_enqueue_style(
            'jquery-auto-complete',
            'https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.css',
            array(),
            '1.0.7'
        );
    
        wp_enqueue_script(
            'jquery-auto-complete',
            'https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.min.js',
            array( 'jquery' ),
            '1.0.7',
            true
        );

        wp_localize_script(
            'jquery-auto-complete',
            'global',
            array(
                'ajax' => admin_url( 'admin-ajax.php' ),
            )
        );
    }

    public function ja_ajax_search() {

        $results = new \WP_Query( array(
            'post_type'     => array( 'post', 'page' ),
            'post_status'   => 'publish',
            'nopaging'      => true,
            'posts_per_page'=> 100,
            's'             => stripslashes( $_POST['search'] ), 
        ) );
    
        $items = array();
    
        if ( !empty( $results->posts ) ) {
            foreach ( $results->posts as $result ) {
                $items[] = $result->post_title;
            }
        }
        
        wp_send_json_success( $items );
    }

    public function autocomplete_rl() { ?>
        <script type="text/javascript">
            jQuery(function($) {
                jQuery('input[type=search]').addClass('search-autocomplete');
                jQuery('input[type=search]').attr('autocomplete', 'on');
            });
            jQuery(function($){
                var searchRequest;
                jQuery('.search-autocomplete').autoComplete({
                    minChars: 2,
                    source: function(term, suggest){
                        try { searchRequest.abort(); } catch(e){}
                        searchRequest = jQuery.getJSON(global.ajax, { q: term, action: 'search_site' }, function(res) {
                            var suggestions = [];
                            for (i=0;i<res.data.length;i++)
                                if (~res.data[i].toLowerCase().indexOf(term)) {
                                    suggestions.push(res.data[i]);
                                } 
                                else if (~res.data[i].toUpperCase().indexOf(term)) { 
                                    suggestions.push(res.data[i]) 
                                };
                            suggest(suggestions);
                        });
                    }
                });
            });
        </script>
    <?php }
}
