<?php

namespace ParcelPanel\CmsPlus;

use ParcelPanel\CmsPlus\Trait\SingletonTrait;
use WP_Error;
use WP_REST_Posts_Controller;
use WP_REST_Request;

/**
 * 根据 URL 路径获取文章
 */
class ActionGetPageTagList
{
    use SingletonTrait;

    public function init()
    {
        add_action('rest_api_init', function () {
            register_rest_route(PARCELPANEL_CMS_PLUS_ROUTE_NAMESPACE, '/page_tags', array(
                'methods' => 'GET',
                'callback' => [$this, 'getPageTags']
            ));

            register_rest_route(PARCELPANEL_CMS_PLUS_ROUTE_NAMESPACE, '/page_tags/(?P<id>\d+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'getPageByTag'],
            ));
        });
    }


    public function getPageTags(): \WP_Error|\WP_REST_Response|\WP_Post
    {
        global $wpdb;

        $results = $wpdb->get_results("select meta_id, meta_value from $wpdb->postmeta where meta_key = 'tag' group by meta_value");

        return rest_ensure_response([
            'page_tags' => array_map(function ($value) {
                return [
                    'label' => $value->meta_value,
                    'id' => $value->meta_id
                ];
            }, $results)
        ]);
    }

    public function getPageByTag(WP_REST_Request $data)
    {
        global $wpdb;

        $meta_id = (int)$data['id'];
        $page = (int) ($_GET['page'] ?? 1);
        $per_page = (int) ($_GET['per_page'] ?? 10);

        // 查询数据库获取标签信息
        $query = $wpdb->prepare(
            "SELECT meta_id, meta_value FROM {$wpdb->postmeta} WHERE meta_id = %d AND meta_key = 'tag' LIMIT 1",
            $meta_id
        );
        $result = $wpdb->get_results($query);

        // 检查是否存在标签信息，如果不存在则返回错误
        if (empty($result)) {
            return new WP_Error(
                'rest_page_tags_invalid_id',
                'Invalid ID',
                array('status' => 404)
            );
        }

        $page_ids = $wpdb->get_col($wpdb->prepare(
            "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'tag' AND meta_value = %s",
            $result[0]->meta_value
        ));

        $request = new WP_REST_Request('GET', "/wp/v2/post");
        $request->set_query_params([
            'include' => $page_ids,
            'per_page' => $per_page,
            'page' => $page,
            'status' => 'publish',
            'order' => 'desc',
            '_embed' => true,
            '_fields' => join(",", [
                'id', 'title', 'type', 'categories', 'tags', 'meta',
                'link', 'slug',
                'yoast_head_json.title',
                'yoast_head_json.description',
                'yoast_head_json.og_image'
            ])
        ]);

        $controller = new WP_REST_Posts_Controller('page');
        return $controller->get_items($request);
    }
}
