<?php
/**
 * /backreload/v1/settings
 *
 * @package Backreload\Api
 */

namespace Backreload\Api;

use WP_REST_Request;

if ( ! defined( 'ABSPATH' ) ) { exit; }

class SettingsController extends BaseController {

	public function register( string $namespace ): void {
		register_rest_route( $namespace, '/settings', [
			[ 'methods' => 'GET',  'callback' => [ $this, 'show' ],   'permission_callback' => [ $this, 'check_perm' ] ],
			[ 'methods' => 'POST', 'callback' => [ $this, 'update' ], 'permission_callback' => [ $this, 'check_perm' ] ],
		] );
	}

	public function show() {
		$s = $this->plugin->get( 'options' )->settings();
		// Mask the passphrase
		if ( ! empty( $s['encryption_passphrase'] ) ) {
			$s['encryption_passphrase'] = '***';
		}
		return $this->ok( $s );
	}

	public function update( WP_REST_Request $req ) {
		// `notify_email`, `notify_on_failure`, `notify_on_success` removed:
		// the Notifications sidebar page (POST /notifiers) now owns every
		// channel including email, stored as rows inside backreload_notifiers.
		// `chunk_size_mb` removed: the engine auto-tunes the zip-part size
		// from PHP memory_limit, the saved value was never read.
		$allowed = [
			'encryption', 'encryption_passphrase',
			'compression_level', 'maintenance_on_restore',
			'exclusions',
			// Log auto-prune retention (days)
			'log_retention_days',
			// Trust forwarded IP header (for sites behind a reverse proxy)
			'trust_forwarded_ip',
		];
		$values = [];
		foreach ( $allowed as $k ) {
			$v = $req->get_param( $k );
			if ( null !== $v ) $values[ $k ] = $v;
		}
		// Don't persist the masked passphrase
		if ( isset( $values['encryption_passphrase'] ) && '***' === $values['encryption_passphrase'] ) {
			unset( $values['encryption_passphrase'] );
		}
		$this->plugin->get( 'options' )->update_settings( $values );
		return $this->show();
	}
}
