<?php

namespace Dispatch\Functions;

use WP_Query;

class Search {

    public function __construct() {

        add_action('wp_ajax_search', [$this, 'search']);
        add_action('wp_ajax_nopriv_search', [$this, 'search']);

    }

    public function search() {

        if (!isset($_POST['s'])) {
            throw new Exception("Query parameter 's' is required for searching");
        }

        $query = new WP_Query();
        $query->query_vars['s'] = $_POST['s'];
        $query->query_vars['post_type'] = 'any';
        $query->query_vars['posts_per_page'] = -1;
        relevanssi_do_query($query);

        // foreach ($query->posts as $post) {
        //     $post->acf = get_fields($post->ID);
        //     $post->title = array( 'rendered' => $post->post_title );
        //     $post->slug = $post->post_name;
        //     $post->id = $post->ID;
        //     if ( get_field( 'place_date_range', $post->ID ) ) {
        //         $post->date_range = format_daterange(get_field( 'place_date_range_start', $post->ID ), get_field( 'place_date_range_end', $post->ID ));
        //     }
        // }

        $data = array(
                'results' => $query->posts
            );

        ob_start();
            echo \Timber::compile('components/search-results.twig', $data);
        $html = ob_get_clean();

        wp_send_json([
            'results' => $query->posts,
            'html' => $html
        ]);

    }

}
