<?php

namespace App\Member\Factories;

use App\Invoice\BillKind;
use App\Invoice\Data\PositionData;
use App\Invoice\Data\ReceiverData;
use App\Member\Member;
use App\Payment\Subscription;
use Illuminate\Support\Collection;

class MemberInvoiceFactory
{

    /** @var Collection<int, Member> */
    private Collection $positions;

    private int $year;

    private ?Subscription $subscription = null;

    public function __construct(private Member $member) {}

    /**
     * @param Collection<int, Member> $members
     */
    public function withFamilyMembers(Collection $members): self
    {
        $this->positions = $members;

        return $this;
    }

    public function forSingleMember(): self
    {
        $this->positions = collect([$this->member]);

        return $this;
    }

    public function year(int $year): self
    {
        $this->year = $year;

        return $this;
    }

    public function withSubscription(Subscription $subscription): self
    {
        $this->subscription = $subscription;

        return $this;
    }

    public function getReceiver(): ReceiverData {
        return ReceiverData::from([
            'name' => 'Familie ' . $this->member->lastname,
            'address' => $this->member->address,
            'zip' => $this->member->zip,
            'location' => $this->member->location,
            'greeting' => 'Liebe Familie ' . $this->member->lastname,
            'email' => $this->member->email_parents ?: $this->member->email,
        ]);
    }

    public function getVia(): BillKind {
        return $this->member->bill_kind;
    }

    public function getUsage(): string {
        return 'Mitgliedsbeitrag für ' . $this->member->lastname;
    }

    /** @return Collection<int, PositionData> */
    public function getPositions() {
        /** @var Collection<int, PositionData> */
        $positions = collect([]);
        foreach ($this->positions as $member) {
            $memberSubscription = $this->subscription ?: $member->subscription;
            foreach ($memberSubscription->children as $child) {
                $positions->push(PositionData::from([
                    'description' => str($child->name)->replace('{name}', $member->firstname . ' ' . $member->lastname)->replace('{year}', (string) $this->year),
                    'price' => $child->amount,
                    'member_id' => $member->id,
                    'id' => null,
                ]));
            }
        }

        return $positions;
    }
}
