<?php
namespace WooNooW\Admin\Rest;

use WP_REST_Request;
use WooNooW\Admin\Compat\MenuProvider;

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

class MenuController {
    public static function init() {
        add_action('rest_api_init', [__CLASS__, 'register']);
    }

    public static function register() {
        register_rest_route('wnw/v1', '/menus', [
            'methods'             => 'GET',
            'callback'            => [__CLASS__, 'get_menus'],
            'permission_callback' => [__CLASS__, 'can_manage'],
        ]);
    }

    public static function can_manage(): bool {
        return current_user_can('manage_woocommerce');
    }

    public static function get_menus(WP_REST_Request $req) {
        $items = MenuProvider::get_snapshot();
        // Filter by capability here to be safe:
        $items = array_values(array_filter($items, function($it) {
            $cap = $it['capability'] ?? '';
            return empty($cap) || current_user_can($cap);
        }));
        return [
            'items' => $items,
            'ok'    => true,
        ];
    }
}