<?php
/**
 * Menu New Tab URLs API
 *
 * Handles configuration for URLs that should open in a new tab (instead of iframe).
 *
 * @package FleekDash
 * @since V2.2
 */

namespace FleekDash\API;

use Throwable;
use WP_REST_Request;
use WP_REST_Response;
use FleekDash\Admin\Menu\MenuConfigService;
use FleekDash\Core\AuthMiddleware;

class MenuNewTabUrlsAPI
{
    private MenuConfigService $menuConfig;

    public function __construct()
    {
        $this->menuConfig = new MenuConfigService();
    }

    public function checkPermissions(): bool
    {
        // Always return true - auth handled inside methods with graceful fallback.
        return true;
    }

    /**
     * REST passes WP_REST_Request; extra args are ignored when this signature has no params.
     */
    public function getNewTabUrls(): WP_REST_Response
    {
        try {
            $auth = AuthMiddleware::check('authenticated');
            if (empty($auth['authenticated'])) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Not authenticated',
                    'fallback_data' => [
                        'urls' => $this->menuConfig->getDefaultNewTabUrls(),
                        'defaults' => $this->menuConfig->getDefaultNewTabUrls(),
                        'is_customized' => false,
                        'count' => 0,
                    ],
                ], 200);
            }

            $configured = $this->menuConfig->getNewTabUrls();
            $defaults = $this->menuConfig->getDefaultNewTabUrls();

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'urls' => $configured,
                    'defaults' => $defaults,
                    'is_customized' => $configured !== $defaults,
                    'count' => count($configured),
                ],
            ], 200);
        } catch (Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to get new tab URLs',
                'fallback_data' => [
                    'urls' => $this->menuConfig->getDefaultNewTabUrls(),
                    'defaults' => $this->menuConfig->getDefaultNewTabUrls(),
                    'is_customized' => false,
                    'count' => 0,
                ],
            ], 200);
        }
    }

    public function updateNewTabUrls(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $auth = AuthMiddleware::check('admin');
            $authorized = !empty($auth['authenticated'])
                && AuthMiddleware::validateRestNonceForMutation($request);

            if (!$authorized) {
                $response = $this->buildUpdateUrlsLimitedResponse();
            } else {
                $body = json_decode($request->get_body(), true);
                $urls = $body['urls'] ?? [];
                if (!is_array($urls)) {
                    $response = new WP_REST_Response([
                        'success' => false,
                        'message' => 'URLs must be an array',
                        'fallback_data' => [
                            'urls' => $this->menuConfig->getNewTabUrls(),
                        ],
                    ], 200);
                } else {
                    $sanitized_urls = $this->menuConfig->updateNewTabUrls($urls);
                    $response = new WP_REST_Response([
                        'success' => true,
                        'message' => 'New tab URLs updated successfully',
                        'data' => [
                            'urls' => array_values($sanitized_urls),
                            'count' => count($sanitized_urls),
                        ],
                    ], 200);
                }
            }

            return $response;
        } catch (Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to update new tab URLs',
                'fallback_data' => [
                    'urls' => $this->menuConfig->getNewTabUrls(),
                ],
            ], 200);
        }
    }

    private function buildUpdateUrlsLimitedResponse(): WP_REST_Response
    {
        return new WP_REST_Response(
            [
                'success' => false,
                'message' => 'Access limited',
                'fallback_data' => [
                    'urls' => $this->menuConfig->getNewTabUrls(),
                ],
            ],
            200,
        );
    }

    public function resetNewTabUrls(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $auth = AuthMiddleware::check('admin');
            if (empty($auth['authenticated']) || !AuthMiddleware::validateRestNonceForMutation($request)) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Access limited',
                    'fallback_data' => [
                        'urls' => $this->menuConfig->getNewTabUrls(),
                    ],
                ], 200);
            }

            $defaults = $this->menuConfig->resetNewTabUrls();

            return new WP_REST_Response([
                'success' => true,
                'message' => 'New tab URLs reset to default',
                'data' => [
                    'urls' => $defaults,
                    'count' => count($defaults),
                ],
            ], 200);
        } catch (Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to reset new tab URLs',
                'fallback_data' => [
                    'urls' => $this->menuConfig->getDefaultNewTabUrls(),
                ],
            ], 200);
        }
    }
}
