<?php

declare(strict_types=1);

if (!defined('_PS_VERSION_')) {
    exit;
}

function upgrade_module_4_0_0(myvetshopclinique $module): bool
{
    // Installation des nouveslles tables
    MyvetshopVeterinaire::install() && MyvetshopCliniqueShipping::install() && MyvetshopTheme::install();

    // Ajout de la nouvelle colonne "name" dans la table clinique
    $cliniqueTable = _DB_PREFIX_ . Clinique::TABLE;
    $query = 'SHOW COLUMNS FROM ' . $cliniqueTable . " LIKE 'name'";

    // Ajout de la colonne "name" dans la clinique
    if (empty(Db::getInstance()->executeS($query))) {
        $query = 'ALTER TABLE `' . $cliniqueTable . '` ADD `name` VARCHAR(255) NOT NULL AFTER id_store';
        Db::getInstance()->execute($query);
    }

    // Ajout de la nouvelle colonne "id_theme" dans la table clinique
    $query = 'SHOW COLUMNS FROM ' . $cliniqueTable . " LIKE 'id_theme'";

    // Ajout de la colonne "id_theme" dans la clinique
    if (empty(Db::getInstance()->executeS($query))) {
        $query = 'ALTER TABLE `' . $cliniqueTable . '` ADD `id_theme` INT(10) NULL AFTER id_store';
        Db::getInstance()->execute($query);
    }

    foreach (Clinique::getAll() as $clinique) {
        $clinique->name = $clinique->getEmployee()->firstname . ' ' . $clinique->getEmployee()->lastname;
        $clinique->update();
    }

    // Suppression des champs inutiles

    $employeeTable = _DB_PREFIX_ . 'employee';
    $query = 'SHOW COLUMNS FROM ' . $employeeTable . " LIKE 'name'";

    if (empty(Db::getInstance()->executeS($query))) {
        $query = 'ALTER TABLE `' . $employeeTable . '` ADD `name` VARCHAR(255) NOT NULL';
        Db::getInstance()->execute($query);
    }

    $query = 'SHOW COLUMNS FROM ' . $employeeTable;
    $columns = Db::getInstance()->executeS($query);
    assert(is_array($columns));

    $toDelete = [
        'code_privilege',
        'centrale',
        'code_client',
        'mdp',
        'code_filiere',
        'theme',
        'masquer_logo',
    ];

    foreach ($columns as $column) {
        if (in_array($column['Field'], $toDelete)) {
            Db::getInstance()->execute('ALTER TABLE ' . $employeeTable . ' DROP COLUMN ' . $column['Field']);
        }
    }

    $cliniques = Db::getInstance()->executeS('SELECT * FROM ' . _DB_PREFIX_ . Clinique::TABLE);
    assert(is_array($cliniques));

    foreach ($cliniques as $clinique) {
        $cliniqueId = (int) $clinique['id_myvetshop_clinique'];

        // Migration des vétérinaires dans une nouvelle table
        $letters = ['A', 'B', 'C', 'D', 'E'];

        foreach ($letters as $letter) {
            $lastname = 'veto' . $letter . 'nom';
            $firstname = 'veto' . $letter . 'prenom';
            $url = 'veto' . $letter . 'urlrdv';

            if (array_key_exists($lastname, $clinique) && array_key_exists($firstname, $clinique) && array_key_exists($url, $clinique)) {
                if ($clinique[$lastname] || $clinique[$firstname] || $clinique[$url]) {
                    $veterinaire = new MyvetshopVeterinaire();
                    $veterinaire->id_myvetshop_clinique = $clinique->id;
                    $veterinaire->lastname = $clinique[$lastname];
                    $veterinaire->firstname = $clinique[$firstname];
                    $veterinaire->url_teleconsultation = $clinique[$url];
                    $veterinaire->add();
                }
            }
        }

        // Migration des informations de livraisons dans une nouvelle table
        $cliniqueShipping = MyvetshopCliniqueShipping::getByCliniqueId($cliniqueId);
        $joursLivraison = explode(',', $clinique['jours_livraison']);

        $cliniqueShipping->monday = in_array('lundi', $joursLivraison);
        $cliniqueShipping->tuesday = in_array('mardi', $joursLivraison);
        $cliniqueShipping->wednesday = in_array('mercredi', $joursLivraison);
        $cliniqueShipping->thursday = in_array('jeudi', $joursLivraison);
        $cliniqueShipping->friday = in_array('vendredi', $joursLivraison);
        $cliniqueShipping->saturday = in_array('samedi', $joursLivraison);
        $cliniqueShipping->sunday = in_array('dimanche', $joursLivraison);

        $cliniqueShipping->save();
    }

    // Ajout des variables de configuration
    Configuration::updateValue($module::CARRIER_HOME_DEFAULT_PRICE, $module->getCarrierHomeDefaultPrice());

    // Migration des thèmes dans le nouveau système

    $themes = [
        [
            'name' => 'Bleu',
            'color_1' => '#263762',
            'color_2' => '#2765a0',
            'color_3' => '#227ebd',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Sable',
            'color_1' => '#984b2f',
            'color_2' => '#e86839',
            'color_3' => '#fd8429',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Orange / Jaune',
            'color_1' => '#fd8429',
            'color_2' => '#fd9e2a',
            'color_3' => '#ffa83f',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Turquoise / Vert',
            'color_1' => '#28acc0',
            'color_2' => '#4abdcf',
            'color_3' => '#8fc89d',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Bleu / Jaune',
            'color_1' => '#347bb3',
            'color_2' => '#42c2f3',
            'color_3' => '#f79e28',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Bleu / Jaune / Vert',
            'color_1' => '#347bb3',
            'color_2' => '#fd8429',
            'color_3' => '#6fac2d',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Violet',
            'color_1' => '#773e8b',
            'color_2' => '#b472cc',
            'color_3' => '#e0167a',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Bleu / Rose / Vert',
            'color_1' => '#347bb3',
            'color_2' => '#e25eaa',
            'color_3' => '#6fac2d',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Noir / Bleu / Vert',
            'color_1' => '#474747',
            'color_2' => '#1d9dce',
            'color_3' => '#65c07b',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Vert / Noir',
            'color_1' => '#6fac2d',
            'color_2' => '#183641',
            'color_3' => '#acc246',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
        [
            'name' => 'Noir / Rouge / Vert',
            'color_1' => '#183641',
            'color_2' => '#b61b1f',
            'color_3' => '#6fac2d',
            'color_4' => '#bdbdbe',
            'color_5' => '#f2f2f3',
        ],
    ];

    foreach ($themes as $key => $data) {
        $themeId = $key + 1;
        $theme = new MyvetshopTheme($themeId);

        if (!Validate::isLoadedObject($theme)) {
            $theme->id = $themeId;
            $theme->name = $data['name'];
            $theme->color_1 = $data['color_1'];
            $theme->color_2 = $data['color_2'];
            $theme->color_3 = $data['color_3'];
            $theme->color_4 = $data['color_4'];
            $theme->color_5 = $data['color_5'];
            $theme->force_id = true;

            $theme->add();
        }
    }

    // On met à jour les cliniques pour qu'elles aient le bon thème d'enregistré
    foreach (Clinique::getAll() as $clinique) {
        $themeId = (int) str_replace('theme', '', $clinique->theme);
        $theme = new MyvetshopTheme($themeId);

        if (Validate::isLoadedObject($theme)) {
            $clinique->id_theme = (int) $theme->id;
            $clinique->save();
        }
    }

    // On met à jour tous les transporteurs pour qu'ils deviennent des transporteurs "modules" ce qui servira à afficher du contenu supplémentaire lors du choix du transporteur au passage de la commande
    $query = 'SELECT id_carrier FROM ' . _DB_PREFIX_ . Carrier::$definition['table'];
    $results = Db::getInstance()->executeS($query);
    assert(is_array($results));
    $carrierListId = array_column($results, 'id_carrier');

    foreach ($carrierListId as $carrierId) {
        $carrier = new Carrier($carrierId);
        $carrier->external_module_name = $module->name;
        $carrier->is_module = true;
        $carrier->need_range = true;
        $carrier->shipping_external = true;

        $carrier->save();
    }

    // On supprime les index customer des recommandations si ils existent

    $query = 'SHOW INDEX FROM ' . _DB_PREFIX_ . Recommandation::$definition['table'] . ' WHERE KEY_NAME = "id_customer"';

    if (!empty(Db::getInstance()->executeS($query))) {
        $query = 'ALTER TABLE ' . _DB_PREFIX_ . Recommandation::$definition['table'] . ' DROP INDEX id_customer';
        Db::getInstance()->execute($query);
    }

    $query = 'SHOW INDEX FROM ' . _DB_PREFIX_ . Recommandation::$definition['table'] . ' WHERE KEY_NAME = "id_customer_2"';

    if (!empty(Db::getInstance()->executeS($query))) {
        $query = 'ALTER TABLE ' . _DB_PREFIX_ . Recommandation::$definition['table'] . ' DROP INDEX id_customer_2';
        Db::getInstance()->execute($query);
    }

    // Ajout de la nouvelle colonne "id_recommandation_product" dans la table recommandation
    $recommandationTable = _DB_PREFIX_ . Recommandation::$definition['table'];
    $query = 'SHOW COLUMNS FROM ' . $recommandationTable . " LIKE 'id_recommandation_product'";

    // Ajout de la colonne "name" dans la clinique
    if (empty(Db::getInstance()->executeS($query))) {
        $query = 'ALTER TABLE `' . $recommandationTable . '` ADD `id_recommandation_product` INT(10) NULL AFTER id_animal';
        Db::getInstance()->execute($query);
    }

    return true;
}
