<?php

declare(strict_types=1);

// Si on n'est pas exécuté depuis la ligne de commande, on arrête tout !
if ('cli' != \PHP_SAPI) {
    exit(1);
}

// ///////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once __DIR__ . '/../../../config/config.inc.php';

    // Gestion multiboutique (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;
}

\Module::getInstanceByName('myvetshopclinique');

// ///////////////////////////////////////////////
// / Classes requises
require_once __DIR__ . \DIRECTORY_SEPARATOR . 'classes' . \DIRECTORY_SEPARATOR . 'Clinique.php';

$context = Context::getContext();
\assert(null !== $context);
$context->language = new Language(1);
$context->currency = new Currency(1);

// Workaround pour PrestaShop
// @phpstan-ignore-next-line
$context->controller = (object) [
    'controller_type' => 'cron',
    'php_self' => 'delete_clinique',
];

if (2 != count($argv)) {
    echo "Utilisation : php delete_clinique.php <code_privilege>\n";
    exit;
}

try {
    $db = Db::getInstance();
    $cliniques = $db->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'myvetshop_clinique` WHERE `deleted` = 0 AND `code_privilege` = "' . $db->escape($argv[1]) . '"');

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

    if (1 != count($cliniques)) {
        echo 'Code privilège invalide : ' . $argv[1] . "\n";
        exit;
    }

    if (!isset($cliniques[0]['id_myvetshop_clinique'])) {
        echo 'Erreur lors de la récupération de l\'id de la clinique : ' . $argv[1] . "\n";
        exit;
    }

    // Récupération de l'objet Clinique
    $clinique = new Clinique($cliniques[0]['id_myvetshop_clinique']);

    echo 'Préparation de la désactivation de la clinique ' . $argv[1];

    for ($i = 0; $i < 10; ++$i) {
        echo '.';
        sleep(1);
    }
    echo "\n";

    // ///////////////////////////////////////////
    // / Etape 1 : Extraction des clients actuels
    if (!is_dir(__DIR__ . \DIRECTORY_SEPARATOR . 'csv')) {
        mkdir(__DIR__ . \DIRECTORY_SEPARATOR . 'csv');
    }
    $outputClientsFileName = __DIR__ . \DIRECTORY_SEPARATOR . 'csv' . \DIRECTORY_SEPARATOR . 'clients-' . $argv[1] . '-' . date('YmdHis') . '.csv';
    echo '1 - Extraction des clients actuels -> ' . $outputClientsFileName . "\n";
    $csv = fopen($outputClientsFileName, 'w+');

    if (!$csv) {
        echo 'Erreur lors de la création du fichier.';
        exit;
    }

    $entries = $db->executeS(
        'SELECT c.`id_customer` AS `id_customer`, `id_gender`, `firstname`, `lastname`, c.`email` AS `email`, `birthday`, `date_add`, c.`active` AS `active`, c.*, a.id_group
            FROM `' . _DB_PREFIX_ . 'customer_group` a
            LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON (a.`id_customer` = c.`id_customer`)
            WHERE a.`id_group` = ' . (int) $clinique->id_group . ' AND c.`deleted` != 1 AND c.id_shop IN (1)
            ORDER BY `id_group` ASC'
    );

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

    echo "\t- " . count($entries) . " clients exportés\n";

    if (0 == count($entries)) {
        // Si aucun résultat, on va gérer un entête par défaut
        $header = ['id_customer', 'id_gender', 'firstname', 'lastname', 'email', 'birthday', 'date_add', 'active', 'id_customer', 'id_shop_group', 'id_shop', 'id_gender', 'id_default_group',
            'id_lang', 'id_risk', 'company', 'siret', 'ape', 'firstname', 'lastname', 'email', 'passwd', 'last_passwd_gen', 'birthday', 'newsletter', 'ip_registration_newsletter',
            'newsletter_date_add', 'optin', 'website', 'outstanding_allow_amount', 'show_public_prices', 'max_payment_days', 'secure_key', 'note', 'active', 'is_guest', 'deleted', 'date_add',
            'date_upd', 'id_group', ];
    } else {
        $header = array_keys($entries[0]);
    }
    fputcsv($csv, $header, ';');

    foreach ($entries as $entry) {
        fputcsv($csv, $entry, ';');
    }
    fclose($csv);

    // ///////////////////////////////////////////
    // / 2 - Désactivation des transporteurs
    echo "2 - Désactivation des transporteurs\n";
    echo "\t- " . $clinique->id_carrier . "\n";
    $carrier = new Carrier($clinique->id_carrier);
    if ($carrier->active) {
        $carrier->active = false;
        $carrier->deleted = true;
        $carrier->save();
    }

    echo "\t- " . $clinique->id_carrier_home . "\n";
    $carrier = new Carrier($clinique->id_carrier_home);
    if ($carrier->active) {
        $carrier->active = false;
        $carrier->deleted = true;
        $carrier->save();
    }

    // ///////////////////////////////////////////
    // / 3 - Désactivation de la boutique
    $store = new Store($clinique->id_store);
    $store->active = false;
    $store->save();

    // ///////////////////////////////////////////
    // / 4 - Désassociation du code privilège des clients
    echo "4 - Dé-association des clients du code privilège\n";
    echo "\t- Changement du groupe par défaut\n";
    $db->execute('DELETE FROM `' . _DB_PREFIX_ . 'customer_group` WHERE `id_group` = ' . (int) $clinique->id_group);
    if ($clinique->id_group_rural) {
        $db->execute('DELETE FROM `' . _DB_PREFIX_ . 'customer_group` WHERE `id_group` = ' . (int) $clinique->id_group_rural);
    }
    echo "\t- Suppression du lien avec le groupe\n";
    $db->execute('UPDATE `' . _DB_PREFIX_ . 'customer` SET `id_default_group` = 3 WHERE `id_default_group` = ' . (int) $clinique->id_group);
    if ($clinique->id_group_rural) {
        $db->execute('UPDATE `' . _DB_PREFIX_ . 'customer` SET `id_default_group` = 3 WHERE `id_default_group` = ' . (int) $clinique->id_group_rural);
    }

    // ///////////////////////////////////////////
    // / 5 - Désactivation de la clinique
    echo "5 - Désactivation de la clinique\n";
    $clinique->deleted = true;
    $clinique->save();

    // ///////////////////////////////////////////
    // / 6 - Désactivation de l'employé lié à la clinique
    echo "6 - Désactivation de l'employé lié à la clinique\n";
    $employee = new Employee($clinique->id_employee);
    $employee->active = false;
    $employee->save();
} catch (\Exception $e) {
    var_dump($e);
    exit;
}

// Purge du cache
$cache = Cache::getInstance()->delete('*');
