<?php

/**
 * Ajax loop
 *
 * Handle ajax loop on archive default archieve and CPT
 *
 * @package     Retheme
 * @category    Core
 * @author      Webforia Studio
 * @version     3.0.0
 */

namespace Retheme;

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

class Query_Ajax {
    public function __construct() {
        add_action('wp_enqueue_scripts', [$this, 'load_scripts'], 99);
        add_action('rest_api_init', [$this, 'rest_api']);
    }

   /**
     * Load scripts
     *
     * @return void
     */
    public function load_scripts() {
        wp_enqueue_script('retheme-ajax-loop', get_template_directory_uri() . '/core/ajax-load/assets/js/ajax-loop.min.js', false, '1.0.0', true);
        wp_localize_script('retheme-ajax-loop', 'retheme_query_ajax', [
            'apiurl' => rest_url('retheme/v1/ajax-loop'),
            'text' => [
                'errorMessage' => __('Server not response, please reload this page', 'jelajah-text'),
                'loading' => __('Loading', 'jelajah-text'),
                'loadmore' => __('Load More', 'jelajah-text'),
            ],
        ]);
    }

     /**
     * Register Rest API
     *
     * @return void
     * @throws \WP_Error If route already exists
     */
    public function rest_api() {
        register_rest_route('retheme/v1', 'ajax-loop', [
            'methods'  => 'POST',
            'callback' => [$this, 'result'],
            'permission_callback' => '__return_true',
        ]);
    }

    /**
     * return query
     *
     * @return [post]
     */
    public function result() {

        // get setting from json to array
        $settings = json_decode(html_entity_decode(stripslashes($_POST['query'])), true);
        
        if (empty($settings) || !is_array($settings)) {
            wp_send_json_error(__('Invalid request data', 'jelajah-text'), 400);
        }

        // Merge Array with current page and status publish
        $the_query = new \WP_Query(wp_parse_args($settings, [
            'paged' => $_POST['page'],
            'post_status' => 'publish',
        ]));

        ob_start();

        if ($the_query->have_posts()) {
            while ($the_query->have_posts()) : $the_query->the_post();

                include get_template_directory() . "/{$settings['template_part']}.php";

            endwhile;

            wp_reset_postdata();
        }

        $ajax_results = ob_get_clean();

        wp_send_json($ajax_results);
    }

    /* end class */
}
new Query_Ajax;
