<?php
/**
 * Ajustes de impresión de etiquetas de producción (HTML / navegador).
 *
 * @package Logistica
 */

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

/**
 * Configuración de tamaño y logo para etiquetas imprimibles.
 */
class Logistica_Label_Print {

	public const OPTION_WIDTH_MM        = 'logistica_label_width_mm';
	public const OPTION_HEIGHT_MM       = 'logistica_label_height_mm';
	public const OPTION_LOGO_MODE       = 'logistica_label_logo_mode';
	public const OPTION_LOGO_URL        = 'logistica_label_logo_url';
	public const OPTION_LOGO_TEXT_LINE1 = 'logistica_label_logo_text_line1';
	public const OPTION_LOGO_TEXT_LINE2 = 'logistica_label_logo_text_line2';
	public const OPTION_ALLOW_BLANK_CAJA_NUM = 'logistica_label_allow_blank_caja_num';

	/**
	 * URL del logo SVG incluido en el plugin.
	 *
	 * @return string
	 */
	public static function default_logo_url() {
		return LOGISTICA_PLUGIN_URL . 'assets/images/label-logo-default.svg';
	}

	/**
	 * @return array<string, string|int>
	 */
	public static function defaults() {
		return array(
			self::OPTION_WIDTH_MM        => 100,
			self::OPTION_HEIGHT_MM       => 100,
			self::OPTION_LOGO_MODE       => 'image',
			self::OPTION_LOGO_URL        => self::default_logo_url(),
			self::OPTION_LOGO_TEXT_LINE1 => '',
			self::OPTION_LOGO_TEXT_LINE2 => '',
			self::OPTION_ALLOW_BLANK_CAJA_NUM => 0,
		);
	}

	/**
	 * @param mixed $mode Modo de logo.
	 * @return string
	 */
	public static function sanitize_logo_mode( $mode ) {
		return 'image' === (string) $mode ? 'image' : 'text';
	}

	/**
	 * @return array<string, string|int>
	 */
	public static function get_settings() {
		$defaults = self::defaults();
		$stored   = get_option( 'logistica_label_print_settings', array() );

		if ( ! is_array( $stored ) ) {
			$stored = array();
		}

		$width  = (int) ( $stored[ self::OPTION_WIDTH_MM ] ?? $defaults[ self::OPTION_WIDTH_MM ] );
		$height = (int) ( $stored[ self::OPTION_HEIGHT_MM ] ?? $defaults[ self::OPTION_HEIGHT_MM ] );

		if ( $width < 50 || $width > 200 ) {
			$width = (int) $defaults[ self::OPTION_WIDTH_MM ];
		}

		if ( $height < 50 || $height > 250 ) {
			$height = (int) $defaults[ self::OPTION_HEIGHT_MM ];
		}

		$logo_mode = self::sanitize_logo_mode( $stored[ self::OPTION_LOGO_MODE ] ?? $defaults[ self::OPTION_LOGO_MODE ] );
		$logo_url  = esc_url_raw( (string) ( $stored[ self::OPTION_LOGO_URL ] ?? '' ) );

		if ( '' === $logo_url ) {
			$logo_url = (string) $defaults[ self::OPTION_LOGO_URL ];
		}

		return array(
			self::OPTION_WIDTH_MM        => $width,
			self::OPTION_HEIGHT_MM       => $height,
			self::OPTION_LOGO_MODE       => $logo_mode,
			self::OPTION_LOGO_URL        => $logo_url,
			self::OPTION_LOGO_TEXT_LINE1 => sanitize_text_field( (string) ( $stored[ self::OPTION_LOGO_TEXT_LINE1 ] ?? $defaults[ self::OPTION_LOGO_TEXT_LINE1 ] ) ),
			self::OPTION_LOGO_TEXT_LINE2 => sanitize_text_field( (string) ( $stored[ self::OPTION_LOGO_TEXT_LINE2 ] ?? $defaults[ self::OPTION_LOGO_TEXT_LINE2 ] ) ),
			self::OPTION_ALLOW_BLANK_CAJA_NUM => ! empty( $stored[ self::OPTION_ALLOW_BLANK_CAJA_NUM ] ) ? 1 : 0,
		);
	}

	/**
	 * @param array<string, mixed> $raw POST settings.
	 * @param bool                 $allow_admin_options Whether admin-only options may change.
	 * @return void
	 */
	public static function save_settings( $raw, $allow_admin_options = false ) {
		if ( ! is_array( $raw ) ) {
			$raw = array();
		}

		$defaults = self::defaults();
		$current  = self::get_settings();
		$width    = array_key_exists( self::OPTION_WIDTH_MM, $raw )
			? (int) $raw[ self::OPTION_WIDTH_MM ]
			: (int) $current[ self::OPTION_WIDTH_MM ];
		$height   = array_key_exists( self::OPTION_HEIGHT_MM, $raw )
			? (int) $raw[ self::OPTION_HEIGHT_MM ]
			: (int) $current[ self::OPTION_HEIGHT_MM ];
		$logo_mode = array_key_exists( self::OPTION_LOGO_MODE, $raw )
			? self::sanitize_logo_mode( $raw[ self::OPTION_LOGO_MODE ] )
			: (string) $current[ self::OPTION_LOGO_MODE ];
		$logo_url  = array_key_exists( self::OPTION_LOGO_URL, $raw )
			? esc_url_raw( (string) $raw[ self::OPTION_LOGO_URL ] )
			: (string) $current[ self::OPTION_LOGO_URL ];
		$logo_line1 = array_key_exists( self::OPTION_LOGO_TEXT_LINE1, $raw )
			? sanitize_text_field( (string) $raw[ self::OPTION_LOGO_TEXT_LINE1 ] )
			: (string) $current[ self::OPTION_LOGO_TEXT_LINE1 ];
		$logo_line2 = array_key_exists( self::OPTION_LOGO_TEXT_LINE2, $raw )
			? sanitize_text_field( (string) $raw[ self::OPTION_LOGO_TEXT_LINE2 ] )
			: (string) $current[ self::OPTION_LOGO_TEXT_LINE2 ];
		$allow_blank_caja = (int) ( $current[ self::OPTION_ALLOW_BLANK_CAJA_NUM ] ?? 0 );
		// $allow_admin_options ya viene validado por el caller (capacidad manage_config).
		// No revalidar con is_admin()/$_GET['config']: en admin-ajax eso puede fallar según el contexto.
		if ( $allow_admin_options ) {
			$allow_blank_caja = array_key_exists( self::OPTION_ALLOW_BLANK_CAJA_NUM, $raw )
				? ( ! empty( $raw[ self::OPTION_ALLOW_BLANK_CAJA_NUM ] ) ? 1 : 0 )
				: (int) ( $current[ self::OPTION_ALLOW_BLANK_CAJA_NUM ] ?? 0 );
		}

		if ( '' === $logo_url ) {
			$logo_url = (string) $defaults[ self::OPTION_LOGO_URL ];
		}

		update_option(
			'logistica_label_print_settings',
			array(
				self::OPTION_WIDTH_MM        => max( 50, min( 200, $width ) ),
				self::OPTION_HEIGHT_MM       => max( 50, min( 250, $height ) ),
				self::OPTION_LOGO_MODE       => $logo_mode,
				self::OPTION_LOGO_URL        => $logo_url,
				self::OPTION_LOGO_TEXT_LINE1 => $logo_line1,
				self::OPTION_LOGO_TEXT_LINE2 => $logo_line2,
				self::OPTION_ALLOW_BLANK_CAJA_NUM => $allow_blank_caja ? 1 : 0,
			),
			false
		);
	}

	/**
	 * Config expuesta al JS de impresión.
	 *
	 * @return array<string, mixed>
	 */
	public static function client_config() {
		$settings = self::get_settings();

		return array(
			'widthMm'        => (int) $settings[ self::OPTION_WIDTH_MM ],
			'heightMm'       => (int) $settings[ self::OPTION_HEIGHT_MM ],
			'logoMode'       => (string) $settings[ self::OPTION_LOGO_MODE ],
			'logoUrl'        => (string) $settings[ self::OPTION_LOGO_URL ],
			'logoTextLine1'  => (string) $settings[ self::OPTION_LOGO_TEXT_LINE1 ],
			'logoTextLine2'  => (string) $settings[ self::OPTION_LOGO_TEXT_LINE2 ],
			'allowBlankCajaNum' => ! empty( $settings[ self::OPTION_ALLOW_BLANK_CAJA_NUM ] ),
			'defaultLogoUrl' => self::default_logo_url(),
			'cssUrl'         => LOGISTICA_PLUGIN_URL . 'assets/css/label-print.css',
			'logoHistory'    => Logistica_Label_Logo_History::client_format(),
		);
	}

	/**
	 * Registra CSS/JS de etiquetas (admin y frontend).
	 *
	 * @return void
	 */
	public static function register_assets() {
		wp_enqueue_style(
			'logistica-label-print',
			LOGISTICA_PLUGIN_URL . 'assets/css/label-print.css',
			array( 'logistica-admin' ),
			logistica_asset_version( 'assets/css/label-print.css' )
		);

		wp_enqueue_script(
			'logistica-jsbarcode',
			LOGISTICA_PLUGIN_URL . 'assets/js/vendor/jsbarcode.all.min.js',
			array(),
			logistica_asset_version( 'assets/js/vendor/jsbarcode.all.min.js' ),
			true
		);

		wp_enqueue_script(
			'logistica-label-print',
			LOGISTICA_PLUGIN_URL . 'assets/js/label-print.js',
			array( 'logistica-jsbarcode' ),
			logistica_asset_version( 'assets/js/label-print.js' ),
			true
		);
	}
}
