<?php

/**
 * {autogenerated}
 * @property int $address_id PK
 * @property int $user_id FK user
 * @property string $type
 * @property string|null $hash
 * @property string|null $name_f
 * @property string|null $name_l
 * @property string|null $street
 * @property string|null $street2
 * @property string|null $city
 * @property string|null $state
 * @property string|null $zip
 * @property string|null $country
 * @property datetime $added
 * @property datetime $updated
 * {/autogenerated}
 */
class Address extends Am_Record
{
    const TYPE_TAX = 'tax'; // To keep address history records for invoice payments tax and refunds
    const TYPE_DEFAULT = 'default'; // To keep address history records for invoice payments tax and refunds
    const TYPE_ANY = 'any';
}

/**
 * @extends Am_Table_WithData<Address>
 * @method void deleteByUserId($value, $useObjects = true)
 */
class AddressTable extends Am_Table_WithData
{
    protected $_key = 'address_id';
    protected $_table = '?_address';
    protected $_recordClass = 'Address';
    protected $fields = ['name_f', 'name_l', 'street', 'street2', 'city', 'state', 'zip', 'country'];

    /**
     * @param User|array $address
     */
    function hash($address): string
    {
        if ($address instanceof User) {
            $address = $address->toArray();
        }
        $hash = '';
        foreach ($this->fields as $v) {
            $hash .= $address[$v] ?? "";
        }
        $hash = md5(strtoupper($hash));
        return $hash;
    }

    /**
     * For now get default address from ?_user table
     * Later it should be stored in address table too;
     */
    function getDefaultAddress(User $user): ?array
    {
        $address = [];
        foreach ($this->fields as $field) {
            $address[$field] = $user->get($field);
        }
        if (empty(array_filter($address))) {
            return null;
        }

        return $address;
    }

    /**
     * Try to find address in table first,
     * if there is no such address create from User profile and return it ID
     */
    function getTaxAddressId(User $user): ?int
    {
        $addressInfo = $this->getDefaultAddress($user);

        if (empty($addressInfo)) {
            return null;
        }

        $hash = $this->hash($addressInfo);
        $search = [
            'user_id' => $user->pk(),
            'hash' => $hash,
            'type'=> Address::TYPE_TAX
        ];

        $address = $this->findFirstBy($search);

        if (empty($address)) {
            $address = $this->createRecord($addressInfo);
            $address->user_id = $user->pk();
            $address->added = $this->getDi()->sqlDateTime;
            $address->updated = $this->getDi()->sqlDateTime;
            $address->hash = $hash;
            $address->type = Address::TYPE_TAX;
            $address->insert();
        }

        return !empty($address) ? $address->pk() : null;
    }

    function anonymize(User $user, $haveTax): void
    {
        foreach ($this->findBy(['user_id' => $user->pk()]) as $address) {
            foreach ($this->fields as $field) {
                if ($haveTax && ($field == 'country'))
                    continue;
                $address->set($field, '');
            }
            $address->save();
        }
    }
}