<?php

namespace Devikit\Ifirma;

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

/**
 * Lump Sum Product Fields
 * Adds lump sum (ryczałt) field to products (FREE).
 */
class LumpSumProductFields {

	const LUMP_SUM_META_KEY = '_ifirma_lump_sum';

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'woocommerce_product_options_general_product_data', [ $this, 'add_lump_sum_field' ] );
		add_action( 'woocommerce_process_product_meta', [ $this, 'save_lump_sum_field' ] );

		add_action( 'woocommerce_product_after_variable_attributes', [ $this, 'add_lump_sum_field_variation' ], 10, 3 );
		add_action( 'woocommerce_save_product_variation', [ $this, 'save_lump_sum_field_variation' ], 10, 2 );
	}

	/**
	 * Get available lump sum options.
	 *
	 * @return array
	 */
	private function get_lump_sum_options() {
		return [
			'empty' => __( 'Select...', 'invoicing-integration-for-ifirma-and-woocommerce' ),
			'3'     => '3%',
			'5.5'   => '5,5%',
			'8.5'   => '8,5%',
			'10'    => '10%',
			'12'    => '12%',
			'12.5'  => '12,5%',
			'14'    => '14%',
			'15'    => '15%',
			'17'    => '17%',
		];
	}

	/**
	 * Add lump sum field to simple/variable product.
	 */
	public function add_lump_sum_field() {
		global $post;

		$settings = get_option( 'devikit_ifirma_settings', [] );
		$lump_sum_enable = isset( $settings['lump_sum_enable'] ) && $settings['lump_sum_enable'] === 'yes';
		if ( ! $lump_sum_enable ) {
			return;
		}

		$value = get_post_meta( $post->ID, self::LUMP_SUM_META_KEY, true );

		echo '<div class="options_group">';

		woocommerce_wp_select( [
			'id'          => self::LUMP_SUM_META_KEY,
			'label'       => __( 'Lump Sum', 'invoicing-integration-for-ifirma-and-woocommerce' ),
			'desc_tip'    => true,
			'description' => __( 'Select lump sum rate for this product. If not set, the default rate from settings will be used.', 'invoicing-integration-for-ifirma-and-woocommerce' ),
			'value'       => $value,
			'options'     => $this->get_lump_sum_options(),
		] );

		echo '</div>';
	}

	/**
	 * Save lump sum field for simple/variable product.
	 *
	 * @param int $post_id Product ID.
	 */
	public function save_lump_sum_field( $post_id ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce handles nonce verification for product save.
		if ( isset( $_POST[ self::LUMP_SUM_META_KEY ] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce handles nonce verification for product save.
			$value = sanitize_text_field( wp_unslash( $_POST[ self::LUMP_SUM_META_KEY ] ) );
			update_post_meta( $post_id, self::LUMP_SUM_META_KEY, $value );
		}
	}

	/**
	 * Add lump sum field to product variation.
	 */
	public function add_lump_sum_field_variation( $loop, $variation_data, $variation ) {
		$settings = get_option( 'devikit_ifirma_settings', [] );
		$lump_sum_enable = isset( $settings['lump_sum_enable'] ) && $settings['lump_sum_enable'] === 'yes';
		if ( ! $lump_sum_enable ) {
			return;
		}

		$value = get_post_meta( $variation->ID, self::LUMP_SUM_META_KEY, true );
		$options = $this->get_lump_sum_options();
		?>
		<p class="form-row form-row-full">
			<label for="<?php echo esc_attr( self::LUMP_SUM_META_KEY . '_' . $loop ); ?>"><?php esc_html_e( 'Lump Sum', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?></label>
			<select id="<?php echo esc_attr( self::LUMP_SUM_META_KEY . '_' . $loop ); ?>" name="<?php echo esc_attr( self::LUMP_SUM_META_KEY ); ?>[<?php echo esc_attr( $loop ); ?>]">
				<?php foreach ( $options as $opt_value => $label ) : ?>
					<option value="<?php echo esc_attr( $opt_value ); ?>" <?php selected( $value, $opt_value ); ?>><?php echo esc_html( $label ); ?></option>
				<?php endforeach; ?>
			</select>
			<span class="description"><?php esc_html_e( 'Select lump sum rate for this variation. If not set, the default rate from settings will be used.', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?></span>
		</p>
		<?php
	}

	/**
	 * Save lump sum field for variation.
	 */
	public function save_lump_sum_field_variation( $variation_id, $loop ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce handles nonce verification for product save.
		if ( isset( $_POST[ self::LUMP_SUM_META_KEY ][ $loop ] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce handles nonce verification for product save.
			$value = sanitize_text_field( wp_unslash( $_POST[ self::LUMP_SUM_META_KEY ][ $loop ] ) );
			update_post_meta( $variation_id, self::LUMP_SUM_META_KEY, $value );
		}
	}

	/**
	 * Get lump sum rate for product/variation or fallback to default.
	 *
	 * @param \WC_Product $product Product.
	 * @param int|null    $variation_id Variation ID if applicable.
	 * @param string      $default_value Default from settings (e.g. 'empty', '8.5').
	 * @return string
	 */
	public static function get_product_lump_sum( $product, $variation_id = null, $default_value = 'empty' ) {
		if ( ! $product ) {
			return '';
		}

		if ( $variation_id ) {
			$variation_value = get_post_meta( $variation_id, self::LUMP_SUM_META_KEY, true );
			if ( ! empty( $variation_value ) && $variation_value !== 'empty' ) {
				return $variation_value;
			}
		}

		$product_value = get_post_meta( $product->get_id(), self::LUMP_SUM_META_KEY, true );
		if ( ! empty( $product_value ) && $product_value !== 'empty' ) {
			return $product_value;
		}

		if ( ! empty( $default_value ) && $default_value !== 'empty' ) {
			return $default_value;
		}

		return '';
	}
}

