<?php

namespace Fab\Api;

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

use Fab\Interfaces\JIT_Interface;

/**
 * Post API
 *
 * @package    Fab
 * @subpackage Fab/Api
 */
class Posts extends Api implements JIT_Interface {

    /**
     * Register REST API endpoints
     */
    public function register_post_search_endpoint() {
        register_rest_route(
            'fab/v1',
            '/search-posts',
            array(
                'methods'             => 'GET',
                'callback'            => array( $this, 'search_posts_handler' ),
                'permission_callback' => function () {
                    return defined( 'FAB_REST_API_USER_IS_ADMIN' ) && FAB_REST_API_USER_IS_ADMIN;
                },
                'args'                => array(
                    'q' => array(
                        'required'          => false,
                        'type'              => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                ),
            )
        );
    }

    /**
     * Handle post search
     */
    public function search_posts_handler( \WP_REST_Request $request ) {
        // Get search term
        $search = $request->get_param( 'q' );

        // Get all public post types
        $post_types = get_post_types( array( 'publicly_queryable' => true ) );

        // Include pages in search, because WordPress set pages not publicly queryable by default.
        // Learn more: https://wordpress.stackexchange.com/questions/67003/is-there-a-reason-why-pages-are-not-publicly-queryable
        $post_types['page'] = 'page';

        // Query posts
        $args = array(
            'post_type'      => array_values( $post_types ),
            'post_status'    => 'publish',
            's'              => $search,
            'posts_per_page' => 20,
        );

        $query   = new \WP_Query( $args );
        $results = array();

        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
                $results[] = array(
                    'id'        => get_the_ID(),
                    'text'      => get_the_title(),
                    'post_type' => get_post_type(),
                );
            }
        }

        wp_reset_postdata();

        return rest_ensure_response( $results );
    }

    /*
    |--------------------------------------------------------------------------
    | Fulfill implemented interface contracts
    |--------------------------------------------------------------------------
     */

    /**
     * JIT Method.
     *
     * @return void
     */
    public static function jit() {
        // Register Routes.
        add_action( 'rest_api_init', array( __CLASS__, 'jit_register_post_search_endpoint' ) );
    }
}
