<?php

declare(strict_types=1);

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

function upgrade_module_4_0_0(myvetshopclinique $module): bool
{
    $container = $module->getContainer();
    $db = Db::getInstance();

    // Installation des nouvelles tables
    $query = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'myvetshop_veterinaire` (
              `id_myvetshop_veterinaire` INT(11) NOT NULL AUTO_INCREMENT,
              `id_myvetshop_clinique` INT(11) NOT NULL,
              `lastname` varchar(55) DEFAULT NULL,
              `firstname` varchar(55) DEFAULT NULL,
              `url_teleconsultation` varchar(100) DEFAULT NULL,
               PRIMARY KEY (`id_myvetshop_veterinaire`),
               INDEX (`id_myvetshop_clinique`)
            );';

    if (!$db->execute($query)) {
        return false;
    }

    $query = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'myvetshop_clinique_shipping` (
              `id_myvetshop_clinique_shipping` INT(11) NOT NULL AUTO_INCREMENT,
              `id_myvetshop_clinique` INT(11) NOT NULL,
              `monday` TINYINT(1) DEFAULT 0,
              `tuesday` TINYINT(1) DEFAULT 0,
              `wednesday` TINYINT(1) DEFAULT 0,
              `thursday` TINYINT(1) DEFAULT 0,
              `friday` TINYINT(1) DEFAULT 0,
              `saturday` TINYINT(1) DEFAULT 0,
              `sunday` TINYINT(1) DEFAULT 0,
               PRIMARY KEY (`id_myvetshop_clinique_shipping`),
               INDEX (`id_myvetshop_clinique`)
            );';

    if (!$db->execute($query)) {
        return false;
    }

    $query = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'myvetshop_theme` (
              `id_myvetshop_theme` INT(11) NOT NULL AUTO_INCREMENT,
              `name` VARCHAR(128) NOT NULL,
              `color_1` VARCHAR(7) NOT NULL,
              `color_2` VARCHAR(7) NOT NULL,
              `color_3` VARCHAR(7) NOT NULL,
              `color_4` VARCHAR(7) NOT NULL,
              `color_5` VARCHAR(7) NOT NULL,
               PRIMARY KEY (`id_myvetshop_theme`)
            );';

    if (!$db->execute($query)) {
        return false;
    }

    $query = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'buy_limited_number_of_products` (
              `id_product` INT(11) NOT NULL,
              `max_quantity` INT(11) NOT NULL,
               PRIMARY KEY (`id_product`)
            );';

    $db->execute($query);

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

    // Ajout de la colonne "name" dans la clinique
    if (empty($db->executeS($query))) {
        $query = 'ALTER TABLE `' . $cliniqueTable . '` ADD `name` VARCHAR(255) NOT NULL AFTER id_store';
        $db->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->executeS($query))) {
        $query = 'ALTER TABLE `' . $cliniqueTable . '` ADD `id_theme` INT(10) NULL AFTER id_store';
        $db->execute($query);
    }

    // Suppression des champs inutiles

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

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

    $query = 'SHOW COLUMNS FROM ' . $employeeTable;
    $columns = $db->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->execute('ALTER TABLE ' . $employeeTable . ' DROP COLUMN ' . $column['Field']);
        }
    }

    // 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é
    /* @var \Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository|null $cliniqueRepository */
    if ($container->has(\Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository::class)) {
        $cliniqueRepository = $container->get(\Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository::class);
        \assert($cliniqueRepository instanceof \Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository);
        foreach ($cliniqueRepository->findAll() as $clinique) {
            $themeId = (int) \str_replace('theme', '', $clinique->theme);
            $theme = new \MyvetshopTheme($themeId);

            if (\Validate::isLoadedObject($theme)) {
                $clinique->idTheme = (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';
    $results = $db->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 s'ils existent

    $query = 'SHOW INDEX FROM ' . _DB_PREFIX_ . 'recommandation WHERE KEY_NAME = "id_customer"';

    if (!empty($db->executeS($query))) {
        $query = 'ALTER TABLE ' . _DB_PREFIX_ . 'recommandation DROP INDEX id_customer';
        $db->execute($query);
    }

    $query = 'SHOW INDEX FROM ' . _DB_PREFIX_ . 'recommandation WHERE KEY_NAME = "id_customer_2"';

    if (!empty($db->executeS($query))) {
        $query = 'ALTER TABLE ' . _DB_PREFIX_ . 'recommandation DROP INDEX id_customer_2';
        $db->execute($query);
    }

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

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

    return true;
}
