<?php
/**
 * Settings REST API Controller
 *
 * Provides REST API endpoints for plugin settings management.
 *
 * @package Sequensy
 * @since 2.0.0
 */

declare(strict_types=1);

namespace Sequensy\Rest;

use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class SettingsController
 *
 * REST API controller for reading and writing plugin settings.
 */
class SettingsController extends WP_REST_Controller {

	use RestControllerTrait;

	/**
	 * Option key for storing settings in wp_options.
	 *
	 * @var string
	 */
	const OPTION_KEY = 'sequensy_settings';

	/**
	 * Default settings values.
	 *
	 * @var array<string, mixed>
	 */
	const DEFAULTS = array(
		'debug_mode'          => false,
		'email_notifications' => true,
		'log_retention'       => 30,
		'max_retries'         => 3,
		'retry_delay'         => 1,
		'webhook_timeout'     => 30,
	);

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->namespace = 'sequensy/v1';
		$this->rest_base = 'settings';
	}

	/**
	 * Register REST API routes.
	 */
	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_settings' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'update_settings' ),
					'permission_callback' => array( $this, 'permissions_check' ),
					'args'                => array(
						'debug_mode'          => array(
							'description'       => 'Enable debug mode',
							'type'              => 'boolean',
							'sanitize_callback' => 'rest_sanitize_boolean',
							'validate_callback' => 'rest_validate_request_arg',
						),
						'email_notifications' => array(
							'description'       => 'Enable email notifications',
							'type'              => 'boolean',
							'sanitize_callback' => 'rest_sanitize_boolean',
							'validate_callback' => 'rest_validate_request_arg',
						),
						'log_retention'       => array(
							'description'       => 'Log retention in days',
							'type'              => 'integer',
							'sanitize_callback' => 'absint',
							'validate_callback' => 'rest_validate_request_arg',
						),
						'max_retries'         => array(
							'description'       => 'Maximum retry attempts',
							'type'              => 'integer',
							'sanitize_callback' => 'absint',
							'validate_callback' => 'rest_validate_request_arg',
						),
						'retry_delay'         => array(
							'description'       => 'Retry delay in minutes',
							'type'              => 'integer',
							'sanitize_callback' => 'absint',
							'validate_callback' => 'rest_validate_request_arg',
						),
						'webhook_timeout'     => array(
							'description'       => 'Webhook timeout in seconds',
							'type'              => 'integer',
							'sanitize_callback' => 'absint',
							'validate_callback' => 'rest_validate_request_arg',
						),
					),
				),
			)
		);
	}

	/**
	 * Get plugin settings.
	 *
	 * Merges saved values with defaults to ensure all keys are present.
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_REST_Response Response object.
	 */
	public function get_settings( WP_REST_Request $request ): WP_REST_Response {
		$saved    = get_option( self::OPTION_KEY, array() );
		$settings = wp_parse_args( $saved, self::DEFAULTS );

		return rest_ensure_response( $settings );
	}

	/**
	 * Update plugin settings.
	 *
	 * Sanitizes input values and saves to wp_options.
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_REST_Response Response object.
	 */
	public function update_settings( WP_REST_Request $request ): WP_REST_Response {
		$params   = $request->get_params();
		$current  = get_option( self::OPTION_KEY, array() );
		$settings = wp_parse_args( $current, self::DEFAULTS );

		// Sanitize and apply incoming values.
		if ( isset( $params['debug_mode'] ) ) {
			$settings['debug_mode'] = (bool) $params['debug_mode'];
		}

		if ( isset( $params['email_notifications'] ) ) {
			$settings['email_notifications'] = (bool) $params['email_notifications'];
		}

		if ( isset( $params['log_retention'] ) ) {
			$settings['log_retention'] = absint( $params['log_retention'] );
		}

		if ( isset( $params['max_retries'] ) ) {
			$settings['max_retries'] = absint( $params['max_retries'] );
		}

		if ( isset( $params['retry_delay'] ) ) {
			$settings['retry_delay'] = absint( $params['retry_delay'] );
		}

		if ( isset( $params['webhook_timeout'] ) ) {
			$settings['webhook_timeout'] = absint( $params['webhook_timeout'] );
		}

		update_option( self::OPTION_KEY, $settings );

		return rest_ensure_response( $settings );
	}
}
