<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\Core\Settings\Settings;

/**
 * Settings REST API endpoints.
 */
class SettingsEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register settings routes.
	 */
	public static function register(): void {
		register_rest_route(self::NAMESPACE, '/settings', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_settings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/settings', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'save_settings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/settings/reset', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'reset_settings'],
			'permission_callback' => [self::class, 'permission_check'],
		]);
	}

	/**
	 * Permission check for admin-only endpoints.
	 */
	public static function permission_check(): bool {
		return current_user_can('manage_options');
	}

	/**
	 * Get all settings.
	 */
	public static function get_settings(\WP_REST_Request $request): \WP_REST_Response {
		$settings = Settings::get_instance();

		return new \WP_REST_Response([
			'success' => true,
			'data' => [
				'settings' => $settings->get_all(),
				'schema' => $settings->get_schema(),
			],
		], 200);
	}

	/**
	 * Save settings.
	 */
	public static function save_settings(\WP_REST_Request $request): \WP_REST_Response {
		$settings = Settings::get_instance();
		$values = $request->get_json_params();

		if (empty($values)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __('No settings provided.', 'form-connector'),
			], 400);
		}

		$saved = $settings->update($values);

		if ($saved) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => __('Settings saved successfully.', 'form-connector'),
				'data' => $settings->get_all(),
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => __('Failed to save settings.', 'form-connector'),
		], 500);
	}

	/**
	 * Reset settings to defaults.
	 */
	public static function reset_settings(\WP_REST_Request $request): \WP_REST_Response {
		$settings = Settings::get_instance();
		$reset = $settings->reset();

		if ($reset) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => __('Settings reset to defaults.', 'form-connector'),
				'data' => $settings->get_all(),
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => __('Failed to reset settings.', 'form-connector'),
		], 500);
	}
}
