<?php

namespace Waypoint\Agent\Admin;

use Waypoint\Agent\Base\Thing;

class Settings_Page extends Thing {

	const NONCE_ACTION = 'waypoint_agent_settings_save';
	const NONCE_FIELD  = 'waypoint_agent_nonce';

	public function attach_hooks(): void {
		add_action( 'admin_menu', [ $this, 'register_page' ] );
		add_action( 'admin_post_waypoint_agent_save_settings', [ $this, 'handle_save' ] );
	}

	public function register_page(): void {
		add_management_page(
			'Waypoint Agent',
			'Waypoint Agent',
			'manage_options',
			'waypoint-agent',
			[ $this, 'render' ]
		);
	}

	public function handle_save(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'Unauthorized.' );
		}

		check_admin_referer( self::NONCE_ACTION, self::NONCE_FIELD );

		Settings::save( $_POST );

		wp_redirect( add_query_arg( [ 'page' => 'waypoint-agent', 'saved' => '1' ], admin_url( 'tools.php' ) ) );
		exit;
	}

	public function render(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings = Settings::get_all();
		$saved    = isset( $_GET['saved'] );
		?>
		<div class="wrap">
			<h1>Waypoint Agent</h1>
			<p>Version <?php echo esc_html( WAYPOINT_AGENT_VERSION ); ?></p>

			<?php if ( $saved ) : ?>
				<div class="notice notice-success is-dismissible">
					<p>Settings saved.</p>
				</div>
			<?php endif; ?>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<input type="hidden" name="action" value="waypoint_agent_save_settings">
				<?php wp_nonce_field( self::NONCE_ACTION, self::NONCE_FIELD ); ?>

				<table class="form-table" role="presentation">
					<tbody>
						<?php foreach ( Settings::FEATURES as $key => $feature ) : ?>
							<tr>
								<th scope="row"><?php echo esc_html( $feature['label'] ); ?></th>
								<td>
									<label>
										<input
											type="checkbox"
											name="<?php echo esc_attr( $key ); ?>"
											value="1"
											<?php checked( $settings[ $key ] ); ?>
										>
										<?php echo esc_html( $feature['description'] ); ?>
									</label>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>

				<?php submit_button( 'Save Settings' ); ?>
			</form>
		</div>
		<?php
	}
}
