<?php

namespace Opencart\Extension\Alsendo\DTO\Entity;

use Opencart\Extension\Alsendo\Helpers\Country;

require_once(DIR_EXTENSION . 'alsendo/src/Helpers/Country.php');

abstract class AbstractOrderDetailsShippingAddressEntity
{
    public int $id;
    public int $orderDetailsId;
    public ?string $fullName;
    public ?string $companyName;
    public ?string $addressType;
    public ?string $phoneNumber;
    public ?string $email;
    public ?string $country;
    public ?string $city;
    public ?string $postalCode;
    public ?string $street;
    public ?string $houseNumber;
    public ?string $apartmentNumber;
    public ?array $deliveryPoint;

    public static function fromArray(array $data): static
    {
        $self = new static();
        $self->id = (int)$data['id'];
        $self->orderDetailsId = (int)$data['order_details_id'];
        $self->fullName = $data['full_name'] ?? null;
        $self->companyName = $data['company_name'] ?? null;
        $self->addressType = $data['address_type'] ?? null;
        $self->phoneNumber = $data['phone_number'] ?? null;
        $self->email = $data['email'] ?? null;
        $self->country = $data['country'] ?? null;
        $self->city = $data['city'] ?? null;
        $self->postalCode = $data['postal_code'] ?? null;
        $self->street = $data['street'] ?? null;
        $self->houseNumber = $data['house_number'] ?? null;
        $self->apartmentNumber = $data['apartment_number'] ?? null;
        $self->deliveryPoint = isset($data['delivery_point']) ? (is_array($data['delivery_point']) ? $data['delivery_point'] : json_decode($data['delivery_point'], true)) : null;
        return $self;
    }

    public function getSummaryText(): string
    {
        $apartmentPart = $this->apartmentNumber ?? '';

        if (!empty($this->street)) {
            $addressPart = sprintf('%s %s %s', $this->street, $this->houseNumber, $apartmentPart);
        } else {
            $addressPart = sprintf('%s %s %s', $this->city, $this->houseNumber, $apartmentPart);
        }


        return sprintf('%s, %s, %s %s, %s', $this->fullName, $addressPart, $this->postalCode, $this->city, $this->country);
    }

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

    public function getDeliveryPointText(): ?string
    {
        if (empty($this->deliveryPoint)) {
            return null;
        }

        $code = $this->deliveryPoint['code'] ?? null;
        $name = $this->deliveryPoint['name'] ?? null;

        if (empty($name) && empty($code)) {
            return 'Unknown';
        }

        if (empty($code)) {
            return $name;
        }

        if (empty($name)) {
            return $code;
        }

        return sprintf('%s - %s', $code, $name);
    }
}
