<?php
/**
 * Handles form data and saving for PromoTimeWidget Product Targeting.
 *
 * @package Ilabs\Firevert\Modules\PromoTimeWidget\Services\Form
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PromoTimeWidget\Services\Form;

use Ilabs\Firevert\Core\Form\Validation\FormValidatorInterface;
use Ilabs\Firevert\Core\Settings\Form\DefaultSettingsProviderInterface;
use Ilabs\Firevert\Modules\PromoTimeWidget\Services\Form\Validator\ProductsFormValidator;

/**
 * Class ProductsFormHandler
 *
 * Handles form fields for product/category inclusion and exclusion.
 */
class ProductsFormHandler extends AbstractFormHandler implements DefaultSettingsProviderInterface {

	/**
	 * Current section slug.
	 *
	 * @var string
	 */
	protected string $section_slug = 'products';

	/**
	 * Fields and their expected types.
	 *
	 * @var array<string, string>
	 */
	protected array $fields = array(
		'firevert_promo_time_widget_all_products'        => 'bool',
		'firevert_promo_time_widget_product_categories'  => 'array',
		'firevert_promo_time_widget_selected_products'   => 'array',
		'firevert_promo_time_widget_excluded_categories' => 'array',
		'firevert_promo_time_widget_excluded_products'   => 'array',
	);

	/**
	 * Returns sanitized form data for view rendering.
	 *
	 * @return array<string, mixed>
	 */
	public function get_data(): array {
		$data = $this->get_all_field_data();

		$data['firevert_promo_time_widget_product_categories'] = is_array( $data['firevert_promo_time_widget_product_categories'] )
			? $data['firevert_promo_time_widget_product_categories']
			: array();

		$data['firevert_promo_time_widget_selected_products'] = is_array( $data['firevert_promo_time_widget_selected_products'] )
			? $data['firevert_promo_time_widget_selected_products']
			: array();

		$data['firevert_promo_time_widget_excluded_categories'] = is_array( $data['firevert_promo_time_widget_excluded_categories'] )
			? $data['firevert_promo_time_widget_excluded_categories']
			: array();

		$data['firevert_promo_time_widget_excluded_products'] = is_array( $data['firevert_promo_time_widget_excluded_products'] )
			? $data['firevert_promo_time_widget_excluded_products']
			: array();

		return array_merge(
			array( 'post' => $this->post ),
			$data
		);
	}

	/**
	 * Returns section form validator.
	 *
	 * @return FormValidatorInterface
	 */
	protected function get_validator(): FormValidatorInterface {
		return new ProductsFormValidator( $this->fields );
	}

	/**
	 * Returns default settings data.
	 *
	 * @return array<string, mixed>
	 */
	public function get_default_settings(): array {
		return array(
			'firevert_promo_time_widget_all_products'      => true,
			'firevert_promo_time_widget_product_categories' => array(),
			'firevert_promo_time_widget_selected_products' => array(),
			'firevert_promo_time_widget_excluded_categories' => array(),
			'firevert_promo_time_widget_excluded_products' => array(),
		);
	}
}
