<?php

namespace Planaday\Config\OptionGroups\Payment;

use Planaday\Platform\PlatformAbstraction\LocalizationController;
use Planaday\Utility\DataFilters\InvalidFieldsException;
use Planaday\Utility\DataFilters\TypeValidator;
use Planaday\Utility\Debug\Log\Logging;

class PaymentOptionsValidator {
	use Logging;

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

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

	public function __construct( TypeValidator $typeValidator, LocalizationController $translator) {
		$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 betaling opties is met ongeldige data ingevuld.'
				);
			}

			$output = $errors;
			return false;
		}

		if (!empty($data[PaymentOptionsEnum::PAYMENT_ACTIVE])) {
			if (($data[PaymentOptionsEnum::TEST_PAYMENT_ACTIVE] ?? true) && empty($data[PaymentOptionsEnum::MOLLIE_API_KEY_TEST])) {
				$errors[PaymentOptionsEnum::PAYMENT_ACTIVE] = $errors[PaymentOptionsEnum::TEST_PAYMENT_ACTIVE] = [false];
				$errors[PaymentOptionsEnum::MOLLIE_API_KEY_TEST] = $tr->translate('De API key voor test betalingen is verplicht als test betalingen actief zijn.');
			}

			if (!($data[PaymentOptionsEnum::TEST_PAYMENT_ACTIVE] ?? true) && empty($data[PaymentOptionsEnum::MOLLIE_API_KEY_LIVE])) {
				$errors[PaymentOptionsEnum::PAYMENT_ACTIVE] = $errors[PaymentOptionsEnum::TEST_PAYMENT_ACTIVE] = [false];
				$errors[PaymentOptionsEnum::MOLLIE_API_KEY_LIVE] = $tr->translate('De API key voor live betalingen is verplicht als live betalingen actief zijn.');
			}
		}

		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 = [
			PaymentOptionsEnum::PAYMENT_ACTIVE,
			PaymentOptionsEnum::TEST_PAYMENT_ACTIVE,
			PaymentOptionsEnum::CANCEL_BOOKING_IF_NO_PAYMENT,
			PaymentOptionsEnum::ALLOW_BULK_PAYMENT
		];

		$string = [
			PaymentOptionsEnum::PAYMENT_NOTICE,
			PaymentOptionsEnum::MOLLIE_API_KEY_LIVE,
			PaymentOptionsEnum::MOLLIE_API_KEY_TEST
		];

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