<?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 Doctrine\Common\Collections\Collection;
use Ferienpass\CoreBundle\Entity\Debtor;
use Ferienpass\CoreBundle\Entity\Payment;
use Ferienpass\CoreBundle\Entity\PaymentItem;
use Ferienpass\CoreBundle\Entity\PostalAddress;
use Symfony\Component\Validator\Constraints as Assert;

class BillingAddressDto
{
    #[Assert\NotBlank]
    public ?string $address = null;

    #[Assert\Email]
    public ?string $email = null;

    public bool $paid = false;

    /** @var Collection<PaymentItem> */
    public Collection $items;

    public static function fromDebtor(Debtor $debtor): self
    {
        $self = new self();

        $user = $debtor->getUser();
        if (!$user instanceof \Ferienpass\CoreBundle\Entity\User) {
            return $self;
        }

        /** @var PostalAddress|false $postalAddress */
        if ($postalAddress = $user->getPostalAddresses()->first()) {
            $self->address = <<<EOF
                {$user->getName()}
                {$postalAddress->getStreet()}
                {$postalAddress->getPostalCode()} {$postalAddress->getCity()}
                EOF;
        } else {
            $self->address = $user->getName()."\n\n";
        }

        $self->email = $user->getEmail();
        $self->address = trim($self->address);

        return $self;
    }

    public static function fromPayment(Payment $payment): self
    {
        if (!($debtor = $payment->getDebtor()) instanceof Debtor) {
            throw new \BadMethodCallException('No debtor found');
        }

        $self = self::fromDebtor($debtor);
        $self->items = $payment->getItems();

        return $self;
    }

    public function toPayment(Payment $payment): Payment
    {
        $payment->setBillingAddress($this->address);
        $payment->setBillingEmail($this->email);

        foreach ($this->items as $item) {
            $payment->addItem(new PaymentItem(
                $payment,
                $item->getAmount(),
                $item->getAttendance(),
                $item->getType()
            ));
        }

        return $payment;
    }

    public function isPaid(): bool
    {
        return $this->paid;
    }
}
