<?php

namespace Myvetshop\Module\Clinique\Command\Clinic;

use Doctrine\ORM\EntityManagerInterface;
use Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class ClinicDeactivateCommand extends Command
{
    private \Db $db;

    private EntityManagerInterface $em;

    private MyvetshopCliniqueRepository $myvetshopCliniqueRepository;

    protected function configure(): void
    {
        $this
            ->setDescription("Désactivation d'une clinique")
            ->addArgument(
                'code_privilege',
                InputArgument::REQUIRED,
                'Code privilège de la clinique'
            );
    }

    public function __construct(
        \Db $db,
        EntityManagerInterface $em,
        MyvetshopCliniqueRepository $myvetshopCliniqueRepository
    ) {
        $this->db = $db;
        $this->em = $em;
        $this->myvetshopCliniqueRepository = $myvetshopCliniqueRepository;

        parent::__construct('app:clinic:deactivate');
    }

    public function execute(InputInterface $input, OutputInterface $output): int
    {
        $styledOutput = new SymfonyStyle($input, $output);

        $codePrivilege = $input->getArgument('code_privilege');

        \assert(\is_string($codePrivilege));

        $clinique = $this->myvetshopCliniqueRepository->findByCodePrivilege($codePrivilege);

        if (!$clinique) {
            $styledOutput->error('Code privilège non trouvé');

            return 1;
        }

        if ($clinique->deleted) {
            $styledOutput->error('Clinique ' . $codePrivilege . ' déjà désactivée');

            return 1;
        }

        $styledOutput->title('Désactivation de la clinique ' . $codePrivilege);

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

        // étape 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-' . $codePrivilege . '-' . \date('YmdHis') . '.csv';

        $styledOutput->section('1 - Extraction des clients actuels -> ' . $outputClientsFileName);
        $csv = \fopen($outputClientsFileName, 'w+');

        if (!$csv) {
            $styledOutput->error('Erreur lors de la création du fichier.');

            return 1;
        }

        $entries = $this->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->idGroup . ' AND c.`deleted` != 1 AND c.id_shop IN (1)'
            . ' ORDER BY `id_group` ASC'
        );

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

        $styledOutput->writeln(\count($entries) . ' clients exportés');

        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
        $styledOutput->section('2 - Désactivation des transporteurs');
        $styledOutput->writeln("\t- " . $clinique->idCarrier);
        $carrier = new \Carrier($clinique->idCarrier);
        if ($carrier->active) {
            $carrier->active = false;
            $carrier->deleted = true;
            $carrier->save();
        }

        $styledOutput->writeln("\t- " . $clinique->idCarrierHome);
        $carrier = new \Carrier($clinique->idCarrierHome);
        if ($carrier->active) {
            $carrier->active = false;
            $carrier->deleted = true;
            $carrier->save();
        }

        // 3 - Désactivation de la boutique
        $styledOutput->section('3 - Désactivation de la boutique');
        // @phpstan-ignore-next-line
        $store = new \Store($clinique->idStore);
        $store->active = false;
        $store->save();

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

        // 5 - Désactivation de la clinique
        $styledOutput->section('5 - Désactivation de la clinique');
        $clinique->deleted = true;
        $this->em->flush();

        // 6 - Désactivation de l'employé lié à la clinique
        $styledOutput->section("6 - Désactivation de l'employé lié à la clinique");
        $employee = new \Employee($clinique->idEmployee);
        $employee->active = false;
        $employee->save();

        \Cache::getInstance()->delete('*');

        return 0;
    }
}
