<?php

declare(strict_types=1);

/**
 * Created by Aurélien RICHAUD (10/07/2017 16:15).
 *
 * @property Clinique $object
 * @property MyVetshopClinique $module
 */
class AdminMyVetShopCliniqueController extends ModuleAdminController
{
    public const GMAP_API_KEY = 'AIzaSyCass66EL1weNGYcbEBjxHnaUXzXxT642o';

    public function __construct()
    {
        parent::__construct();

        $this->bootstrap = true;

        $context = \Context::getContext();
        \assert(null !== $context);
        $this->context = $context;
        $this->table = Clinique::$definition['table'];
        $this->className = Clinique::class;
        $this->position_identifier = Clinique::$definition['primary'];
        $this->identifier = Clinique::$definition['primary'];
        $this->_orderBy = Clinique::$definition['primary'];
        $this->allow_export = true;
        $this->lang = false;
        $this->_select = "CONCAT(sl.address1, ' ', sl.address2, ' ', s.postcode, ' ', s.city) as fulladdress";
        $this->_join = ' LEFT JOIN ps_store s ON s.id_store = a.id_store'
        . ' LEFT JOIN ps_store_lang sl ON sl.id_store = a.id_store AND sl.id_lang = ' . ($context->language?->id ?? 1);

        $this->fields_list = [
            'id_myvetshop_clinique' => [
                'title' => $this->trans('ID'),
                'align' => 'text-center',
                'class' => 'fixed-width-xs',
            ],
            'name' => [
                'title' => $this->trans('Nom'),
                'havingFilter' => true,
            ],
            'id_store' => [
                'title' => $this->trans('Adresse'),
                'havingFilter' => false,
                'callback' => 'printAddress',
            ],
            'code_privilege' => [
                'title' => $this->trans('Code privilège'),
                'align' => 'text-center',
                'class' => 'fixed-width-xs',
            ],
            'deleted' => [
                'title' => $this->trans('Active'),
                'align' => 'text-center',
                'callback' => 'printActive',
                'class' => 'fixed-width-xs',
                'type' => 'bool',
            ],
            'centrale' => [
                'title' => $this->trans('Centrale'),
                'align' => 'text-center',
                'class' => 'fixed-width-xs',
            ],
            'id_warehouse' => [
                'title' => $this->trans('Entrepot'),
                'havingFilter' => false,
                'callback' => 'printEntrepot',
            ],
        ];
        $this->bulk_actions = [
            'delete' => [
                'text' => $this->trans('Delete selected'),
                'icon' => 'icon-trash',
                'confirm' => $this->trans('Delete selected object?'),
            ],
        ];
        $this->fieldImageSettings = [
            [
                'name' => 'logo',
                'dir' => 'e',
                'id_field' => 'id_employee',
                'height' => 150,
                'width' => 380,
            ],
            [
                'name' => 'photo',
                'dir' => 'st',
                'id_field' => 'id_store',
                'height' => 150,
                'width' => 150,
            ],
        ];

        // Actions disponibles
        $this->addRowAction('view');
        $this->addRowAction('veterinaire');
        $this->addRowAction('shipping');
        $this->addRowAction('holidays');
        $this->addRowAction('edit');
        // $this->addRowAction('delete');

        parent::__construct();
    }

    /**
     * @param string $token
     * @param int|string $cliniqueId
     */
    public function displayVeterinaireLink($token, $cliniqueId): string
    {
        \assert(null !== $this->context->smarty);

        $this->context->smarty->assign(
            'url',
            ($this->context->link?->getAdminLink('AdminMyVetShopVeterinaire') ?? '')
            . '&id_myvetshop_clinique=' . (int) $cliniqueId
        );

        return $this->module->fetch('module:myvetshopclinique/views/templates/admin/my_vet_shop_clinique/listing/display_veterinaire_link.tpl');
    }

    /**
     * @param string $token
     * @param int|string $cliniqueId
     */
    public function displayShippingLink($token, $cliniqueId): string
    {
        \assert(null !== $this->context->smarty);

        $cliniqueShipping = MyvetshopCliniqueShipping::getByCliniqueId((int) $cliniqueId);

        $this->context->smarty->assign(
            'url',
            ($this->context->link?->getAdminLink('AdminMyVetShopCliniqueShipping') ?? '')
            . '&id_myvetshop_clinique_shipping=' . $cliniqueShipping->id . '&updatemyvetshop_clinique_shipping'
        );

        return $this->module->fetch('module:myvetshopclinique/views/templates/admin/my_vet_shop_clinique/listing/display_clinique_shipping_link.tpl');
    }

    /**
     * @param string $token
     * @param int|string $cliniqueId
     */
    public function displayHolidaysLink($token, $cliniqueId): string
    {
        \assert(null !== $this->context->smarty);

        $this->context->smarty->assign(
            'url',
            ($this->context->link?->getAdminLink('AdminMyVetShopCliniqueHolidays') ?? '')
            . '&id_myvetshop_clinique=' . $cliniqueId
        );

        return $this->module->fetch('module:myvetshopclinique/views/templates/admin/my_vet_shop_clinique/listing/display_holidays_link.tpl');
    }

    /**
     * @throws PrestaShopDatabaseException
     */
    public function initProcess(): void
    {
        if (!$this->context->employee) {
            throw new \Exception();
        }

        if (5 == $this->context->employee->id_profile) {
            // Empêche l'édition
            if (isset($_GET['update' . $this->table])) {
                Tools::redirectAdmin($this->context->link?->getAdminLink('AdminMyVetShopClinique') ?? '');
            }

            // Empêche l'export
            if (isset($_GET['export' . $this->table])) {
                Tools::redirectAdmin($this->context->link?->getAdminLink('AdminMyVetShopClinique') ?? '');
            }

            // Empêche la suppression
            if (isset($_GET['delete' . $this->table])) {
                \Tools::redirectAdmin($this->context->link?->getAdminLink('AdminMyVetShopClinique') ?? '');
            }

            $_GET['view' . $this->table] = '';
            $clinique = Clinique::getCliniqueByEmployeeId((int) $this->context->employee->id);
            $_GET['id_myvetshop_clinique'] = $clinique ? $clinique->id : null;
        }

        if (Tools::getIsset('deletedmyvetshop_clinique')) {
            $cliniqueId = \Tools::getValue('id_myvetshop_clinique');
            if (\is_numeric($cliniqueId)) {
                $cliniqueId = \intval($cliniqueId);
            } else {
                $cliniqueId = null;
            }
            $clinique = new Clinique($cliniqueId);

            if (Validate::isLoadedObject($clinique)) {
                $clinique->deleted = !$clinique->deleted;
                $clinique->save();
            }

            \Tools::redirectAdmin($this->context->link?->getAdminLink('AdminMyVetShopClinique') ?? '');
        }

        parent::initProcess();
    }

    public function printAddress(int $storeId): string
    {
        \assert(null !== $this->context->smarty);

        $this->context->smarty->assign('store', new Store($storeId, $this->context->language?->id ?? 1));

        return $this->module->fetch('module:myvetshopclinique/views/templates/admin/my_vet_shop_clinique/listing/_print_address.tpl');
    }

    public function printActive(bool $isDeleted): string
    {
        \assert(null !== $this->context->smarty);

        $this->context->smarty->assign('isDeleted', $isDeleted);

        return $this->module->fetch('module:myvetshopclinique/views/templates/admin/my_vet_shop_clinique/listing/_print_active.tpl');
    }

    public function printEntrepot(int $id_warehouse): string
    {
        $warehouse = new Warehouse($id_warehouse);

        return $warehouse->name;
    }

    /**
     * @param Clinique $clinique
     *
     * @return array<string, mixed>|false
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     *
     * {@inheritDoc}
     */
    public function getFieldsValue($clinique)
    {
        $values = parent::getFieldsValue($clinique);

        if (Validate::isLoadedObject($this->object)) {
            $values = \array_merge(
                $values,
                MyvetshopCliniqueShipping::getByCliniqueId((int) $this->object->id)->toArray()
            );
        }

        if (!Validate::isLoadedObject($this->object) && !$values['name']) {
            $values['name'] = 'Clinique vétérinaire';
        }

        $store = new Store($clinique->id_store);
        $values['address1'] = $store->address1;
        $values['address2'] = $store->address2;
        $values['postcode'] = $store->postcode;
        $values['city'] = $store->city;
        $values['latitude'] = $store->latitude;
        $values['longitude'] = $store->longitude;
        // @phpstan-ignore-next-line
        $values['website'] = $store->website;

        /** @var array<int, string> $hours */
        $hours = $store->hours ?: [];

        foreach ($hours as $langId => $value) {
            $value = \json_decode($value);
            if (!\is_array($value)) {
                $value = [];
            }

            foreach ($value as $key => $hour) {
                $key = 'hours_' . $key;

                if (!\array_key_exists($key, $values)) {
                    $values[$key] = [];
                }

                $values[$key][$langId] = $hour[0];
            }
        }

        return $values;
    }

    /**
     * @throws Exception
     * @throws SmartyException
     */
    public function renderForm(): string
    {
        $this->multiple_fieldsets = true;

        $this->fields_form = array_merge(
            $this->getCliniqueForm(),
            $this->getShippingForm(),
            $this->getCentraleForm()
        );

        $carrier_home_price_default = 14.0;

        $carrier_home = new Carrier($this->object->id_carrier_home);
        $price = $carrier_home->getDeliveryPriceByWeight(50, 1);
        if (\is_bool($price)) {
            $price = $carrier_home_price_default;
        }

        $this->fields_value = [
            'carrier_home_price' => \round($price, 2),
        ];

        return parent::renderForm();
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function renderView(): string
    {
        /** @var Clinique $clinique */
        $clinique = $this->loadObject();

        // Réductions de groupe
        $group_reduction = true;
        foreach (Clinique::getReductionsByCat() as $id_category => $reduction) {
            if (!GroupReduction::doesExist($this->object->id_group, $id_category)) {
                $group_reduction = false;
            }
        }

        $result = Db::getInstance(false)->executeS(
            'SELECT ch.*
                  FROM ' . _DB_PREFIX_ . CliniqueHolidays::TABLE . ' ch
                  WHERE ch.id_myvetshop_clinique = ' . $clinique->id . '
                  ORDER BY ch.date_debut DESC
                  LIMIT 10');

        if (!is_array($result)) {
            $result = [];
        }

        $holidays = ObjectModel::hydrateCollection(
            'CliniqueHolidays', $result
        );

        // ///////////////////////////////////////
        // / Livraison à domicile
        $carrier_home = new Carrier($this->object->id_carrier_home);
        $carrier_home_price = $carrier_home->getDeliveryPriceByWeight(50, 1);

        // ///////////////////////////////////////
        // / URL logo / photo
        $photo_url = ImageManager::thumbnail(
            _PS_STORE_IMG_DIR_ . $clinique->id_store . '.jpg',
            'store_' . (int) $clinique->id_store . '.' . $this->imageType,
            150,
            $this->imageType,
            true,
            true
        );
        $logo_url = ImageManager::thumbnail(
            _PS_EMPLOYEE_IMG_DIR_ . $clinique->id_employee . '.jpg',
            'employee_' . (int) $clinique->id_employee . '.' . $this->imageType,
            150,
            $this->imageType,
            true,
            true
        );

        $this->tpl_view_vars = [
            'clinique' => $clinique,
            'carrier_home_price' => $carrier_home_price,
            'photo_url' => $photo_url,
            'logo_url' => $logo_url,
            'holidays' => $holidays,
            'carrier' => new Carrier($clinique->id_carrier),
            'carrier_home' => new Carrier($clinique->id_carrier_home),
            'warehouse' => new Warehouse($clinique->id_warehouse),
            'employee' => new Employee($clinique->id_employee),
            'group' => new Group($clinique->id_group),
            'group_reduction' => $group_reduction,
            'store' => new Store($clinique->id_store, $this->context->language?->id ?? 1),
            'orders' => $clinique->getOrders(10, 0),
            'order_count' => $clinique->getOrderCount(),
            'customers' => $clinique->getCustomers(10, 0),
            'customer_count' => $clinique->getCustomerCount(),
        ];

        return parent::renderView();
    }

    /**
     * @return false|ObjectModel|void
     *
     * @throws PrestaShopException
     *
     * {@inheritDoc}
     */
    public function processSave()
    {
        $result = parent::processSave();

        if (!$result) {
            return $result;
        }

        $this->loadObject();

        // Création de l'objet et tous les sous-objets liés
        if (!$this->object->id) {
            $this->object->save();
        }

        // Livraison à domicile
        $carrierHomePrice = Tools::getValue('carrier_home_price', $this->module->getCarrierHomeDefaultPrice());
        if (\is_numeric($carrierHomePrice)) {
            $carrierHomePrice = \floatval($carrierHomePrice);
        } else {
            $carrierHomePrice = $this->module->getCarrierHomeDefaultPrice();
        }

        $this->object->setPriceCarrierHome($carrierHomePrice);

        // Jours de livraisons
        $cliniqueShipping = $this->object->getShipping();

        foreach (MyvetshopCliniqueShipping::getDays() as $day => $dayTranslate) {
            $dayVal = \Tools::getValue($day);
            if (\is_string($dayVal) || \is_bool($dayVal)) {
                $dayVal = \boolval($dayVal);
            } else {
                $dayVal = false;
            }
            $cliniqueShipping->{$day} = $dayVal;
        }

        $cliniqueShipping->save();

        // /////////////////////////////////////////////////
        // / Magasin
        // /////////////////////////////////////////////////
        $store = new Store($this->object->id_store);
        // @phpstan-ignore-next-line
        $store->name = [];
        // @phpstan-ignore-next-line
        $store->address1 = [];
        // @phpstan-ignore-next-line
        $store->address2 = [];

        /** @var int[] $langIds */
        $langIds = Language::getLanguages(true, false, true);

        foreach ($langIds as $langId) {
            $address1 = \Tools::getValue('address1_' . $langId);
            if (!\is_string($address1)) {
                $address1 = '';
            }
            $address2 = \Tools::getValue('address2_' . $langId);
            if (!\is_string($address2)) {
                $address2 = '';
            }

            $store->name[$langId] = $this->object->name;
            $store->address1[$langId] = $address1;
            $store->address2[$langId] = $address2;
        }

        $postcode = \Tools::getValue('postcode');
        if (!\is_string($postcode)) {
            $postcode = '';
        }
        $store->postcode = $postcode;
        $city = \Tools::getValue('city');
        if (!\is_string($city)) {
            $city = '';
        }
        $store->city = \strval($city);

        $website = \Tools::getValue('website');
        if (!\is_string($website)) {
            $website = '';
        }
        // @phpstan-ignore-next-line
        $store->website = $website;

        $hours = [];

        foreach ($langIds as $langId) {
            $hours[$langId] = [];

            for ($i = 0; $i < 7; ++$i) {
                $key = \implode('_', ['hours', $i, $langId]);
                $hourVal = \Tools::getValue($key);
                if (!\is_string($hourVal)) {
                    $hourVal = '';
                }
                $hours[$langId][$i] = [$hourVal];
            }
        }

        // @phpstan-ignore-next-line
        $store->hours = \array_map(fn ($hour) => \json_encode($hour) ?: '', $hours);

        $latitude = \Tools::getValue('latitude');
        if (\is_numeric($latitude)) {
            $latitude = \floatval($latitude);
        } else {
            $latitude = null;
        }
        $longitude = \Tools::getValue('longitude');
        if (\is_numeric($longitude)) {
            $longitude = \floatval($longitude);
        } else {
            $longitude = null;
        }

        // S'il manque une coordonnée GPS, on va utiliser le GeoCoding Google Maps
        if (!$latitude || !$longitude) {
            $ch = \curl_init();

            $address1 = \Tools::getValue('address1');
            if (!\is_string($address1)) {
                $address1 = '';
            }
            $postcode = \Tools::getValue('postcode');
            if (!\is_string($postcode)) {
                $postcode = '';
            }
            $city = \Tools::getValue('city');
            if (!\is_string($city)) {
                $city = '';
            }

            \curl_setopt(
                $ch,
                \CURLOPT_URL,
                'https://maps.google.com/maps/api/geocode/json?key=' . self::GMAP_API_KEY . '&address='
                . \urlencode(
                    $address1
                    . ', ' . $postcode
                    . ' ' . $city
                )
            );
            \curl_setopt($ch, \CURLOPT_HEADER, 0);
            \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
            $result = \curl_exec($ch);

            if (\is_string($result)) {
                $result = \json_decode($result, true);
                if (!\is_array($result)) {
                    $result = [];
                }
            }

            \curl_close($ch);

            if (isset($result['results'][0]['geometry']['location'])) {
                $latitude = \floatval($result['results'][0]['geometry']['location']['lat'] ?? 0.0);
                $longitude = \floatval($result['results'][0]['geometry']['location']['lng'] ?? 0.0);
            }
        }

        $store->latitude = $latitude ?? 0.0;
        $store->longitude = $longitude ?? 0.0;

        $store->save();

        \Cache::clean('*');
        \Tools::clearSmartyCache();
    }

    public function processAdd()
    {
        $codePrivilege = \Tools::getValue('code_privilege');
        if (!\is_string($codePrivilege)) {
            $codePrivilege = '';
        }

        $clinique = Clinique::getByCodePrivilege($codePrivilege);

        if ($clinique && \Validate::isLoadedObject($clinique)) {
            $this->errors[] = 'Le code privilège est déjà utilisé pour une autre clinique. Veuillez en choisir un autre.';
        }

        return parent::processAdd();
    }

    public function processUpdate()
    {
        $codePrivilege = \Tools::getValue('code_privilege');
        if (!\is_string($codePrivilege)) {
            $codePrivilege = '';
        }

        $clinique = Clinique::getByCodePrivilege($codePrivilege);

        if ($clinique && \Validate::isLoadedObject($clinique) && $clinique->id != $this->object->id) {
            $this->errors[] = 'Le code privilège est déjà utilisé pour une autre clinique. Veuillez en choisir un autre.';
        }

        return parent::processUpdate();
    }

    /**
     * Overload this method for custom checking.
     *
     * @param mixed $id Object id used for deleting images
     *
     * @return bool
     *
     * {@inheritDoc}
     */
    protected function postImage($id): bool
    {
        $obj = $this->loadObject(true);
        if ($obj instanceof Clinique) {
            foreach ($this->fieldImageSettings as $image) {
                if (isset($image['name'], $image['dir'], $image['id_field'], $image['width'], $image['height'])) {
                    // Récupère l'ID depuis le champ qui va bien
                    $id = $obj->{$image['id_field']};
                    $this->uploadImage($id, $image['name'], $image['dir'] . '/', false, $image['width'], $image['height']);
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Gestion des filtres sur les champs calculés.
     */
    public function processFilter(): void
    {
        parent::processFilter();

        if ($this->_filterHaving) {
            $this->_filterHaving = str_replace(
                [
                    '`id_store`',
                    '`id_employee`',
                    '`id_warehouse`',
                ],
                [
                    'fulladdress',
                    "(SELECT CONCAT(e.firstname, ' ', e.lastname) FROM `" . _DB_PREFIX_ . 'employee` e WHERE e.id_employee = a.id_employee )',
                    '(SELECT w.name FROM `' . _DB_PREFIX_ . 'warehouse` w WHERE w.id_warehouse = a.id_warehouse )',
                ],
                $this->_filterHaving
            );
        }
    }

    public function initContent(): void
    {
        if (!$this->viewAccess()) {
            $this->errors[] = \Tools::displayError('You do not have permission to view this.');

            return;
        }
        if (isset($_GET['exportabandonmyvetshop_clinique'])) {
            /** @var Clinique $clinique */
            $clinique = $this->loadObject();

            $query = 'SELECT'
                . ' c.firstname AS prenom,'
                . ' c.lastname AS nom,'
                . ' c.email AS email,'
                . ' MAX(a.phone) AS telephone,'
                . ' MAX(a.phone_mobile) AS telephone_mobile,'
                . ' c.date_add AS date_inscription,'
                . ' COUNT(o.id_order) AS nb_commandes,'
                . ' MAX(o.invoice_date) AS date_derniere_commande'
                . ' FROM `' . _DB_PREFIX_ . 'customer` c'
                . ' LEFT JOIN `' . _DB_PREFIX_ . 'address` a ON a.id_customer = c.id_customer AND a.deleted = 0 AND a.active = 1'
                . ' LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON o.id_customer = c.id_customer'
                . ' WHERE c.id_default_group = ' . $clinique->id_group . ' AND c.active = 1'
                . ' GROUP BY c.id_customer'
                . ' HAVING MAX(o.invoice_date) < DATE_SUB(NOW(), INTERVAL 4 MONTH)'
                . ' ORDER BY MAX(o.invoice_date) DESC';

            \header('Content-Type: application/json');
            \header('Content-Disposition: attachment; filename="export_abandons_' . \date('Y-m-d') . '.csv"');
            $stdout = \fopen('php://temp ', 'w+');

            if (!$stdout) {
                throw new Exception('Error lors de l\'ouverture du fichier');
            }
            \fwrite($stdout, "\xEF\xBB\xBF");
            $header = null;

            $result = \Db::getInstance(false)->executeS($query);

            if (!is_array($result)) {
                $result = [];
            }
            foreach ($result as $row) {
                if (!$header) {
                    $header = \array_keys($row);
                    \fputcsv($stdout, $header, ';');
                }

                \fputcsv($stdout, $row, ';');
            }

            \rewind($stdout);
            \fpassthru($stdout);
            \fclose($stdout);
            exit;
        }

        parent::initContent();
    }

    /**
     * @return array<mixed>[]
     */
    protected function getCliniqueForm(): array
    {
        // ///////////////////////////////////////
        // / Détection des photos
        $logo_url = '';
        $logo_size = 0;
        $photo_url = '';
        $photo_size = 0;
        /** @var Clinique|false $obj */
        $obj = $this->loadObject(true);
        if ($obj) {
            // Logo
            $logo = _PS_EMPLOYEE_IMG_DIR_ . $obj->id_employee . '.jpg';
            $logo_url = ImageManager::thumbnail($logo, 'employee_' . (int) $obj->id_employee . '.' . $this->imageType, 150, $this->imageType, true, true);
            $logo_size = \file_exists($logo) ? \filesize($logo) / 1000 : false;

            // Photo de la clinique
            $photo = _PS_STORE_IMG_DIR_ . $obj->id_store . '.jpg';
            $photo_url = ImageManager::thumbnail($photo, 'store_' . (int) $obj->id_store . '.' . $this->imageType, 300, $this->imageType, true, true);
            $photo_size = \file_exists($photo) ? \filesize($photo) / 1000 : false;
        }

        $optionsTheme = [['id' => 0, 'label' => 'Aucun']];

        foreach (MyvetshopTheme::getAll() as $theme) {
            $optionsTheme[] = ['id' => $theme->id, 'label' => $theme->name];
        }

        return [
            [
                'form' => [
                    'legend' => [
                        'title' => (\Tools::getValue('id_myvetshop_clinique')) ? $this->trans('Modifier une clinique') : $this->trans('Ajouter une clinique'),
                        'icon' => 'icon-angle-double-right',
                    ],
                    'input' => [
                        [
                            'type' => 'text',
                            'label' => $this->trans('Code privilège'),
                            'name' => 'code_privilege',
                            'required' => true,
                            'col' => '1',
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Nom de la clinique'),
                            'name' => 'name',
                            'required' => true,
                            'col' => 2,
                        ],
                        [
                            'type' => 'select',
                            'label' => $this->trans('Thème'),
                            'name' => 'id_theme',
                            'empty_message' => '',
                            'options' => [
                                'query' => $optionsTheme,
                                'id' => 'id',
                                'name' => 'label',
                            ],
                            'required' => false,
                        ],
                        [
                            'type' => 'file',
                            'label' => $this->trans('Logo (150x380)'),
                            'name' => 'logo',
                            'required' => false,
                            'display_image' => true,
                            'image' => $logo_url ? $logo_url : false,
                            'size' => $logo_size,
                        ],
                        [
                            'type' => 'file',
                            'label' => $this->trans('Photo de la clinique (150x150)'),
                            'name' => 'photo',
                            'required' => false,
                            'display_image' => true,
                            'image' => $photo_url ? $photo_url : false,
                            'size' => $photo_size,
                        ],
                        [
                            'type' => 'radio',
                            'label' => $this->trans('Affichage du logo'),
                            'name' => 'masquer_logo',
                            'empty_message' => '',
                            'values' => [
                                [
                                    'id' => 'afficher_myvetshop',
                                    'value' => 0,
                                    'label' => 'Afficher le logo MyVetshop',
                                ],
                                [
                                    'id' => 'masquer_myvetshop',
                                    'value' => 1,
                                    'label' => 'Masquer le logo MyVetshop',
                                ],
                            ],
                            'required' => false,
                        ],
                        [
                            'type' => 'radio',
                            'label' => $this->trans('Bons de livraison par email'),
                            'name' => 'email_delivery_notes',
                            'empty_message' => '',
                            'values' => [
                                [
                                    'id' => 'aucun_bl',
                                    'value' => 0,
                                    'label' => 'Ne rien envoyer par email',
                                ],
                                [
                                    'id' => 'bl_email',
                                    'value' => 1,
                                    'label' => 'Envoyer les bons de livraison à la clinique par email',
                                ],
                            ],
                            'required' => false,
                        ],
                        [
                            'type' => 'radio',
                            'label' => $this->trans('Copie des factures par email'),
                            'name' => 'email_factures',
                            'empty_message' => '',
                            'values' => [
                                [
                                    'id' => 'aucune_copie',
                                    'value' => 0,
                                    'label' => 'Ne pas envoyer de copie par email',
                                ],
                                [
                                    'id' => 'copie_email',
                                    'value' => 1,
                                    'label' => 'Envoyer une copie de chaque facture client à la clinique',
                                ],
                            ],
                            'required' => false,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('E-Mail pour les ARCs'),
                            'name' => 'email_original',
                            'required' => true,
                            'col' => 2,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Site internet'),
                            'name' => 'website',
                            'required' => false,
                            'col' => 2,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Adresse 1'),
                            'name' => 'address1',
                            'lang' => true,
                            'required' => false,
                            'col' => 2,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Adresse 2'),
                            'name' => 'address2',
                            'lang' => true,
                            'required' => false,
                            'col' => 2,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Code postal'),
                            'name' => 'postcode',
                            'required' => false,
                            'col' => 1,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Ville'),
                            'name' => 'city',
                            'required' => false,
                            'col' => 2,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Latitude'),
                            'name' => 'latitude',
                            'required' => false,
                            'col' => 2,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Longitude'),
                            'name' => 'longitude',
                            'required' => false,
                            'col' => 2,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('URL de prise de rendez-vous'),
                            'name' => 'url_rendez_vous',
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Horaire Lundi'),
                            'name' => 'hours_0',
                            'lang' => true,
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Horaire Mardi'),
                            'name' => 'hours_1',
                            'lang' => true,
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Horaire Mercredi'),
                            'name' => 'hours_2',
                            'lang' => true,
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Horaire Jeudi'),
                            'name' => 'hours_3',
                            'lang' => true,
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Horaire Vendredi'),
                            'name' => 'hours_4',
                            'lang' => true,
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Horaire Samedi'),
                            'name' => 'hours_5',
                            'lang' => true,
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Horaire Dimanche'),
                            'name' => 'hours_6',
                            'lang' => true,
                            'required' => false,
                            'col' => 4,
                        ],
                        [
                            'type' => 'text',
                            'label' => $this->trans('Tarif livraison à domicile (H.T)'),
                            'name' => 'carrier_home_price',
                            'required' => false,
                            'col' => 1,
                        ],
                        [
                            'type' => 'radio',
                            'label' => $this->trans('Rurale'),
                            'name' => 'rurale',
                            'empty_message' => '',
                            'values' => [
                                [
                                    'id' => 'desactiver_rurale',
                                    'value' => 0,
                                    'label' => 'Masquer la rurale pour cette clinique',
                                ],
                                [
                                    'id' => 'activer_rurale',
                                    'value' => 1,
                                    'label' => 'Activer la rurale pour cette clinique',
                                ],
                            ],
                            'required' => false,
                        ],
                        [
                            'type' => 'textarea',
                            'label' => $this->trans('Message avant la commande'),
                            'hint' => $this->trans('Affiché sur la page commande, avant le paiement'),
                            'name' => 'message',
                            'required' => false,
                            'cols' => 10,
                            'rows' => 10,
                            'class' => 'rte autoload_rte',
                        ],
                        [
                            'type' => 'radio',
                            'label' => $this->trans('Don Univet Nature'),
                            'name' => 'don',
                            'empty_message' => '',
                            'values' => [
                                [
                                    'id' => 'desactiver_don',
                                    'value' => 0,
                                    'label' => 'Masquer le don pour cette clinique',
                                ],
                                [
                                    'id' => 'activer_don',
                                    'value' => 1,
                                    'label' => 'Activer le don pour cette clinique',
                                ],
                            ],
                            'required' => true,
                        ],
                        [
                            'type' => 'textarea',
                            'label' => $this->trans('Produits bloqués'),
                            'hint' => $this->trans('ID produits prestashop séparés par des virgules'),
                            'name' => 'blockedProducts',
                            'required' => false,
                            'cols' => 10,
                            'rows' => 5,
                            'class' => '',
                        ],
                        [
                            'type' => 'textarea',
                            'label' => $this->trans('Message affiché pour les produits bloqués'),
                            'hint' => $this->trans('Laisser vide pour le message par défaut'),
                            'name' => 'blockedProductsMessage',
                            'required' => false,
                            'cols' => 10,
                            'rows' => 5,
                            'class' => '',
                        ],
                    ],
                ],
            ],
        ];
    }

    /**
     * @return array<mixed>[]
     */
    protected function getShippingForm(): array
    {
        $fields = [];

        foreach (MyvetshopCliniqueShipping::getDays() as $day => $dayTranslate) {
            $fields[] = [
                'type' => 'switch',
                'label' => ucfirst($dayTranslate),
                'name' => $day,
                'required' => false,
                'is_bool' => true,
                'values' => [
                    [
                        'id' => $day . '_on',
                        'value' => 1,
                        'label' => $this->trans('Enabled'),
                    ],
                    [
                        'id' => $day . '_off',
                        'value' => 0,
                        'label' => $this->trans('Disabled'),
                    ],
                ],
            ];
        }

        return [
            [
                'form' => [
                    'legend' => [
                        'title' => 'Jour de livraison',
                        'icon' => 'icon-angle-double-right',
                    ],
                    'input' => $fields,
                ],
            ],
        ];
    }

    /**
     * @return array<mixed>[]
     */
    protected function getCentraleForm(): array
    {
        return [[
            'form' => [
                'legend' => [
                    'title' => 'Centrale',
                    'icon' => 'icon-angle-double-right',
                ],
                'input' => [
                    [
                        'type' => 'select',
                        'label' => $this->trans('Centrale'),
                        'name' => 'centrale',
                        'required' => false,
                        'col' => '1',
                        'options' => [
                            'query' => [
                                ['id' => '', 'label' => ''],
                                ['id' => 'alcyon', 'label' => 'Alcyon'],
                                ['id' => 'centravet', 'label' => 'CentraVet'],
                                ['id' => 'coveto', 'label' => 'CoVeto'],
                                ['id' => 'hippocampe', 'label' => 'Hippocampe'],
                            ],
                            'id' => 'id',
                            'name' => 'label',
                        ],
                    ],
                    [
                        'type' => 'select',
                        'label' => $this->trans('Entrepot'),
                        'name' => 'id_warehouse',
                        'required' => false,
                        'col' => '1',
                        'options' => [
                            'query' => \Db::getInstance()->executeS(
                                'SELECT `id_warehouse`, `name` FROM `' . _DB_PREFIX_ . 'warehouse`'
                            ),
                            'id' => 'id_warehouse',
                            'name' => 'name',
                        ],
                    ],
                    [
                        'type' => 'text',
                        'label' => $this->trans('Code client'),
                        'name' => 'code_client',
                        'required' => false,
                        'col' => '1',
                    ],
                    [
                        'type' => 'text',
                        'label' => $this->trans('Mot de passe'),
                        'name' => 'mdp',
                        'required' => false,
                        'col' => '1',
                    ],
                    [
                        'type' => 'text',
                        'label' => $this->trans('Code filière'),
                        'name' => 'code_filiere',
                        'required' => false,
                        'col' => '1',
                    ],
                ],
                'submit' => [
                    'title' => $this->trans('Save'),
                    'class' => 'btn btn-default pull-right',
                    'name' => 'saveAction',
                ],
            ],
        ]];
    }
}
