<?php
/**
 * Created by Aurélien RICHAUD (08/01/2018 17:19)
 */

// Si on est pas exécuté depuis la ligne de commande, ou si la mauvaise secure_key est envoyée, on arrête tout !
if ('cli' != php_sapi_name() && !isset($_GET['secure_key']) && 'LEKFPQ345PRRAOY5' != $_GET['secure_key']) {
    die(1);
}

// Désactivation du timeout
set_time_limit(0);

/////////////////////////////////////////////////
// Configuration

/////////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.inc.php';
    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'Clinique.php';

    // Gestion multi-boutique (au cas où) : Ce module est global
    if (Shop::isFeatureActive()) {
        Shop::setContext(Shop::CONTEXT_ALL);
    }
} catch (Exception $e) {
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
    exit();
}

$context = Context::getContext();

// Workaround pour PrestaShop
$context->controller = (object) [
    'controller_type' => 'cron',
];

/**
 * @param string $centrale
 *
 * @return int[]|null
 */
function getAccessoireCategoriesByCentrale($centrale)
{
    $db = Db::getInstance();

    switch ($centrale) {
        case 'alcyon':
            $centraleCatName = 'Alcyon';
            break;

        case 'centravet':
            $centraleCatName = 'CentraVet';
            break;

        case 'coveto':
            $centraleCatName = 'CoVeto';
            break;

        case 'hippocampe':
            $centraleCatName = 'Hippocampe';
            break;

        default:
            return null;
    }

    $idCatCentrale = $db->getValue('SELECT `id_category` FROM `ps_category_lang` WHERE `name` = "' . $db->escape($centraleCatName) . '"');

    if (!$idCatCentrale) {
        return null;
    }

    $idCatAccessoires = $db->getValue(
        'SELECT `c`.`id_category`'
        . ' FROM `ps_category` c'
        . ' INNER JOIN `ps_category_lang` cl ON `cl`.`id_category` = `c`.`id_category`'
        . ' WHERE `c`.`id_parent` = ' . (int) $idCatCentrale . ' AND `cl`.`name` = "' . $db->escape('Accessoires') . '"'
    );
    if (!$idCatAccessoires) {
        return null;
    }

    $ret = [(int) $idCatAccessoires];

    $result = $db->executeS('SELECT c.* FROM `ps_category` c WHERE id_parent = ' . (int) $idCatAccessoires);

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

    foreach ($result as $row) {
        $ret[] = (int) $row['id_category'];
    }

    return $ret;
}

try {
    $cliniques = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'myvetshop_clinique` WHERE `deleted` = 0');

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

    foreach ($cliniques as $clinique) {
        echo '- ' . $clinique['code_privilege'] . "\n";

        if ($clinique['id_group']) {
            echo "\t- Catégorie accessoire\n";
            $cliniqueObj = new Clinique($clinique['id_myvetshop_clinique']);

            $catAccessoires = $cliniqueObj->getAccessoireCategories();

            $db = Db::getInstance();
            if ($catAccessoires) {
                foreach ($catAccessoires as $idCat) {
                    $count = $db->getValue('SELECT COUNT(*) FROM ps_category_group WHERE id_category = ' . (int) $idCat . ' AND id_group = ' . (int) $clinique['id_group']);

                    if (!$count) {
                        echo "\t\t- Ajout " . $idCat . "\n";
                        $db->execute('INSERT INTO ps_category_group (id_category, id_group) VALUES (' . (int) $idCat . ', ' . (int) $clinique['id_group'] . ')');
                    }
                }

                foreach (['alcyon', 'centravet', 'coveto', 'hippocampe'] as $centrale) {
                    // Traitement de la suppression pour les AUTRES centrales
                    if ($centrale == $cliniqueObj->centrale) {
                        continue;
                    }

                    $catAccessoiresDel = getAccessoireCategoriesByCentrale($centrale);

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

                    $db = Db::getInstance();

                    foreach ($catAccessoiresDel as $idCat) {
                        $count = $db->getValue('SELECT COUNT(*) FROM ps_category_group WHERE id_category = ' . (int) $idCat . ' AND id_group = ' . (int) $clinique['id_group']);

                        if ($count) {
                            echo "\t\t- Suppression " . $idCat . "\n";

                            $db->execute('DELETE FROM `ps_category_group` WHERE id_category = ' . (int) $idCat . ' AND id_group = ' . (int) $clinique['id_group']);
                        }
                    }
                }

                $db->execute('DELETE FROM ps_category_group WHERE id_group IN (1,2,3) AND id_category IN (' . implode(',', $catAccessoires) . ')');
            }

            $groups = [];

            if ($clinique['id_carrier']) {
                echo "\t- Livraison clinique\n";
                $carrier = new Carrier($clinique['id_carrier']);
                $groups = $carrier->getGroups();
                foreach ($groups as &$group) {
                    $group = $group['id_group'];
                }

                if (1 != count($groups) || (count($groups) > 0 && $groups[0] != $clinique['id_group'])) {
                    echo "\t\t- Association groupe\n";
                    $carrier->setGroups([$clinique['id_group']]);
                }

                // Image img-clinique.jpg
                if (!is_file(_PS_SHIP_IMG_DIR_ . $clinique['id_carrier'] . '.jpg')) {
                    echo "\t\t- Image\n";
                    copy(_PS_SHIP_IMG_DIR_ . 'img-clinique.jpg', _PS_SHIP_IMG_DIR_ . $clinique['id_carrier'] . '.jpg');
                }

                $jours_livraison = explode(',', $cliniqueObj->jours_livraison);
                if (trim($cliniqueObj->jours_livraison) && is_array($jours_livraison) && count($jours_livraison)) {
                    $livraison_text = implode(', le ', array_slice($jours_livraison, 0, -1)) . ' et le ' . end($jours_livraison);
                } else {
                    $livraison_text = 'Livraison en 2 à 4 jours ouvrés (hors corse)';
                }

                echo "\t\t- Correction descriptif : " . $livraison_text . "\n";
                $db->execute(
                    'UPDATE `' . _DB_PREFIX_ . 'carrier_lang` SET `delay` = "Livraison le ' . $db->escape($livraison_text) . '" WHERE `id_carrier` = '
                    . (int) $clinique['id_carrier']
                );
            }

            if ($clinique['id_carrier_home']) {
                echo "\t- Livraison à domicile\n";
                $carrier = new Carrier($clinique['id_carrier_home']);

                if (1 != count($groups) || (count($groups) > 0 && $groups[0] != $clinique['id_group'])) {
                    echo "\t\t- Association groupe\n";
                    $carrier->setGroups([$clinique['id_group']]);
                }

                // Image img-domicile.jpg
                if (!is_file(_PS_SHIP_IMG_DIR_ . $clinique['id_carrier_home'] . '.jpg')) {
                    echo "\t\t- Image\n";
                    copy(_PS_SHIP_IMG_DIR_ . 'img-domicile.jpg', _PS_SHIP_IMG_DIR_ . $clinique['id_carrier_home'] . '.jpg');
                }
            }

            $warehouse = new Warehouse($clinique['id_warehouse']);
            echo "\t- Association entrepot\n";
            $id_carriers = $warehouse->getCarriers();

            if (!in_array($clinique['id_carrier'], $id_carriers) || !in_array($clinique['id_carrier_home'], $id_carriers)) {
                echo "\t\t- Mise à jour\n";
                Db::getInstance()->execute(
                    'DELETE FROM `' . _DB_PREFIX_ . 'warehouse_carrier`'
                    . ' WHERE `id_carrier` IN (' . (int) $clinique['id_carrier'] . ', ' . (int) $clinique['id_carrier_home'] . ') AND `id_warehouse` != ' . (int) $warehouse->id
                );
                Db::getInstance()->executeS(
                    'INSERT INTO `' . _DB_PREFIX_ . 'warehouse_carrier` (`id_carrier`, `id_warehouse`)'
                    . ' VALUES (' . (int) $clinique['id_carrier'] . ', ' . (int) $warehouse->id . '), '
                    . ' (' . (int) $clinique['id_carrier_home'] . ', ' . (int) $warehouse->id . ') '
                    . ' ON DUPLICATE KEY UPDATE `id_warehouse` = ' . (int) $warehouse->id
                );
            }

            /// Association au groupe d'accessoire qui va bien
            $catAccessoires = $cliniqueObj->getAccessoireCategories();

            if ($catAccessoires) {
                foreach ($catAccessoires as $idCat) {
                    $count = $db->getValue('SELECT COUNT(*) FROM ps_category_group WHERE id_category = ' . (int) $idCat . ' AND id_group = ' . (int) $clinique['id_group']);

                    if (!$count) {
                        $db->execute('INSERT INTO ps_category_group (id_category, id_group) VALUES (' . (int) $idCat . ', ' . (int) $clinique['id_group'] . ')');
                    }
                }

                // Détermine la catégorie accessoire principale, et applique 10% de réduction
                $mainAccessoireCatId = array_values(array_intersect($catAccessoires, [274, 399, 418]));

                if (count($mainAccessoireCatId)) {
                    if (!GroupReduction::doesExist((int) $clinique['id_group'], $mainAccessoireCatId[0])) {
                        $groupeReduction = new GroupReduction();
                        $groupeReduction->id_group = (int) $clinique['id_group'];
                        $groupeReduction->id_category = $mainAccessoireCatId[0];
                        $groupeReduction->reduction = 0.100;
                        $groupeReduction->save();
                    }
                }
            }
        }

        echo "\n";
    }

    /////////////////////////////////////////////
    /// Suppression des carriers surnuméraires
    $carriers = Db::getInstance()->executeS(
        'SELECT * FROM ' . _DB_PREFIX_ . 'carrier WHERE id_carrier NOT IN (SELECT id_carrier FROM ps_myvetshop_clinique UNION SELECT id_carrier_home FROM ps_myvetshop_clinique)'
    );

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

    echo 'Suppression des transporteurs surnuméraires (' . count($carriers) . ")\n";

    foreach ($carriers as $carrier) {
        echo "\t- " . $carrier['name'] . ' (' . $carrier['id_carrier'] . ")\n";
        $carrier = new Carrier($carrier['id_carrier']);
        $carrier->delete();
    }
} catch (Exception $e) {
    var_dump($e);
}
