<?php
defined('ABSPATH') || exit;

class Willro_Reviews_REST {

    public function __construct() {
        add_action('wp_ajax_willro_filter_reviews', [$this, 'handle']);
        add_action('wp_ajax_nopriv_willro_filter_reviews', [$this, 'handle']);
    }

    public function handle() {
        $nonce = '';
        if ( isset( $_POST['nonce'] ) ) {
            $nonce = sanitize_text_field( wp_unslash( $_POST['nonce'] ) );
        }


        $settings = [
            'template'  => isset( $_POST['template'] ) ? absint( wp_unslash( $_POST['template'] ) ) : 1,
            'limit'     => isset( $_POST['limit'] ) ? absint( wp_unslash( $_POST['limit'] ) ) : 10,
            'mediaType' => isset( $_POST['mediaType'] ) ? sanitize_text_field( wp_unslash( $_POST['mediaType'] ) ) : '',
            'rating'    => isset( $_POST['rating'] ) ? sanitize_text_field( wp_unslash( $_POST['rating'] ) ) : '',
            'sortType'  => isset( $_POST['sortType'] ) ? sanitize_text_field( wp_unslash( $_POST['sortType'] ) ) : '',
            'page'      => isset( $_POST['page'] ) ? absint( wp_unslash( $_POST['page'] ) ) : 1,
        ];

        $html = Willro_Reviews_Renderer::render( $settings );
        $html = preg_replace( '/<!--[\\s\\S]*?-->/', '', $html );

        echo wp_kses( $html, Willro_Reviews_Renderer::allowed_html() );
        wp_die();
    }
}
