<?php

namespace customers;

use classes\response;
use objects\users_o;

class economic_customer_mo
{
    public int $customer_number;
    public null|string $name;
    public null|string $address;
    public null|string $city;
    public null|string $zip;
    public null|string $message;
    public null|string $corporateIdentificationNumber;
    public null|string $email;
    public null|string $mobilePhone;
    public null|string $currency;
    public null|string $country;
    public bool $barred;

    public function getCustomerByCustomerNumber(int $customer_number): static
    {
        // Get the customer from the economic system
        $economicCustomers = new economicCustomers();
        $customer = $economicCustomers->getCustomerId($customer_number);
        // Check if the customer exists
        if ($customer) {
            return $this->parseCustomer($customer);
        }
        return $this;

    }

    public function parseCustomer($customer): static
    {
        global /** @var response $response */
        $response;
        $this->customer_number = $customer->customerNumber;
        $this->name = ($customer->name ?? null);
        $this->address = ($customer->address ?? null);
        $this->city = ($customer->city ?? null);
        $this->zip = ($customer->zip ?? null);
        $this->corporateIdentificationNumber = ($customer->corporateIdentificationNumber ?? null);
        $this->email = ($customer->email ?? null);
        $this->mobilePhone = ($customer->mobilePhone ?? null);
        $this->currency = ($customer->currency ?? null);
        $this->country = ($customer->country ?? null);
        $this->barred = (isset($customer->barred) ? (bool)$customer->barred : false);
        $users_o = new users_o();
        $user = $users_o->getUserByCustomerNumber($this->customer_number);

        // Cache the customer
        if ($user->exists()) {
            $user->cache('economic_customer', $this);
        }
        // Add the customer to the debug log (IF DEBUG IS ENABLED)
        //$response->add_debug_list('economic_customer', $this->customer_number, $customer);
        return $this;
    }

    public function asArray(): array
    {
        // If the customer does not exist, return an empty array
        if (!isset($this->customer_number)) {
            return [];
        }
        return [
            'customerNumber' => $this->customer_number,
            'name' => $this->name,
            'address' => $this->address,
            'city' => $this->city,
            'zip' => $this->zip,
            'corporateIdentificationNumber' => $this->corporateIdentificationNumber,
            'email' => $this->email,
            'mobilePhone' => $this->mobilePhone,
            'currency' => $this->currency,
            'country' => $this->country,
            'barred' => $this->barred,
        ];
    }
}