<?php

declare(strict_types=1);
/**
 * Created by Aurélien RICHAUD (08/01/2018 17:19).
 */

// Si on n'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 && !isset($_GET['secure_key']) && 'LEKFPQ345PRRAOY5' != $_GET['secure_key']) {
    exit(1);
}

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

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

// ///////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'config' . \DIRECTORY_SEPARATOR . 'config.inc.php';
    require_once __DIR__ . \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
// @phpstan-ignore-next-line
$context->controller = (object) [
    'controller_type' => 'cron',
    'php_self' => 'force_groups',
];

$db = \Db::getInstance();

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

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

    foreach ($cliniques as $clinique) {
        $cliniqueObj = new Clinique($clinique['id_myvetshop_clinique']);

        echo '- ' . $clinique['code_privilege'] . "\n";

        if ($clinique['id_group']) {
            $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) || (!empty($groups) && $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) || (!empty($groups) && $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->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->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
                );
            }
        }

        echo "\n";
    }

    // ///////////////////////////////////////////
    // / Suppression des carriers surnuméraires
    $carriers = $db->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);
}
