<?php

namespace PortalPeople\virtualstock\models;

/**
 * Represents a shipping/delivery address from a VirtualStock order.
 */
class ShippingAddress
{
    public string $name = '';
    public string $company = '';
    public string $address1 = '';
    public string $address2 = '';
    public string $city = '';
    public string $county = '';
    public string $postcode = '';
    public string $country = 'GB';
    public string $phone = '';
    public string $email = '';

    /** Raw API payload for any fields not explicitly mapped */
    public array $raw = [];

    public static function fromArray(array $data): self
    {
        $addr = new self();
        $addr->name     = (string) ($data['name'] ?? $data['delivery_name'] ?? '');
        $addr->company  = (string) ($data['company'] ?? $data['company_name'] ?? '');
        $addr->address1 = (string) ($data['address1'] ?? $data['address_1'] ?? $data['line1'] ?? '');
        $addr->address2 = (string) ($data['address2'] ?? $data['address_2'] ?? $data['line2'] ?? '');
        $addr->city     = (string) ($data['city'] ?? $data['town'] ?? '');
        $addr->county   = (string) ($data['county'] ?? $data['state'] ?? '');
        $addr->postcode = (string) ($data['postcode'] ?? $data['postal_code'] ?? $data['zip'] ?? '');
        $addr->country  = (string) ($data['country'] ?? $data['country_code'] ?? 'GB');
        $addr->phone    = (string) ($data['phone'] ?? $data['telephone'] ?? '');
        $addr->email    = (string) ($data['email'] ?? '');
        $addr->raw      = $data;

        return $addr;
    }

    public function toArray(): array
    {
        return [
            'name'     => $this->name,
            'company'  => $this->company,
            'address1' => $this->address1,
            'address2' => $this->address2,
            'city'     => $this->city,
            'county'   => $this->county,
            'postcode' => $this->postcode,
            'country'  => $this->country,
            'phone'    => $this->phone,
            'email'    => $this->email,
        ];
    }

    /**
     * Basic UK postcode format validation (e.g. SW1A 2AA, EC1A 1BB, W1A 0AX).
     */
    public function isValidUkPostcode(): bool
    {
        $postcode = (string) preg_replace('/\s+/', '', strtoupper($this->postcode));
        return (bool) preg_match('/^[A-Z]{1,2}[0-9][0-9A-Z]?[0-9][A-Z]{2}$/', $postcode);
    }

    public function isComplete(): bool
    {
        return $this->name !== ''
            && $this->address1 !== ''
            && $this->city !== ''
            && $this->postcode !== '';
    }
}
