<?php

namespace App\Supports;

use Modules\Country\Entities\Country;

class Address
{
    public $full_one_line = null;
    public $full_with_break = null;

    private ?Country $country = null;

    public function __construct(
        public string $address_line_1,
        public ?string $address_line_2 = null,
        public ?string $postcode = null,
        public ?string $country_name = null,
        public ?int $country_id = null,
        public ?string $contact_no = null,
        public ?string $email = null,
        public ?string $name = null,
    )
    {
        if ($country_id) {
            $this->country = Country::find($country_id);
        }

        $filtered_address = array_filter([
            $address_line_1,
            $this->unBreak($address_line_2),
            $postcode,
            $this->country ? $this->country->name : $country_name,
        ]);

        $this->full_one_line = $this->unBreak(implode(', ', $filtered_address));
        $this->full_with_break = implode(",\n", $filtered_address);
    }

    public function hasAddress(): bool
    {
        return !empty($this->address_line_1);
    }

    public function getCountry(): ?Country
    {
        return $this->country;
    }

    public function getLineOnly(): string
    {
        return implode(', ', array_filter([$this->address_line_1, $this->address_line_2]));
    }

    private function unBreak($string): ?string
    {
        return str_replace(["\r\n", "\r", "\n"], ' ', $string);
    }

    public function notComplete()
    {
        return is_null($this->country) || is_null($this->postcode);
    }

    public function missingContact()
    {
        return is_null($this->name) || is_null($this->email) || is_null($this->contact_no);
    }
}
