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

add_action('rest_api_init', 'cf_resource_search_register_rest');

function cf_resource_search_register_rest() {
    register_rest_route('cf-resource-search/v1', '/filter', [
        'methods'             => 'GET',
        'callback'            => 'cf_resource_search_filter_posts',
        'permission_callback' => '__return_true',
        'args'                => [
            'search'  => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
            'topic'   => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
            'service' => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
            'type'    => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
            'page'    => ['type' => 'integer', 'default' => 1, 'sanitize_callback' => 'absint'],
            'per_page'=> ['type' => 'integer', 'default' => 9, 'sanitize_callback' => 'absint'],
        ],
    ]);
}

function cf_resource_search_filter_posts($request) {
    $args = [
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => $request->get_param('per_page') ?: 9,
        'paged'          => $request->get_param('page') ?: 1,
        'orderby'        => 'date',
        'order'          => 'DESC',
    ];

    // Search query
    $search = $request->get_param('search');
    if (!empty($search)) {
        $args['s'] = $search;
    }

    // Taxonomy filters
    $tax_query = [];

    $topic = $request->get_param('topic');
    if (!empty($topic)) {
        $tax_query[] = [
            'taxonomy' => 'topic',
            'field'    => 'slug',
            'terms'    => $topic,
        ];
    }

    $service = $request->get_param('service');
    if (!empty($service)) {
        $tax_query[] = [
            'taxonomy' => 'resource-service',
            'field'    => 'slug',
            'terms'    => $service,
        ];
    }

    $type = $request->get_param('type');
    if (!empty($type)) {
        $tax_query[] = [
            'taxonomy' => 'resource-type',
            'field'    => 'slug',
            'terms'    => $type,
        ];
    }

    if (!empty($tax_query)) {
        $tax_query['relation'] = 'AND';
        $args['tax_query'] = $tax_query;
    }

    $query = new WP_Query($args);
    $posts_html = '';

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();

            // Get resource type label
            $resource_types = get_the_terms(get_the_ID(), 'resource-type');
            $type_label = $resource_types && !is_wp_error($resource_types) ? $resource_types[0]->name : 'Article';
            $type_slug = $resource_types && !is_wp_error($resource_types) ? $resource_types[0]->slug : 'article';

            // Get topic label
            $topics = get_the_terms(get_the_ID(), 'topic');
            $topic_label = $topics && !is_wp_error($topics) ? $topics[0]->name : '';

            // Get featured image
            $thumbnail = get_the_post_thumbnail_url(get_the_ID(), 'medium');

            $posts_html .= '<article class="cf-resource-card" data-type="' . esc_attr($type_slug) . '">';
            $posts_html .= '<a href="' . esc_url(get_permalink()) . '" class="cf-resource-card-link">';

            if ($thumbnail) {
                $posts_html .= '<div class="cf-resource-card-image"><img src="' . esc_url($thumbnail) . '" alt="' . esc_attr(get_the_title()) . '" loading="lazy"></div>';
            }

            $posts_html .= '<div class="cf-resource-card-content">';
            $posts_html .= '<span class="cf-resource-card-type cf-type-' . esc_attr($type_slug) . '">' . esc_html($type_label) . '</span>';
            $posts_html .= '<h3 class="cf-resource-card-title">' . esc_html(get_the_title()) . '</h3>';

            $excerpt = get_the_excerpt();
            if ($excerpt) {
                $posts_html .= '<p class="cf-resource-card-excerpt">' . esc_html(wp_trim_words($excerpt, 20)) . '</p>';
            }

            $posts_html .= '<div class="cf-resource-card-meta">';
            if ($topic_label) {
                $posts_html .= '<span class="cf-resource-card-topic">' . esc_html($topic_label) . '</span>';
            }
            $posts_html .= '<time datetime="' . esc_attr(get_the_date('c')) . '">' . esc_html(get_the_date('M Y')) . '</time>';
            $posts_html .= '</div>'; // .meta

            $posts_html .= '</div>'; // .content
            $posts_html .= '</a>';
            $posts_html .= '</article>';
        }
        wp_reset_postdata();
    }

    return rest_ensure_response([
        'html'        => $posts_html,
        'found_posts' => $query->found_posts,
        'max_pages'   => $query->max_num_pages,
        'current_page'=> $request->get_param('page') ?: 1,
    ]);
}
