<?php

namespace Fifa\ConnectId\Sdk\Tms\Validators;

use Fifa\ConnectId\Sdk\Model\Transfer\DomesticTransferDeclaration;
use Fifa\ConnectId\Sdk\Model\Validation\DocumentValidator;
use Fifa\ConnectId\Sdk\Model\Validation\DocumentValidatorInterface;
use Fifa\ConnectId\Sdk\Model\Validation\PdfValidator;
use Fifa\ConnectId\Sdk\Model\Validation\PictureValidator;
use Fifa\ConnectId\Sdk\Registration\ValidationException;
use Fifa\ConnectId\Sdk\Util\Data\Transfer\SellOnFee;

class DomesticTransferDeclarationValidator
{
    /**
     * @var DocumentValidatorInterface[]
     */
    private static $validator;

    private static $instance;

    public static function getInstance(): DomesticTransferDeclarationValidator
    {
        if (self::$instance == null) self::$instance = new DomesticTransferDeclarationValidator();
        return self::$instance;
    }

    /**
     * DomesticTransferDeclarationValidator constructor.
     */
    private function __construct()
    {
        self::$validator = new DocumentValidator(new PdfValidator(), new PictureValidator());
    }

    /**
     * @param DomesticTransferDeclaration $domesticTransferDeclaration
     *
     * @throws ValidationException
     */
    public static function validate(DomesticTransferDeclaration $domesticTransferDeclaration)
    {
        PersonLocalValidator::validate($domesticTransferDeclaration->PersonLocal);

        self::validateIfNotNull($domesticTransferDeclaration->TransferCertificate);
        self::validateIfNotNull($domesticTransferDeclaration->TransferAgreement);

        if ($domesticTransferDeclaration->ResidencePermit != null) {
            self::validateIfNotNull($domesticTransferDeclaration->ResidencePermit->ResidencePermitDocument);
        }
        if ($domesticTransferDeclaration->WorkPermit != null) {
            self::validateIfNotNull($domesticTransferDeclaration->WorkPermit->WorkPermitDocument);
        }

        $fees = array_merge(
            $domesticTransferDeclaration->FixedTransferFee ?: [],
            $domesticTransferDeclaration->ConditionalTransferFee ?: [],
            $domesticTransferDeclaration->ReleaseBuyoutFee ?: []
        );
        if ($domesticTransferDeclaration->SellOnFee != SellOnFee::YES && empty($fees)) {
            throw new ValidationException("At least one fee (Sell-on, Fixed, Conditional or Buy-out) must be specified");
        }
    }

    /**
     * @throws ValidationException
     */
    private static function validateIfNotNull($document)
    {
        if ($document != null) {
            $result = self::$validator->validate($document->_content);
            if (!$result->isValid()) {
                throw new ValidationException($result->getMessage());
            }
        }
    }
}

