<?php

// 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()) {
    die(1);
}

/////////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.inc.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();
}

Module::getInstanceByName('myvetshopclinique');

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

$context = Context::getContext();
$context->language = new Language(1);

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

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 < 0; ++$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 du code privilège de la clinique
    echo "2 - Désactivation du groupe de clients\n";
    echo "\t- " . $clinique->id_group . "\n";
    $group = new Group($clinique->id_group);
    $group->name = [Context::getContext()->language->id => 'delete-' . $clinique->code_privilege];
    $group->save();

    if ($clinique->id_group_rural) {
        echo "2b - Désactivation du groupe de clients rural\n";
        echo "\t- " . $clinique->id_group_rural . "\n";
        $group = new Group($clinique->id_group_rural);
        $group->name = [Context::getContext()->language->id => 'delete-' . $clinique->code_privilege];
        $group->save();
    }

    /////////////////////////////////////////////
    /// 3 - Désactivation des transporteurs
    echo "3 - 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();
    }

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

    /////////////////////////////////////////////
    /// 5 - Désassociation du code privilège des clients
    echo "5 - 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('*');
