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

declare( strict_types=1 );

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

use Ilabs\Firevert\Core\Form\Validation\FormValidatorInterface;
use Ilabs\Firevert\Core\Settings\Form\DefaultSettingsProviderInterface;
use Ilabs\Firevert\Modules\SpectatorViews\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_spectator_views_all_products'        => 'bool',
		'firevert_spectator_views_product_categories'  => 'array',
		'firevert_spectator_views_selected_products'   => 'array',
		'firevert_spectator_views_excluded_categories' => 'array',
		'firevert_spectator_views_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_spectator_views_product_categories'] = is_array( $data['firevert_spectator_views_product_categories'] )
			? $data['firevert_spectator_views_product_categories']
			: array();

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

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

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

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

	/**
	 * Returns default settings data.
	 *
	 * @return array<string, mixed>
	 */
	public function get_default_settings(): array {
		return array(
			'firevert_spectator_views_all_products'        => true,
			'firevert_spectator_views_product_categories'  => array(),
			'firevert_spectator_views_selected_products'   => array(),
			'firevert_spectator_views_excluded_categories' => array(),
			'firevert_spectator_views_excluded_products'   => array(),
		);
	}

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