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

namespace Backreload\Api;

use WP_REST_Request;

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

class MaintenanceController extends BaseController {

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

	public function show() {
		return $this->ok( $this->plugin->get( 'maintenance' )->status() );
	}

	public function update( WP_REST_Request $req ) {
		$svc = $this->plugin->get( 'maintenance' );

		$active = $req->get_param( 'active' );
		$config = [];
		foreach ( [ 'heading', 'message', 'eta' ] as $k ) {
			$v = $req->get_param( $k );
			if ( null !== $v ) $config[ $k ] = sanitize_text_field( (string) $v );
		}
		$ips = $req->get_param( 'bypass_ips' );
		if ( null !== $ips ) {
			$config['bypass_ips'] = array_values( array_filter(
				array_map( 'trim', is_array( $ips ) ? $ips : explode( "\n", (string) $ips ) )
			) );
		}

		if ( true === $active || 'true' === $active || 1 === $active || '1' === $active ) {
			$svc->enable( $config );
			$this->plugin->get( 'logger' )->warn( 'Maintenance mode enabled' );
		} elseif ( false === $active || 'false' === $active || 0 === $active || '0' === $active ) {
			$svc->disable();
			$this->plugin->get( 'logger' )->info( 'Maintenance mode disabled' );
		} elseif ( $config ) {
			// Update config only (don't change active state).
			$cur = $svc->status();
			update_option( \Backreload\Core\MaintenanceMode::OPTION, array_merge( $cur, $config ) );
		}

		return $this->show();
	}
}
