<?php

namespace Planaday\Config\OptionGroups\Booking\Form\Company;

use Planaday\Config\OptionGroups\Booking\Form\Company\Invoice\InvoiceOptionsValidator;
use Planaday\Platform\PlatformAbstraction\LocalizationController;
use Planaday\Utility\DataFilters\InvalidFieldsException;
use Planaday\Utility\DataFilters\TypeValidator;
use Planaday\Utility\Debug\Log\Logging;

class CompanyOptionsValidator {
	use Logging;

	/** @var TypeValidator */
	protected $typeValidator;

	/** @var LocalizationController */
	protected $translator;

	/** @var InvoiceOptionsValidator */
	private $invoiceOptionsValidator;

	public function __construct(
		TypeValidator $typeValidator,
		LocalizationController $translator,
		InvoiceOptionsValidator $invoiceOptionsValidator
	) {
		$this->invoiceOptionsValidator  = $invoiceOptionsValidator;
		$this->typeValidator            = $typeValidator;
		$this->translator               = $translator;
	}

	/**
	 * @param array $data
	 * @param array|null $output if valid, clean data is returned here. if not, errors will be returned here
	 *
	 * @return bool true if valid, false if not
	 */
	public function validate( array $data, ?array &$output): bool {
		$errors = [];
		$tr = $this->translator;

		try {
			$data = $this->getSafeData( $data );
		} catch ( InvalidFieldsException $e ) {
			foreach ( $e->getInvalidFields() as $field => $fieldException ) {
				$errors[ $field ] = $tr->translate(
					'Het ' . strtolower($field) . ' veld bij de boeking company opties is met ongeldige data ingevuld.'
				);
			}

			$output = $errors;
			return false;
		}

		if ( ($data[ CompanyOptionsEnum::PHONE_NUMBER_REQUIRED ] ?? false) && !($data[CompanyOptionsEnum::ASK_PHONE_NUMBER] ?? false)) {
			$errors[ CompanyOptionsEnum::ASK_PHONE_NUMBER ]  = [false];
			$errors[ CompanyOptionsEnum::PHONE_NUMBER_REQUIRED ] = $tr->translate(
				'Als het bedrijfsnummer verplicht is moet het telefoonnummer ook gevraagd worden.'
			);
		}

		if (!$this->invoiceOptionsValidator->validate($data[CompanyOptionsEnum::INVOICE] ?? [], $invoiceOutput)) {
			$errors[CompanyOptionsEnum::INVOICE . '-isValid'] = $tr->translate('De invoice opties zijn niet geldig');
			$errors[CompanyOptionsEnum::INVOICE] = $invoiceOutput;
		} else {
			$data[CompanyOptionsEnum::INVOICE] = $invoiceOutput;
		}

		if ( count( $errors ) > 0 ) {
			$output = $errors;
			$this->logWarning("data is not valid", $errors);
			return false;
		}

		$output = $data;
		return true;
	}

	/**
	 * @param array $data
	 *
	 * @return array
	 * @throws InvalidFieldsException
	 */
	private function getSafeData(array $data): array {
		$tv = $this->typeValidator;

		$bool = [
			CompanyOptionsEnum::AS_COMPANY_DEFAULT,
			CompanyOptionsEnum::ALLOW_COMPANIES,
			CompanyOptionsEnum::ASK_PHONE_NUMBER,
			CompanyOptionsEnum::PHONE_NUMBER_REQUIRED,
		];

		$arrays = [
			CompanyOptionsEnum::INVOICE
		];

		return $tv->getSafeData($data, [], $arrays, $bool);
	}

}