<?php
/**
 * Responsive settings management for AxcelersBlocks plugin.
 *
 * @package AxcelersBlocks
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class AxcelersBlocks_Responsive_Settings
 *
 * Handles the responsive settings (device widths for devices) for the AxcelersBlocks plugin.
 */
class AxcelersBlocks_Responsive_Settings {

	/**
	 * Settings error group slug (must match settings_fields group).
	 */
	private const SETTINGS_ERROR_GROUP = 'axcelersblocks_device_settings_group';

	/**
	 * Initialize hooks.
	 *
	 * @since 1.0.0
	 */
	public function init() {
		add_action( 'admin_init', array( $this, 'register_settings' ) );
	}

	/**
	 * Default responsive settings.
	 *
	 * @return array
	 */
	private function get_default_settings() {
		return array(
			'devices' => array(
				'tablet' => array(
					'name'       => 'Tablet',
					'width'      => '1024px',
					'is_default' => true,
				),
				'mobile' => array(
					'name'       => 'Mobile',
					'width'      => '768px',
					'is_default' => true,
				),
			),
		);
	}

	/**
	 * Register settings, sections, and fields for responsive settings.
	 *
	 * @since 1.0.0
	 */
	public function register_settings() {
		register_setting(
			'axcelersblocks_device_settings_group',
			'axcelersblocks_responsive_settings',
			array(
				'sanitize_callback' => array( $this, 'sanitize_responsive_settings' ),
				'default'           => $this->get_default_settings(),
			)
		);

		add_settings_section(
			'axcelersblocks_device_settings_section',
			__( 'Device Configuration', 'axcelersblocks' ),
			array( $this, 'device_settings_section_callback' ),
			'axcelersblocks-settings'
		);

		add_settings_field(
			'axcelersblocks_responsive_settings',
			__( 'Device Widths', 'axcelersblocks' ),
			array( $this, 'responsive_settings_field_callback' ),
			'axcelersblocks-settings',
			'axcelersblocks_device_settings_section'
		);
	}

	/**
	 * Sanitize a device width value (e.g. 1024px).
	 *
	 * @param mixed  $width        Raw width input.
	 * @param string $default      Fallback width.
	 * @param string $field_label  Human-readable field name for admin notices.
	 * @return string
	 */
	private function sanitize_device_width( $width, $default, $field_label ) {
		$width = is_string( $width ) ? trim( $width ) : '';

		if ( preg_match( '/^\d+px$/', $width ) ) {
			return $width;
		}

		if ( '' !== $width ) {
			add_settings_error(
				self::SETTINGS_ERROR_GROUP,
				'axcelersblocks_invalid_' . sanitize_key( $field_label ),
				sprintf(
					/* translators: 1: device field label, 2: example width */
					__( 'Invalid %1$s width. Use a pixel value like %2$s.', 'axcelersblocks' ),
					$field_label,
					$default
				),
				'error'
			);
		}

		return $default;
	}

	/**
	 * Extract the numeric pixel value from a width string.
	 *
	 * @param string $width Width string (e.g. 1024px).
	 * @return int
	 */
	private function parse_device_width_px( $width ) {
		if ( preg_match( '/^(\d+)px$/', (string) $width, $matches ) ) {
			return (int) $matches[1];
		}

		return 0;
	}

	/**
	 * Ensure mobile breakpoint is smaller than tablet breakpoint.
	 *
	 * @param array $sanitized Sanitized settings array.
	 * @return array
	 */
	private function enforce_device_width_order( array $sanitized ) {
		$defaults  = $this->get_default_settings();
		$tablet_px = $this->parse_device_width_px( $sanitized['devices']['tablet']['width'] ?? '' );
		$mobile_px = $this->parse_device_width_px( $sanitized['devices']['mobile']['width'] ?? '' );

		if ( $mobile_px >= $tablet_px ) {
			add_settings_error(
				self::SETTINGS_ERROR_GROUP,
				'axcelersblocks_mobile_width_order',
				__( 'Mobile width must be smaller than tablet width.', 'axcelersblocks' ),
				'error'
			);

			$sanitized['devices']['mobile']['width'] = $defaults['devices']['mobile']['width'];
			$mobile_px                               = $this->parse_device_width_px( $sanitized['devices']['mobile']['width'] );

			if ( $mobile_px >= $tablet_px ) {
				$sanitized['devices']['tablet']['width'] = $defaults['devices']['tablet']['width'];
			}
		}

		return $sanitized;
	}

	/**
	 * Sanitize the responsive settings.
	 *
	 * @param array $input The input data.
	 * @return array Sanitized data.
	 *
	 * @since 1.0.0
	 */
	public function sanitize_responsive_settings( $input ) {
		$sanitized = $this->get_default_settings();

		if ( ! is_array( $input ) ) {
			return $sanitized;
		}

		if ( isset( $input['devices'] ) && is_array( $input['devices'] ) ) {

			if ( isset( $input['devices']['tablet']['width'] ) ) {
				$sanitized['devices']['tablet']['width'] = $this->sanitize_device_width(
					$input['devices']['tablet']['width'],
					$sanitized['devices']['tablet']['width'],
					__( 'Tablet', 'axcelersblocks' )
				);
			}

			if ( isset( $input['devices']['mobile']['width'] ) ) {
				$sanitized['devices']['mobile']['width'] = $this->sanitize_device_width(
					$input['devices']['mobile']['width'],
					$sanitized['devices']['mobile']['width'],
					__( 'Mobile', 'axcelersblocks' )
				);
			}

			$sanitized = $this->enforce_device_width_order( $sanitized );
		}

		return $sanitized;
	}

	/**
	 * Device settings section callback.
	 *
	 * @since 1.0.0
	 */
	public function device_settings_section_callback() {
		echo '<p>' . esc_html__( 'Configure the device widths for responsive behavior. Unit should be PX (e.g., 1024px).', 'axcelersblocks' ) . '</p>';
	}

	/**
	 * Device settings field callback.
	 *
	 * @since 1.0.0
	 */
	public function responsive_settings_field_callback() {
		$responsive_settings = get_option( 'axcelersblocks_responsive_settings', $this->get_default_settings() );

		if ( ! is_array( $responsive_settings ) ) {
			$responsive_settings = $this->get_default_settings();
		}

		if ( ! isset( $responsive_settings['devices'] ) || ! is_array( $responsive_settings['devices'] ) ) {
			$responsive_settings['devices'] = $this->get_default_settings()['devices'];
		}

		?>
		<div id="axcelersblocks-responsive-settings">
			<div class="responsive-devices-list">
				<?php foreach ( $responsive_settings['devices'] as $key => $device ) : ?>
					<?php
					$device_name  = ( is_array( $device ) && isset( $device['name'] ) ) ? $device['name'] : '';
					$device_width = ( is_array( $device ) && isset( $device['width'] ) ) ? $device['width'] : '';
					?>
					<div class="responsive-device" style="margin-bottom: 20px;">
						<label><?php echo esc_html__( 'Device Name', 'axcelersblocks' ); ?></label>
						<input type="text"
							value="<?php echo esc_attr( $device_name ); ?>"
							style="width: 150px; margin-right: 10px;"
							readonly />

						<label><?php echo esc_html__( 'Device Width', 'axcelersblocks' ); ?></label>
						<input type="text"
							name="axcelersblocks_responsive_settings[devices][<?php echo esc_attr( $key ); ?>][width]"
							value="<?php echo esc_attr( $device_width ); ?>"
							style="width: 100px; margin-right: 10px;"
							required />
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}
}
