<?php

/**

 * Admin UI for manual Grundpreis meta key mapping.

 *

 * @package PhoenixWP\PriceLabels

 */



declare(strict_types=1);



namespace PhoenixWP\PriceLabels\Admin;



use PhoenixWP\PriceLabels\Compliance\Unit_Price_Settings;



defined( 'ABSPATH' ) || exit;



/**

 * Renders and saves unit price settings on the labels screen.

 */

final class Unit_Price_Settings_Admin {



	public const ACTION_SAVE = 'phoenix_wp_price_labels_unit_price_settings';



	private static ?self $instance = null;



	public static function instance(): self {

		if ( null === self::$instance ) {

			self::$instance = new self();

		}



		return self::$instance;

	}



	private function __construct() {}



	private function __clone() {}



	/**

	 * Registers admin hooks.

	 */

	public function init(): void {

		add_action( 'admin_post_' . self::ACTION_SAVE, array( $this, 'handle_save' ) );

	}



	/**

	 * Renders unit price settings nested under the label fields block.

	 */

	public function render_nested_panel(): void {

		$settings = Unit_Price_Settings::get();



		echo '<div class="phoenix-price-labels-for-woocommerce-unit-price-panel" hidden>';

		echo '<p class="phoenix-price-labels-for-woocommerce-unit-price-panel__title"><strong>' . esc_html__( 'Unit price settings', 'phoenix-price-labels-for-woocommerce' ) . '</strong></p>';

		echo '<p class="description">' . esc_html__( 'By default, unit prices are read from German Market, Germanized, or common product meta fields. Configure custom meta keys when your shop stores unit price data differently.', 'phoenix-price-labels-for-woocommerce' ) . '</p>';



		wp_nonce_field( self::ACTION_SAVE, '_phoenix_wp_price_labels_unit_price_nonce' );



		echo '<table class="form-table phoenix-price-labels-for-woocommerce-unit-price-panel__table" role="presentation">';

		echo '<tr><th scope="row"><label for="phoenix_wp_price_labels_unit_price_mode">' . esc_html__( 'Source mode', 'phoenix-price-labels-for-woocommerce' ) . '</label></th><td>';

		echo '<select name="unit_price_settings[mode]" id="phoenix_wp_price_labels_unit_price_mode">';

		echo '<option value="auto"' . selected( $settings['mode'], 'auto', false ) . '>' . esc_html__( 'Auto (plugins + custom meta fallback)', 'phoenix-price-labels-for-woocommerce' ) . '</option>';

		echo '<option value="manual_only"' . selected( $settings['mode'], 'manual_only', false ) . '>' . esc_html__( 'Custom meta keys only', 'phoenix-price-labels-for-woocommerce' ) . '</option>';

		echo '</select></td></tr>';



		$fields = array(

			'formatted_meta'      => __( 'Preformatted text meta key', 'phoenix-price-labels-for-woocommerce' ),

			'unit_price_meta'     => __( 'Unit price meta key', 'phoenix-price-labels-for-woocommerce' ),

			'base_amount_meta'    => __( 'Reference quantity meta key', 'phoenix-price-labels-for-woocommerce' ),

			'product_amount_meta' => __( 'Product quantity meta key', 'phoenix-price-labels-for-woocommerce' ),

			'unit_meta'           => __( 'Unit label meta key', 'phoenix-price-labels-for-woocommerce' ),

		);



		foreach ( $fields as $key => $label ) {

			printf(

				'<tr><th scope="row"><label for="phoenix_wp_price_labels_%1$s">%2$s</label></th><td><input type="text" class="regular-text code" name="unit_price_settings[%1$s]" id="phoenix_wp_price_labels_%1$s" value="%3$s" placeholder="_unit_price" /></td></tr>',

				esc_attr( $key ),

				esc_html( $label ),

				esc_attr( $settings[ $key ] )

			);

		}



		echo '</table>';



		echo '<p class="description">' . esc_html__( 'German Market / Germanized defaults: _unit, _unit_base, _unit_product, _unit_price. Leave custom fields empty to rely on plugin detection only.', 'phoenix-price-labels-for-woocommerce' ) . '</p>';

		echo '<p class="submit" style="margin-top:0.5rem;padding-bottom:0;">';

		echo '<button type="submit" class="button button-secondary" name="action" value="' . esc_attr( self::ACTION_SAVE ) . '">';

		echo esc_html__( 'Save unit price settings', 'phoenix-price-labels-for-woocommerce' );

		echo '</button></p>';

		echo '</div>';

	}



	/**

	 * Saves settings from admin POST.

	 */

	public function handle_save(): void {

		if ( ! current_user_can( 'manage_woocommerce' ) ) {

			wp_die( esc_html__( 'Permission denied.', 'phoenix-price-labels-for-woocommerce' ) );

		}



		check_admin_referer( self::ACTION_SAVE, '_phoenix_wp_price_labels_unit_price_nonce' );

		$request = filter_input_array( INPUT_POST, FILTER_UNSAFE_RAW );
		if ( ! is_array( $request ) ) {
			$request = array();
		}

		$input = isset( $request['unit_price_settings'] ) && is_array( $request['unit_price_settings'] )
			? Unit_Price_Settings::sanitize( $request['unit_price_settings'] )
			: array();

		Unit_Price_Settings::save( $input );

		Generator_Form_State::capture_from_request( $request );

		wp_safe_redirect(

			add_query_arg(

				'phoenix_wp_price_labels_saved',

				'unit_price',

				admin_url( 'admin.php?page=' . Labels_Admin::PAGE_SLUG )

			)

		);

		exit;

	}

}


