<?php

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

final class WpironSecurityHeaders {


	const OPTION_NAME = 'wpironis_options';
	private $helpers;

	public function __construct(WpironHelper $helpers) {
		$this->helpers = $helpers;
	}
	public function handleSecurityHeadersToggle($enabled, $headerName) {
		if ( empty( $headerName ) ) {
			wp_send_json_error( 'Invalid header name' );
			return;
		}

		if ( ! isset( $option_map[ $headerName ] ) ) {
			wp_send_json_error( 'Unknown header type' );

			return;
		}

		$option_name = $option_map[ $headerName ];
		$options = $this->helpers->wpironis_getOption(self::OPTION_NAME);
		$options[ $option_name ] = $enabled ? 1 : 0;
		$updated = update_option( 'wpironis_options', $options );

		$header_friendly_names = [
			'contentTypeOptions'      => 'X-Content-Type-Options',
			'frameOptions'            => 'X-Frame-Options',
			'xssProtection'           => 'X-XSS-Protection',
			'strictTransportSecurity' => 'Strict-Transport-Security',
			'referrerPolicy'          => 'Referrer-Policy',
			'contentSecurityPolicy'   => 'Content-Security-Policy',
			'permissionsPolicy'       => 'Permissions-Policy'
		];

		$header_friendly_name = isset( $header_friendly_names[ $headerName ] ) ? $header_friendly_names[ $headerName ] : $headerName;

		if ( $updated ) {
			wp_send_json_success( array(
				'message' => sprintf( '%s header %s successfully',
					$header_friendly_name,
					$enabled ? 'enabled' : 'disabled' ),
				'enabled' => $enabled,
				'options' => $options
			) );
		} else {
			$current_options = get_option( 'wpironis_options' );
			if ( isset( $current_options[ $option_name ] ) && $current_options[ $option_name ] === ( $enabled ? 1 : 0 ) ) {
				wp_send_json_success( array(
					'message' => sprintf( '%s header is already %s',
						$header_friendly_name,
						$enabled ? 'enabled' : 'disabled' ),
					'enabled' => $enabled,
					'options' => $current_options
				) );
			} else {
				wp_send_json_error( sprintf( 'Failed to update %s header setting', $header_friendly_name ) );
			}
		}
	}

}