<?php
/**
 * Progressive Web App settings for the Tweaks page.
 *
 * @package FoodOrd
 */

defined( 'ABSPATH' ) || exit;

/**
 * Handles customer PWA settings and media selection.
 */
class Foodord_Pwa_Settings {
	private const ERROR_TRANSIENT = 'foodord_pwa_settings_error';

	/**
	 * Save settings from the unified Tweaks form.
	 */
	public function handle_form_submission(): void {
		if ( ! class_exists( 'Foodord_Pwa' ) || ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! isset( $_POST['foodord_tweaks_nonce'] ) ) {
			return;
		}

		$nonce = sanitize_text_field( wp_unslash( $_POST['foodord_tweaks_nonce'] ) );
		if ( ! wp_verify_nonce( $nonce, 'foodord_tweaks_save' ) ) {
			return;
		}

		$options = Foodord_Pwa::get_option_names();
		$changed = false;
		$enabled = isset( $_POST['foodord_pwa_enabled'] ) ? 'yes' : 'no';

		$app_name    = isset( $_POST['foodord_pwa_app_name'] )
			? sanitize_text_field( wp_unslash( $_POST['foodord_pwa_app_name'] ) )
			: '';
		$short_name  = isset( $_POST['foodord_pwa_short_name'] )
			? sanitize_text_field( wp_unslash( $_POST['foodord_pwa_short_name'] ) )
			: '';
		$description = isset( $_POST['foodord_pwa_description'] )
			? sanitize_text_field( wp_unslash( $_POST['foodord_pwa_description'] ) )
			: '';

		$app_name    = $this->limit_text( $app_name, 90 );
		$short_name  = $this->limit_text( $short_name, 30 );
		$description = $this->limit_text( $description, 180 );

		$icon_id          = isset( $_POST['foodord_pwa_icon_id'] )
			? absint( wp_unslash( $_POST['foodord_pwa_icon_id'] ) )
			: 0;
		$maskable_icon_id = isset( $_POST['foodord_pwa_maskable_icon_id'] )
			? absint( wp_unslash( $_POST['foodord_pwa_maskable_icon_id'] ) )
			: 0;

		$icon_valid = 0 === $icon_id || Foodord_Pwa::is_valid_icon_attachment( $icon_id );
		$mask_valid = 0 === $maskable_icon_id || Foodord_Pwa::is_valid_icon_attachment( $maskable_icon_id );

		if ( ! $icon_valid || ! $mask_valid ) {
			set_transient(
				$this->get_error_transient_key(),
				__( 'App icons must be square images of at least 512 by 512 pixels.', 'foodord' ),
				45
			);
			$icon_id          = absint( get_option( $options['icon_id'], 0 ) );
			$maskable_icon_id = absint( get_option( $options['maskable_icon_id'], 0 ) );
		}

		$site_icon_id = absint( get_option( 'site_icon', 0 ) );
		if ( 'yes' === $enabled && 0 === $icon_id && ! Foodord_Pwa::is_valid_icon_attachment( $site_icon_id ) ) {
			$enabled = 'no';
			set_transient(
				$this->get_error_transient_key(),
				__( 'Add a square 512 by 512 pixel app icon before enabling the customer app.', 'foodord' ),
				45
			);
		}

		if ( $icon_id > 0 ) {
			Foodord_Pwa::prepare_icon_attachment( $icon_id );
		}
		if ( $maskable_icon_id > 0 ) {
			Foodord_Pwa::prepare_icon_attachment( $maskable_icon_id );
		}

		$start_page_id = isset( $_POST['foodord_pwa_start_page_id'] )
			? absint( wp_unslash( $_POST['foodord_pwa_start_page_id'] ) )
			: 0;
		if ( $start_page_id > 0 && ( 'page' !== get_post_type( $start_page_id ) || 'publish' !== get_post_status( $start_page_id ) ) ) {
			$start_page_id = 0;
		}

		$theme_color      = isset( $_POST['foodord_pwa_theme_color'] )
			? sanitize_hex_color( wp_unslash( $_POST['foodord_pwa_theme_color'] ) )
			: null;
		$background_color = isset( $_POST['foodord_pwa_background_color'] )
			? sanitize_hex_color( wp_unslash( $_POST['foodord_pwa_background_color'] ) )
			: null;

		$values = array(
			$options['enabled']          => $enabled,
			$options['install_prompt']   => isset( $_POST['foodord_pwa_install_prompt'] ) ? 'yes' : 'no',
			$options['app_name']         => $app_name,
			$options['short_name']       => $short_name,
			$options['description']      => $description,
			$options['icon_id']          => $icon_id,
			$options['maskable_icon_id'] => $maskable_icon_id,
			$options['start_page_id']    => $start_page_id,
			$options['theme_color']      => is_string( $theme_color ) ? $theme_color : '#ea004b',
			$options['background_color'] => is_string( $background_color ) ? $background_color : '#ffffff',
		);

		foreach ( $values as $option => $value ) {
			if ( update_option( $option, $value ) ) {
				$changed = true;
			}
		}

		if ( 'yes' === $enabled ) {
			update_option( $options['ever_enabled'], 'yes', false );
		}

		if ( $changed ) {
			Foodord_Pwa::increment_revision();
			if ( class_exists( 'Foodord_Pwa_Language' ) ) {
				Foodord_Pwa_Language::register_translatable_strings();
			}
		}
	}

	/**
	 * Render PWA settings panel.
	 */
	public function render_section(): void {
		if ( ! class_exists( 'Foodord_Pwa' ) ) {
			return;
		}

		$options           = Foodord_Pwa::get_option_names();
		$enabled           = 'yes' === get_option( $options['enabled'], 'no' );
		$install_prompt    = 'no' !== get_option( $options['install_prompt'], 'yes' );
		$app_name          = (string) get_option( $options['app_name'], '' );
		$short_name        = (string) get_option( $options['short_name'], '' );
		$description       = (string) get_option( $options['description'], '' );
		$icon_id           = absint( get_option( $options['icon_id'], 0 ) );
		$maskable_icon_id  = absint( get_option( $options['maskable_icon_id'], 0 ) );
		$start_page_id     = absint( get_option( $options['start_page_id'], 0 ) );
		$theme_color       = (string) get_option( $options['theme_color'], '#ea004b' );
		$background_color  = (string) get_option( $options['background_color'], '#ffffff' );
		$error             = get_transient( $this->get_error_transient_key() );
		$effective_icon_id = Foodord_Pwa::get_icon_attachment_id();
		$pages             = get_pages(
			array(
				'post_status' => 'publish',
				'sort_column' => 'post_title',
				'sort_order'  => 'ASC',
			)
		);

		if ( $error ) {
			delete_transient( $this->get_error_transient_key() );
		}
		?>
		<div class="wrc-pwa-container">
			<div class="wrc-pwa-header">
				<div class="wrc-section-heading">
					<h2 class="wrc-section-title"><?php esc_html_e( 'Progressive Web App', 'foodord' ); ?></h2>
					<p class="wrc-card-sub"><?php esc_html_e( 'Let customers install your restaurant website as a fast, branded app on supported devices.', 'foodord' ); ?></p>
				</div>
				<div class="wrc-toggle-row">
					<label class="foodord-toggle-switch" for="foodord_pwa_enabled">
						<input type="checkbox" id="foodord_pwa_enabled" class="foodord-toggle-input" name="foodord_pwa_enabled" value="yes" aria-label="<?php echo esc_attr__( 'Enable the customer app', 'foodord' ); ?>" <?php checked( $enabled ); ?> />
						<span class="foodord-toggle-slider"></span>
					</label>
				</div>
			</div>
			<div class="wrc-pwa-content">
				<?php if ( is_string( $error ) && '' !== $error ) : ?>
					<div class="wrc-pwa-notice" role="alert"><?php echo esc_html( $error ); ?></div>
				<?php endif; ?>

				<div class="wrc-pwa-settings<?php echo esc_attr( $enabled ? '' : ' is-disabled' ); ?>" data-foodord-pwa-settings>
					<div class="wrc-pwa-grid">
						<div class="wrc-pwa-field">
							<label class="wrc-pwa-label" for="foodord_pwa_app_name"><?php esc_html_e( 'App name', 'foodord' ); ?></label>
							<input type="text" id="foodord_pwa_app_name" name="foodord_pwa_app_name" value="<?php echo esc_attr( $app_name ); ?>" maxlength="90" placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" />
						</div>
						<div class="wrc-pwa-field">
							<label class="wrc-pwa-label" for="foodord_pwa_short_name"><?php esc_html_e( 'Short name', 'foodord' ); ?></label>
							<input type="text" id="foodord_pwa_short_name" name="foodord_pwa_short_name" value="<?php echo esc_attr( $short_name ); ?>" maxlength="30" placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" />
							<p class="wrc-help"><?php esc_html_e( 'Used below the app icon on the home screen.', 'foodord' ); ?></p>
						</div>
						<div class="wrc-pwa-field wrc-pwa-field--wide">
							<label class="wrc-pwa-label" for="foodord_pwa_description"><?php esc_html_e( 'App description', 'foodord' ); ?></label>
							<input type="text" id="foodord_pwa_description" name="foodord_pwa_description" value="<?php echo esc_attr( $description ); ?>" maxlength="180" placeholder="<?php echo esc_attr( get_bloginfo( 'description' ) ); ?>" />
						</div>
						<div class="wrc-pwa-field">
							<label class="wrc-pwa-label" for="foodord_pwa_start_page_id"><?php esc_html_e( 'Start page', 'foodord' ); ?></label>
							<select id="foodord_pwa_start_page_id" name="foodord_pwa_start_page_id">
								<option value="0" <?php selected( 0, $start_page_id ); ?>><?php esc_html_e( 'Select a page', 'foodord' ); ?></option>
								<?php foreach ( $pages as $page ) : ?>
									<option value="<?php echo esc_attr( (string) $page->ID ); ?>" <?php selected( $start_page_id, $page->ID ); ?>><?php echo esc_html( $page->post_title ); ?></option>
								<?php endforeach; ?>
							</select>
						</div>
						<div class="wrc-pwa-field">
							<label class="wrc-pwa-label" for="foodord_pwa_install_prompt"><?php esc_html_e( 'Installation prompt', 'foodord' ); ?></label>
							<div class="foodord-toggle-row">
								<label class="foodord-toggle-switch" for="foodord_pwa_install_prompt">
								<input type="checkbox" id="foodord_pwa_install_prompt" class="foodord-toggle-input" name="foodord_pwa_install_prompt" value="yes" <?php checked( $install_prompt ); ?> />
									<span class="foodord-toggle-slider"></span>
								</label>
								<span class="foodord-toggle-label"><?php esc_html_e( 'Show install guidance to customers', 'foodord' ); ?></span>
							</div>
						</div>
					</div>

					<div class="wrc-pwa-branding">
						<?php
						$this->render_icon_control(
							'foodord_pwa_icon_id',
							__( 'App icon', 'foodord' ),
							__( 'Square image, at least 512 by 512 pixels. The WordPress Site Icon is used when empty.', 'foodord' ),
							$icon_id,
							$effective_icon_id
						);
						$this->render_icon_control(
							'foodord_pwa_maskable_icon_id',
							__( 'Maskable icon', 'foodord' ),
							__( 'Optional icon with safe padding for Android adaptive icon shapes.', 'foodord' ),
							$maskable_icon_id,
							$maskable_icon_id
						);
						?>
					</div>

					<div class="wrc-pwa-colors">
						<div class="wrc-pwa-field">
							<label class="wrc-pwa-label" for="foodord_pwa_theme_color"><?php esc_html_e( 'Theme color', 'foodord' ); ?></label>
							<input type="text" id="foodord_pwa_theme_color" name="foodord_pwa_theme_color" value="<?php echo esc_attr( $theme_color ); ?>" class="wr-color-picker" />
						</div>
						<div class="wrc-pwa-field">
							<label class="wrc-pwa-label" for="foodord_pwa_background_color"><?php esc_html_e( 'Launch background', 'foodord' ); ?></label>
							<input type="text" id="foodord_pwa_background_color" name="foodord_pwa_background_color" value="<?php echo esc_attr( $background_color ); ?>" class="wr-color-picker" />
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render one media-backed icon setting.
	 *
	 * @param string $field_id   Input ID and name.
	 * @param string $label      Visible field label.
	 * @param string $description Field help text.
	 * @param int    $value       Saved attachment ID.
	 * @param int    $preview_id  Preview attachment ID.
	 */
	private function render_icon_control( string $field_id, string $label, string $description, int $value, int $preview_id ): void {
		$preview = $preview_id > 0 ? wp_get_attachment_image_url( $preview_id, 'thumbnail' ) : '';
		?>
		<div class="wrc-pwa-icon-field" data-foodord-pwa-icon-field>
			<div class="wrc-pwa-icon-copy">
				<label for="<?php echo esc_attr( $field_id ); ?>"><?php echo esc_html( $label ); ?></label>
				<p class="wrc-help"><?php echo esc_html( $description ); ?></p>
			</div>
			<div class="wrc-pwa-icon-control">
				<button type="button" class="wrc-pwa-icon-preview" data-foodord-pwa-icon-preview data-foodord-pwa-preview-trigger aria-label="<?php echo esc_attr__( 'Select image', 'foodord' ); ?>">
					<?php if ( is_string( $preview ) && '' !== $preview ) : ?>
						<img src="<?php echo esc_url( $preview ); ?>" alt="" />
					<?php else : ?>
						<span aria-hidden="true">+</span>
					<?php endif; ?>
				</button>
				<input type="hidden" id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $field_id ); ?>" value="<?php echo esc_attr( (string) $value ); ?>" data-foodord-pwa-icon-input />
				<div class="wrc-pwa-icon-actions">
					<button type="button" class="wrc-pwa-icon-action wrc-pwa-icon-action--select" data-foodord-pwa-select-icon>
						<span class="dashicons dashicons-format-image" aria-hidden="true"></span>
						<?php esc_html_e( 'Select image', 'foodord' ); ?>
					</button>
					<button type="button" class="wrc-pwa-icon-action wrc-pwa-icon-action--remove" data-foodord-pwa-remove-icon<?php echo esc_attr( $value > 0 ? '' : ' hidden' ); ?>>
						<span class="dashicons dashicons-trash" aria-hidden="true"></span>
						<?php esc_html_e( 'Remove', 'foodord' ); ?>
					</button>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Limit a string without breaking multibyte text.
	 *
	 * @param string $value  Value to limit.
	 * @param int    $length Maximum character count.
	 */
	private function limit_text( string $value, int $length ): string {
		return function_exists( 'mb_substr' ) ? mb_substr( $value, 0, $length ) : substr( $value, 0, $length );
	}

	/**
	 * Return the current administrator's error transient key.
	 */
	private function get_error_transient_key(): string {
		return self::ERROR_TRANSIENT . '_' . get_current_user_id();
	}
}
