<?php
/**
 * Editor Settings Controller
 *
 * API endpoints for Editor Settings (Edit With dropdown, page builders).
 *
 * @package FleekDash\Controllers
 * @since 2.4.3
 */

namespace FleekDash\Controllers;

use WP_REST_Request;
use FleekDash\Core\AuthMiddleware;
use FleekDash\Services\EditorSettingsService;
use FleekDash\Services\EditorSettingsServiceInterface;
use FleekDash\Services\ResponseService;

class EditorSettingsController
{
    private EditorSettingsServiceInterface $service;

    public function __construct(?EditorSettingsServiceInterface $service = null)
    {
        $this->service = $service ?? new EditorSettingsService();
    }

    /**
     * Parity with RouteAuthMiddleware (GET uses authenticated(), POST uses admin()).
     * REST routes do not use this callback; kept for tests or future wiring.
     */
    public function checkPermissions(): bool
    {
        $auth = AuthMiddleware::check('authenticated');

        return !empty($auth['authenticated']);
    }

    /**
     * Log and return generic error response
     */
    private function handleError(string $context, \Exception $e, string $message)
    {
        if (\function_exists('fleekdash_log_error')) {
            \fleekdash_log_error('EditorSettingsController::' . $context . ': ' . $e->getMessage());
        }
        return ResponseService::error($message, null, 500);
    }

    /**
     * GET editor settings (detected editors + user settings)
     */
    public function getSettings()
    {
        try {
            $data = $this->service->getFullResponse();

            return ResponseService::success('Editor settings retrieved', $data);
        } catch (\Exception $e) {
            return $this->handleError(
                'getSettings',
                $e,
                'Failed to retrieve editor settings',
            );
        }
    }

    /**
     * POST update editor settings
     */
    public function updateSettings(WP_REST_Request $request)
    {
        try {
            $params = $request->get_json_params();
            if (!$params || !\is_array($params)) {
                $out = ResponseService::error('Invalid parameters', null, 400);
            } elseif (!$this->service->updateSettings($params)) {
                $out = ResponseService::error(
                    'Unable to persist editor settings. Please try again.',
                    null,
                    503,
                );
            } else {
                $data = $this->service->getFullResponse();
                $out = ResponseService::success('Editor settings updated', $data);
            }

            return $out;
        } catch (\Exception $e) {
            return $this->handleError(
                'updateSettings',
                $e,
                'Failed to update editor settings',
            );
        }
    }
}
