<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Api\Controller;

use BookiFlex\Core\Contract\RoleCapabilitiesInterface;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

/**
 * RatePlan REST API Controller
 *
 * Endpoints:
 * - GET /rate-plans - List all published rate plans (for block editor use)
 */
class RatePlanController extends AbstractController
{
    public const API_ENDPOINT_NAME = 'rate-plans';

    public function __construct(string $namespace = 'bflex/v1')
    {
        parent::__construct($namespace);
    }

    public function registerRoutes(): void
    {
        register_rest_route($this->namespace, '/' . self::API_ENDPOINT_NAME, [
            [
                'methods'             => 'GET',
                'callback'            => [$this, 'getRatePlans'],
                'permission_callback' => [$this, 'hasAccess'],
            ],
        ]);
    }

    public function getRatePlans(WP_REST_Request $request): WP_REST_Response|WP_Error
    {
        $posts = get_posts([
            'post_type'   => 'bflex-rate-plan',
            'numberposts' => -1,
            'post_status' => 'publish',
            'orderby'     => 'menu_order',
            'order'       => 'ASC',
        ]);

        $ratePlans = array_map(
            fn(\WP_Post $p) => ['id' => $p->ID, 'name' => $p->post_title],
            $posts
        );

        return $this->success([
            'result' => [
                'ratePlans' => $ratePlans,
            ],
        ]);
    }

    public function hasAccess(): bool|WP_Error
    {
        if (!current_user_can(RoleCapabilitiesInterface::MANAGE_CONFIGURATION)) {
            return $this->error(
                'bookiflex_forbidden',
                __('You are not allowed to manage configuration.', 'bookiflex'),
                401
            );
        }

        return true;
    }
}
