<?php
/**
 * Validator for ProductsFormHandler.
 *
 * @package Ilabs\Firevert\Modules\PowerWidget\Services\Form\Validator
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PowerWidget\Services\Form\Validator;

use Ilabs\Firevert\Core\Form\Validation\FormValidator;

/**
 * Class ProductsFormValidator
 *
 * Validates form fields defined in ProductsFormHandler.
 */
class ProductsFormValidator extends FormValidator {

	/**
	 * ProductsFormValidator constructor.
	 *
	 * @param array<string, string> $field_types Field definitions passed from FormHandler.
	 */
	public function __construct( array $field_types ) {
		$this->set_field_types( $field_types );

		$this->set_custom_rules(
			array(
				'firevert_power_widget_products_button_text' => array(
					function ( $value, $data ) {
						return ! empty( $data['firevert_power_widget_products_show_button'] ) && empty( $value )
							? __( 'Button text is required if button is enabled.', 'firevert' )
							: null;
					},
				),

				'firevert_power_widget_products_selection_mode' => array(
					function ( $value ) {
						if ( empty( $value ) ) {
							return __( 'Selection mode is required.', 'firevert' );
						}
						if ( ! in_array( $value, array( 'sale', 'selected' ), true ) ) {
							return __( 'Invalid selection mode.', 'firevert' );
						}
						return null;
					},
				),

				'firevert_power_widget_products_selected' => array(
					function ( $value, $data ) {
						$mode = $data['firevert_power_widget_products_selection_mode'] ?? null;

						if ( 'selected' !== $mode ) {
							return null;
						}

						if ( empty( $value ) || ! is_array( $value ) ) {
							return __( 'You must select at least one product.', 'firevert' );
						}

						return null;
					},
				),
			)
		);
	}
}
