<?php
use API\Partenaire\IBatch;
use API\Partenaire\Service\PartenaireService;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\ServerRequest;
use Modules\API\APIInterne\Mail\Controller\MailController;
use Modules\Facture\Service\FactureDematBatch;
use Skeleton\Application;
use Helpers\Outil\Sql;
use Modules\Facture\Service\FactureDematStatusBatch;

$loader = require_once dirname(__DIR__) .'/vendor/autoload.php';
chdir(Application::getAppRoot());

session_start();

/**
 * Enlever la limete de temps
*/
set_time_limit(0);

/**
 * Prise en compte du contexte
 */
$_SESSION['batch'] = true;

/** Token */
$stringHash = 'fSS!fsf545f-sd5sf$0ezegfrs?df0Hf-5f04zerzerdf45$sdfsd6t5rP-r6teg4fd0?s470f.fzezfrsdf' ;

// var_dump(hash('sha256', $stringHash.'Batch:Consultation.Mail.envoieMailFournisseur00--idAO=167'));

/** init tableau POST */
$post = [];

if (isset($argc)) {
    for ($i = 0; $i < $argc; $i++) {
        if ($i == 0 && isset($argv[0])) {
            $racine = str_replace('batch.php', '', $argv[0]);
        } elseif ($i == 1 && isset($argv[1])) {
            $token = $argv[1];
        } elseif ($i == 2 && isset($argv[2])) {
            $_POST['numBroker'] = $argv[2];
        } elseif ($i == 3 && isset($argv[3])) {
            $codeTraitement = $argv[3];
            $stringHash .= str_replace(' ', '', $argv[$i]);
        } elseif ($i == 4 && isset($argv[4])) {
            $numeroTraitement = $argv[4];
            $stringHash .= str_replace(' ', '', $argv[$i]);
        } elseif ($i == 5 && isset($argv[5])) {
            $nomFichierRetour = $argv[5];
            $stringHash .= str_replace(' ', '', $argv[$i]);
        } else {
            $stringHash .= str_replace(' ', '', $argv[$i]);
            if (str_starts_with($argv[$i], '--')) {
                [$key, $value] = explode('=', $argv[$i]);
                $key           = substr($key, 2);
                $post['args'][$key]    = $value;
            } else {
                $post[] = $argv[$i];
            }
        }
    }
} else {
    echo "argc and argv disabled\n";
}

$builderInit = new DI\ContainerBuilder();
$builderInit->addDefinitions('config\configSessionInit.php');
//$builderInit->addDefinitions('config\configVersion.php');
$containerSession = $builderInit->build();
$_SESSION['Session_NumClient'] = Sql::getNumClient($containerSession->get(\PDO::class));

/*
* Recuperation et le merge des differents Modules standart et Specifique client
*/
$builder = new DI\ContainerBuilder();
$modules = Application::builderIndex(
    $builder,
    'config/configSkeleton.php',
    'config/configVersion.php',
    require 'config/Module/configModule.php',
    require 'config/Specifique/configModuleSpecifique.php'
);


$container = $builder->build();

if (hash('sha256', $stringHash) != $token) {
    echo 'token error';

    \Modules\Outil\Outil\GestionFile::creationFile("E|erreur de token", $nomFichierRetour);
    exit;
}

/**
 * CSRF : Prise en compte du CSRF car pour le batch il y a déjà un control dessus
 */
$_POST['tokenCSRF'] = \Helpers\Securite\Securite::creationTokenCSRF();

if (strpos($post[0] ?? '', 'Specifique') === 0) {
    $class = '\\Modules\\Additional\\Specifique\\Client' . $_SESSION['Session_NumClient'] . '\\Modules\\API\\Controller\\' . $codeTraitement . 'Controller';

    $execution = new $class(
        $container->get(\Skeleton\Renderer\RendererInterface::class),
        $container->get(\PDO::class),
        $container->get(\Skeleton\Router::class),
        $container->get(\Psr\Container\ContainerInterface::class)
    );

    $retour = $execution->{'batch' . $post[1] . 'Action'}($post);

    if ($retour != 'O' && $retour != '200') {
        \Modules\Outil\Outil\GestionFile::creationFile($retour, $nomFichierRetour);
    } else {
        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
    }
} elseif (strpos($codeTraitement ?? '', 'Batch') === 0) {
    [$module, $serviceName, $method] = explode('.', explode(':', $codeTraitement)[1]);
    foreach ($post['args'] as $key => $value) {
        $_POST[$key] = $value;
    }

    $classFQCN = "API\\Batch\\{$module}\\{$serviceName}";
    $class = $container->get($classFQCN);

    $container->call([$class, $method]);
} else {
    switch ($codeTraitement) {
        case 'MAJ_PARTENAIRE_FOURNISSEUR':
            switch ($post[0]) {
                case 'HIVEO':
                    $execution = new \Modules\API\APIExterne\Controller\HiveoController(
                        $container->get(\Skeleton\Renderer\RendererInterface::class),
                        $container->get(\PDO::class),
                        $container->get(\Skeleton\Router::class),
                        $container->get(\Psr\Container\ContainerInterface::class)
                    );
                    $retour =  $execution->bashAction($numeroTraitement);

                    if ($retour != 'O') {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|Problème lors de la mise à jour", $nomFichierRetour);
                    } else {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
                    }

                    break;
                case 'EAT':
                    $execution = new \Modules\API\APIExterne\Controller\EATController(
                        $container->get(\Skeleton\Renderer\RendererInterface::class),
                        $container->get(\PDO::class),
                        $container->get(\Skeleton\Router::class),
                        $container->get(\Psr\Container\ContainerInterface::class)
                    );
                    $retour =  $execution->bashAction($numeroTraitement);

                    if ($retour != 'O') {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|Problème lors de la mise à jour", $nomFichierRetour);
                    } else {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
                    }

                    break;
                case 'INFOLG':
                    $execution = new \Modules\API\APIExterne\Controller\InfoLegaleController(
                        $container->get(\Skeleton\Renderer\RendererInterface::class),
                        $container->get(\PDO::class),
                        $container->get(\Skeleton\Router::class),
                        $container->get(\Psr\Container\ContainerInterface::class)
                    );
                    $retour =  $execution->bashAction($numeroTraitement);

                    if ($retour != 'O') {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|Problème lors de la mise à jour", $nomFichierRetour);
                    } else {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
                    }

                    break;
                case 'PROVIGIS':
                    $execution = new \Modules\API\APIExterne\Controller\ProvigisController(
                        $container->get(\Skeleton\Renderer\RendererInterface::class),
                        $container->get(\PDO::class),
                        $container->get(\Skeleton\Router::class),
                        $container->get(\Psr\Container\ContainerInterface::class)
                    );
                    $retour =  $execution->bashAction($numeroTraitement);

                    \Modules\Outil\Outil\GestionFile::creationFile(
                        ($retour == 'O') ?
                            $retour . "|OK" :
                            $retour . "|Problème lors de la mise à jour",
                        $nomFichierRetour
                    );

                    break;
                case 'ALTARES':
                    $execution = new \Modules\API\APIExterne\Controller\IntuizController(
                        $container->get(\Skeleton\Renderer\RendererInterface::class),
                        $container->get(\PDO::class),
                        $container->get(\Skeleton\Router::class),
                        $container->get(\Psr\Container\ContainerInterface::class)
                    );
                    $retour = $execution->batchAction($numeroTraitement);

                    if ($retour != 'O') {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|Problème lors de la mise à jour", $nomFichierRetour);
                    } else {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
                    }

                    break;
                case 'ALTADIR':
                    $execution = new \Modules\API\APIExterne\Controller\DirectPlusController(
                        $container->get(\Skeleton\Renderer\RendererInterface::class),
                        $container->get(\PDO::class),
                        $container->get(\Skeleton\Router::class),
                        $container->get(\Psr\Container\ContainerInterface::class)
                    );
                    $retour = $execution->batchAction($numeroTraitement);

                    if ($retour != 'O') {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|Problème lors de la mise à jour", $nomFichierRetour);
                    } else {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
                    }

                    break;
                default:
                    $partn = $container->get(PartenaireService::class)->getByCode($post[0]);
                    if (! ($partn instanceof IBatch)) {
                        \Modules\Outil\Outil\GestionFile::creationFile("0|Trying to process a Partenaire without Batch interface", $nomFichierRetour);
                        break;
                    };
                    $retour = $partn->batch($numeroTraitement);
                    if ($retour != 'O') {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|Problème lors de la mise à jour", $nomFichierRetour);
                    } else {
                        \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
                    }
            }
            break;

        case 'RELANCE_HIVEO':
            $execution = new \Modules\API\APIExterne\Controller\HiveoAjaxController(
                $container->get(\Skeleton\Renderer\RendererInterface::class),
                $container->get(\PDO::class),
                $container->get(\Skeleton\Router::class),
                $container->get(\Psr\Container\ContainerInterface::class)
            );

            $retour =  $execution->relanceAllAction($numeroTraitement);

            if ($retour != 'O') {
                \Modules\Outil\Outil\GestionFile::creationFile($retour . "|Problème lors de la relance", $nomFichierRetour);
            } else {
                \Modules\Outil\Outil\GestionFile::creationFile($retour . "|OK", $nomFichierRetour);
            }


            break;
        case 'EXPORT_GRO_VOLUME':
            /**
             * TODO : Cette fonction n'est pas utilisé je pense à voir pour le kill
             */
            $execution = new \Modules\Outil\Controller\AsynchroneController(
                $container->get(\Skeleton\Renderer\RendererInterface::class),
                $container->get(\PDO::class),
                $container->get(\Skeleton\Router::class),
                $container->get(\Psr\Container\ContainerInterface::class)
            );
            $retour =  $execution->envoiEmailExportVolumineuxAction();

            break;
        case 'FLEXI_TEST_IMAP':
            $response = (new Application($container, $modules))->run(new ServerRequest(
                'GET',
                $container->get('baseUrl'). 'V2/API/mail/imap-test',
                ['Accept' => 'text/xml']
            ));
            $content = $response->getBody()->__toString();

            // Fail safe
            if (empty($content)) {
                throw new \Exception('!!!');
            }

            \Modules\Outil\Outil\GestionFile::creationFile(
                $content,
                $nomFichierRetour
            );
            break;

        case 'BYCN_API_REST':
            $execution = new \Modules\API\APIExterne\Controller\BouycoController(
                $container->get(\Skeleton\Renderer\RendererInterface::class),
                $container->get(\PDO::class),
                $container->get(\Skeleton\Router::class),
                $container->get(\Psr\Container\ContainerInterface::class)
            );

            $execution->dispatcher($post, $nomFichierRetour);
            break;
        
        case 'FAC_DEMAT_PARTN':
            // Note : load alias twig
            $container->get(\Modules\Facture\FactureModule::class);
            $container->get(\Modules\API\APIModule::class); // Required by Edicom

            $ret = (new FactureDematBatch($container->get(\Psr\Container\ContainerInterface::class)))->batch($numeroTraitement);
            $ret2 = (new FactureDematStatusBatch($container->get(\Psr\Container\ContainerInterface::class)))->batch($numeroTraitement);
            break;
        default:
            echo 'Code de Traitement non connu';
            break;
    }
}

session_destroy();
