<?php

declare(strict_types=1);

/**
 * Created by Aurélien RICHAUD (23/05/2018 15:20).
 */
class Customer extends CustomerCore
{
    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function __construct($id = null)
    {
        parent::__construct($id);

        $this->webserviceParameters =
            [
                'fields' => [
                    'id_default_group' => ['setter' => null],
                    'id_lang' => ['setter' => null],
                    'newsletter_date_add' => [],
                    'ip_registration_newsletter' => [],
                    'last_passwd_gen' => ['setter' => null],
                    'secure_key' => ['setter' => null],
                    'deleted' => [],
                    'passwd' => ['setter' => 'setWsPasswd'],
                ],
                'associations' => [
                    'groups' => ['resource' => 'group'],
                    'animals' => ['resource' => 'animals', 'setter' => false, 'virtual_entity' => true,
                        'fields' => [
                            'id' => ['setter' => null],
                            'id_product' => ['setter' => null],
                            'id_customer' => ['setter' => null],
                            'espece' => ['setter' => null],
                            'nom' => ['setter' => null],
                            'race' => ['setter' => null],
                            'id_gender' => ['setter' => null],
                            'robe' => ['setter' => null],
                            'date_naissance' => ['setter' => null],
                            'ration' => ['setter' => null],
                            'photo' => ['setter' => null],
                        ],
                    ],
                ],
            ];
    }

    /**
     * @return array<string, mixed>
     *
     * @throws PrestaShopDatabaseException
     */
    public function getWsAnimals(): array
    {
        return array_map(fn (Animal $animal) => $animal->toArray(), Animal::getByCustomerId($this->id));
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     *
     * Permet de vérifier qu'un client appartient bien au groupe de la clinique
     */
    public function checkGroup(int $idEmployee): bool
    {
        $clinique = Clinique::getCliniqueByEmployeeId($idEmployee);
        if (!$clinique) {
            return false;
        }

        return in_array($this->id_default_group, [$clinique->id_group, $clinique->id_group_rural]);
    }

    public function getTotalOrders(): int
    {
        return (int) $this->getStats()['total_orders'];
    }

    public function getLastVisit(): string
    {
        return (string) $this->getStats()['last_visit'];
    }
}
