<?php

namespace Planaday\Entities\Booking\Validators;

use Planaday\Config\Booking\Form\Company\Invoice\InvoiceSettings;
use Planaday\Entities\Booking\DTO\Address;
use Planaday\Entities\Booking\DTO\BookingInvoice;
use Planaday\Entities\Booking\PostRequest\BookingInvoiceFieldEnum;
use Planaday\Platform\PlatformAbstraction\LocalizationController;
use Planaday\Utility\DataFilters\AdvancedValidatorFactory;
use Planaday\Utility\DataFilters\InvalidException;
use Planaday\Utility\DataFilters\TypeValidator;

class BookingInvoiceValidator {
	public function __construct(
		protected LocalizationController $localisationService,
		protected InvoiceSettings $invoiceSettings,
		protected TypeValidator $typeValidator,
		protected AdvancedValidatorFactory $advancedValidatorFactory,
		protected BookingAddressValidator $addressValidator
	) {}

	public function getFromPost( array $postData ): BookingInvoice|array {
		$t      = $this->localisationService;
		$type   = $this->typeValidator;
		$errors = [];


		try {
			$email = $type->str($postData[BookingInvoiceFieldEnum::EMAIL] ?? null);
		} catch (InvalidException ) {
			$errors[BookingInvoiceFieldEnum::EMAIL] = $t->translate('Factuur email is niet geldig');
		}
		try {
			$addressArray = $type->array($postData[BookingInvoiceFieldEnum::ADDRESS] ?? null);
		} catch (InvalidException ) {
			$errors[BookingInvoiceFieldEnum::ADDRESS] = $t->translate('Factuuradres is niet geldig');
		}

		if (empty($email) && $this->invoiceSettings->isEmailRequired() && $this->invoiceSettings->isAskForEmail())
			$errors[BookingInvoiceFieldEnum::EMAIL] = $t->translate('Factuur email is verplicht bij de factuur informatie');
		if (!empty($email) && !$this->advancedValidatorFactory->isEmail($email))
			$errors[BookingInvoiceFieldEnum::EMAIL] = $t->translate('Factuur email is geen geldig email adres');

		if (!empty($addressArray)){
			$address = $this->addressValidator->getFromPost( $addressArray, 'factuur', false);
			if ( !$address instanceof Address ) {
				$errors[BookingInvoiceFieldEnum::ADDRESS] = $address;
			}
		}

		if ( count( $errors ) > 0 ) {
			return $errors;
		}

		return (new BookingInvoice())
			->setEmail($email ?? null)
			->setAddress($address ?? null);
	}
}