<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Dto;

use Ferienpass\CoreBundle\Entity\Host;
use Ferienpass\CoreBundle\Entity\PostalAddress;
use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber;
use Symfony\Component\DependencyInjection\Attribute\Exclude;
use Symfony\Component\Validator\Constraints as Assert;

#[Exclude]
class OrganizationDataDto
{
    public ?string $name = null;
    #[PhoneNumber(type: PhoneNumber::FIXED_LINE, defaultRegion: 'DE')]
    public ?string $phone = null;
    #[PhoneNumber(type: PhoneNumber::FIXED_LINE, defaultRegion: 'DE')]
    public ?string $fax = null;
    #[PhoneNumber(type: PhoneNumber::MOBILE, defaultRegion: 'DE')]
    public ?string $mobile = null;
    #[Assert\Email]
    public ?string $email = null;
    #[Assert\Url]
    public ?string $website = null;
    public ?string $street = null;
    public ?string $postalCode = null;
    public ?string $city = null;
    public ?string $country = null;
    public ?string $text = null;

    public function fromEntity(Host $host)
    {
        $this->name = $host->getName();
        $this->phone = $host->getPhone();
        $this->fax = $host->getFax();
        $this->mobile = $host->getMobile();
        $this->email = $host->getEmail();
        $this->website = $host->getWebsite();
        $this->text = $host->getText();

        $postalAddress = $host->getPostalAddresses()->first();
        if (false === $postalAddress) {
            return;
        }

        $this->street = $postalAddress->getStreet();
        $this->postalCode = $postalAddress->getPostalCode();
        $this->city = $postalAddress->getCity();
        $this->country = $postalAddress->getCountry();
    }

    public function toEntity(Host $host): void
    {
        $host->setName($this->name);
        $host->setPhone($this->phone);
        $host->setFax($this->fax);
        $host->setMobile($this->mobile);
        $host->setEmail($this->email);
        $host->setWebsite($this->website);
        $host->setText($this->text);

        if (false === $host->getPostalAddresses()->first()) {
            $host->getPostalAddresses()->add(new PostalAddress());
        }

        $postalAddress = $host->getPostalAddresses()->first();
        $postalAddress->setStreet($this->street);
        $postalAddress->setPostalCode($this->postalCode);
        $postalAddress->setCity($this->city);
        $postalAddress->setCountry($this->country);
    }
}
