<?php

/**
 * Command Palette REST API Controller.
 *
 * @package ProRank\SEO\Core\RestApi
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use ProRank\SEO\Core\MenuRegistry;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * Command Palette controller class.
 */


class CommandPaletteController extends BaseController {
    /**
     * Menu registry instance.
     *
     * @var MenuRegistry
     */
    private MenuRegistry $menu_registry;

    /**
     * Constructor.
     *
     * @param MenuRegistry $menu_registry Menu registry instance.
     */
    public function __construct(MenuRegistry $menu_registry) {
        $this->menu_registry = $menu_registry;
    }

    /**
     * Register routes.
     *
     * @return void
     */
    public function register_routes(): void {
        register_rest_route(
            $this->namespace,
            '/command-palette/items',
            [
                [
                    'methods'             => 'GET',
                    'callback'            => [$this, 'get_items'],
                    'permission_callback' => [$this, 'check_permission'],
                    'args'                => [],
                ],
                'schema' => [$this, 'get_items_schema'],
            ]
        );
    }

    /**
     * Get command palette items.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response object or error.
     */
    public function get_items($request) {
        try {
            $items = [];

            // Get all registered menu items from MenuRegistry
            $menus_data = $this->menu_registry->get_registered_menus_data();
            $menu_items = array_merge(
                $menus_data['top_level'] ?? [],
                $menus_data['sub_menus'] ?? []
            );

            // Process menu items — only include free-tier items
            foreach ($menu_items as $item) {
                // Skip if user doesn't have capability
                if (isset($item['capability']) && !current_user_can($item['capability'])) {
                    continue;
                }

                $items[] = [
                    'label'       => $item['menu_title'] ?? $item['page_title'] ?? '',
                    'description' => $item['description'] ?? null,
                    'url'         => $this->build_admin_url($item),
                    'type'        => 'navigation',
                ];
            }

            // Add additional command items (non-menu items)
            foreach ($this->get_additional_command_items() as $additional_item) {
                // Check capability
                if (isset($additional_item['capability']) && !current_user_can($additional_item['capability'])) {
                    continue;
                }

                unset($additional_item['capability']);
                $items[] = $additional_item;
            }

            return $this->get_success_response([
                'items' => $items,
                'total' => count($items),
            ]);

        } catch (\Exception $e) {
            return $this->get_error_response(
                __('Failed to fetch command palette items.', 'prorank-seo'),
                500,
                'fetch_failed'
            );
        }
    }

    /**
     * Build admin URL for menu item.
     *
     * @param array $item Menu item data.
     * @return string Admin URL.
     */
    private function build_admin_url(array $item): string {
        $slug = $item['slug'] ?? $item['menu_slug'] ?? '';
        if ($slug) {
            return admin_url('admin.php?page=' . $slug);
        }

        return admin_url();
    }

    /**
     * Get additional command items not in menu.
     *
     * @return array Additional command items.
     */
    private function get_additional_command_items(): array {
        return [
            [
                'label'       => __('SEO Settings', 'prorank-seo'),
                'description' => __('Configure general SEO settings', 'prorank-seo'),
                'url'         => admin_url('admin.php?page=prorank-seo'),
                'type'        => 'navigation',
                'capability'  => 'manage_options',
            ],
            [
                'label'       => __('Import/Export Settings', 'prorank-seo'),
                'description' => __('Import or export your SEO settings', 'prorank-seo'),
                'url'         => admin_url('admin.php?page=prorank-site-audit&tab=import-export'),
                'type'        => 'navigation',
                'capability'  => 'manage_options',
            ],
            [
                'label'       => __('View Documentation', 'prorank-seo'),
                'description' => __('Open ProRank SEO documentation', 'prorank-seo'),
                'url'         => 'https://prorank.io/docs/',
                'type'        => 'external',
                'capability'  => 'read',
            ],
            [
                'label'       => __('Support & Resources', 'prorank-seo'),
                'description' => __('Open documentation, feedback, changelog, and backup tools', 'prorank-seo'),
                'url'         => admin_url('admin.php?page=prorank-support'),
                'type'        => 'navigation',
                'capability'  => 'manage_options',
            ],
        ];
    }

    /**
     * Get items schema.
     *
     * @return array Schema definition.
     */
    public function get_items_schema(): array {
        return [
            '$schema'    => 'http://json-schema.org/draft-04/schema#',
            'title'      => 'command-palette-items',
            'type'       => 'object',
            'properties' => [
                'items' => [
                    'description' => __('List of command palette items.', 'prorank-seo'),
                    'type'        => 'array',
                    'items'       => [
                        'type'       => 'object',
                        'properties' => [
                            'label' => [
                                'description' => __('Item label.', 'prorank-seo'),
                                'type'        => 'string',
                            ],
                            'description' => [
                                'description' => __('Item description.', 'prorank-seo'),
                                'type'        => ['string', 'null'],
                            ],
                            'url' => [
                                'description' => __('Navigation URL.', 'prorank-seo'),
                                'type'        => 'string',
                                'format'      => 'uri',
                            ],
                            'action' => [
                                'description' => __('Action identifier.', 'prorank-seo'),
                                'type'        => ['string', 'null'],
                            ],
                            'type' => [
                                'description' => __('Item type.', 'prorank-seo'),
                                'type'        => 'string',
                                'enum'        => ['navigation', 'action', 'external'],
                            ],
                        ],
                    ],
                ],
                'total' => [
                    'description' => __('Total number of items.', 'prorank-seo'),
                    'type'        => 'integer',
                ],
            ],
        ];
    }
}
