<?php

use API\Partenaire\Service\PartenaireService;
use API\Provigis\ProvigisService;
use Helpers\Outil\EnvHelper;
use Helpers\Outil\Outils;
use Helpers\Roles\ParseConfigFile;
use Helpers\Trad\Trad;
use Helpers\Fichier\AvatarFileService;
use Helpers\Trad\TradDev;
use Helpers\Trad\TradRecette;
use Skeleton\Renderer\RendererInterface;
use Psr\Container\ContainerInterface;
use Yiisoft\Cache\WinCache\WinCache;
use Helpers\Fichier\Fichier;

if ((isset($_SESSION['AUTH_SSO']) && $_SESSION['AUTH_SSO']==1) || (isset($_SESSION['lastAUTH_SSO']) && $_SESSION['lastAUTH_SSO'] == 1)) {
    $_SESSION['lastAUTH_SSO']  = 1;
    $broker= 'sso';
} else {
    $broker = '';
}

if ($_SESSION['_brokernumber'] == 1) {
    $broker .='';
} else {
    $broker .=$_SESSION['_brokernumber'];
}

if ((
        !isset($_SESSION['Session_Login']) || $_SESSION['Session_Login'] == '' )
        && substr(str_replace('/oxaproc'.$broker.'/V2/', '', $_SERVER['REQUEST_URI']), 0, 6) != 'index/'
        && substr(str_replace('/oxaproc'.$broker.'/V2/', '', $_SERVER['REQUEST_URI']), 0, 18) != 'global/MultiSelect'
        && substr(str_replace('/oxaproc'.$broker.'/V2/', '', $_SERVER['REQUEST_URI']), 0, 4) != 'API/'
        && substr(str_replace('/oxaproc'.$broker.'/V2/', '', $_SERVER['REQUEST_URI']), 0, 5) != 'ajax/'
        && substr(str_replace('/oxaproc'.$broker.'/V2/', '', $_SERVER['REQUEST_URI']), 0, 11) != 'evaluation/'
        && (!isset($_SESSION['batch']) || (isset($_SESSION['batch']) && !$_SESSION['batch'])
    )
) {
    header('Location: /oxaproc'.$broker.'/index.php');
    exit();
}

if (substr(str_replace('/oxaproc', '', $_SERVER['REQUEST_URI']), 0, 3) == 'sso' && (!isset($_SESSION['lastAUTH_SSO']) || !$_SESSION['lastAUTH_SSO'])) {
    header('Location: ../index.php');
    exit();
}



if (!isset($_SESSION['batch']) || (isset($_SESSION['batch']) && !$_SESSION['batch'])) {
    /**
     * Recuperation des extension Twig Globale
     */
    $extention = \Skeleton\Renderer\TwigRendererFactory::getAllTwigExtensions();
} else {
    $extention;
}

/**
 * NOTE : Never use ```function() use()``` here, it will break when cached.
 */
return [
        'database.hostSQL' => $_SESSION['OXASQLDB_SERVER'],
        'database.usernameSQL' => $_SESSION['OXASQLDB_LOGIN'],
        'database.passwordSQL' => $_SESSION['OXASQLDB_P_PASSWORD'],
        'database.nameSQL' => $_SESSION['OXASQLDB_NAME'],
        
        'database.hostCAT' => $_SESSION['OXACATDB_SERVER'],
        'database.usernameCAT' => $_SESSION['OXACATDB_LOGIN'],
        'database.passwordCAT' => $_SESSION['OXACATDB_P_PASSWORD'],
        'database.nameCAT' => $_SESSION['OXACATDB_NAME'],
        
        
        'database.hostPROC' => $_SESSION['OXAPROCDB_SERVER'],
        'database.usernamePROC' => $_SESSION['OXAPROCDB_LOGIN'],
        'database.passwordPROC' => $_SESSION['OXAPROCDB_P_PASSWORD'],
        'database.namePROC' => $_SESSION['OXAPROCDB_NAME'],

        'database.hostDW' => $_SESSION['OXADWDB_SERVER'] ?? '',
        'database.usernameDW' => $_SESSION['OXADWDB_LOGIN'] ?? '',
        'database.passwordDW' => $_SESSION['OXADWDB_P_PASSWORD'] ?? '',
        'database.nameDW' => $_SESSION['OXADWDB_NAME'] ?? '',
    
        'database.hostFT' => $_SESSION['OXAFTDB_SERVER'] ?? null,
        'database.usernameFT' => $_SESSION['OXAFTDB_LOGIN'] ?? null,
        'database.passwordFT' => $_SESSION['OXAFTDB_P_PASSWORD'] ?? null,
        'database.nameFT' => $_SESSION['OXAFTDB_NAME'] ?? null,
        'driverPDO' => "odbc:Driver={ODBC Driver 18 for SQL Server};TrustServerCertificate=yes;MARS_Connection=yes;",

        'BASE' => '../../ini/base1.ini',
        
        /**
         * Recuperation des extensions
         */
        'twig.extensions' => $extention,

        'base' => '/oxaproc'.$broker.'/',
        'baseUrl' => '/oxaproc'.$broker.'/V2/',
        
        'host' => function () {
            return ParseConfigFile::getConfigFileIni()['SERVERWEBHTTP'];
        },
        'hostFront' => function () {
            return ParseConfigFile::getConfigFileIni()['SERVERWEBHTTP_FRONTAL'];
        },

        'urlOxaLink' => function (ContainerInterface $c) {
            return Outils::getPreferredProtocol()
                . $c->get('hostFront').'/oxalink'
                . Outils::getBrokerPrefix()
                . '/index.php';
        },
        'urlOxaLinkIndex' => function (ContainerInterface $c) {
            return Outils::getPreferredProtocol()
                . $c->get('hostFront')
                .'/oxalink'
                . Outils::getBrokerPrefix();
        },
        'urlOxaproc' => function (ContainerInterface $c) {
            return Outils::getPreferredProtocol()
                . $c->get('hostFront')
                .'/oxaproc'
                . Outils::getBrokerPrefix();
        },
        'urlOxaprocSso' => function (ContainerInterface $c) {
            return Outils::getPreferredProtocol()
                . $c->get('hostFront')
                . '/oxaprocsso'
                . Outils::getBrokerPrefix();
        },
        
        \Psr\Http\Message\ServerRequestInterface::class => \GuzzleHttp\Psr7\ServerRequest::fromGlobals(),

        //ResponseInterface::class => DI\Factory(ResponseInterface::class),
        RendererInterface::class => DI\Factory(\Skeleton\Renderer\TwigRendererFactory::class),
        'RendererInterface::class' => DI\Factory(\Skeleton\Renderer\TwigRendererFactory::class),
        \PDO::class => function (ContainerInterface $c) {
            return new \Skeleton\Pdo\PdoSkeletonV2(
                $c->get('driverPDO')
                . ';Server=' . $c->get('database.hostSQL')
                . ';database=' . $c->get('database.nameSQL'),
                $c->get('database.usernameSQL'),
                $c->get('database.passwordSQL')
            );
        },
        'PDO.oxasql' => function (ContainerInterface $c) {
            
            return $c->get(\PDO::class);
            
            
            // return new \Skeleton\Pdo\PdoSkeletonV2(
            //     $c->get('driverPDO')
            //     . ';Server=' . $c->get('database.hostSQL')
            //     . ';database=' . $c->get('database.nameSQL'),
            //     $c->get('database.usernameSQL'),
            //     $c->get('database.passwordSQL')
            // );
        },
        'PDO.oxacat' =>  function (ContainerInterface $c) {
            if ((bool)array_diff(
                [
                        $_SESSION['OXASQLDB_SERVER'],
                        $_SESSION['OXASQLDB_LOGIN'],
                        $_SESSION['OXASQLDB_NAME']
                    ],
                [
                        $_SESSION['OXACATDB_SERVER'],
                        $_SESSION['OXACATDB_LOGIN'],
                        $_SESSION['OXACATDB_NAME']
                    ]
            ) === false
            ) {
                return $c->get(\PDO::class);
            }
            return new \Skeleton\Pdo\PdoSkeletonV2(
                $c->get('driverPDO')
                . ';Server=' . $c->get('database.hostCAT')
                . ';database=' . $c->get('database.nameCAT'),
                $c->get('database.usernameCAT'),
                $c->get('database.passwordCAT')
            );
        },
        'PDO.oxaproc' =>  function (ContainerInterface $c) {
            if ((bool)array_diff(
                [
                        $_SESSION['OXASQLDB_SERVER'],
                        $_SESSION['OXASQLDB_LOGIN'],
                        $_SESSION['OXASQLDB_NAME']
                    ],
                [
                        $_SESSION['OXAPROCDB_SERVER'],
                        $_SESSION['OXAPROCDB_LOGIN'],
                        $_SESSION['OXAPROCDB_NAME']
                    ]
            ) === false
            ) {
                return $c->get(\PDO::class);
            }
            return new \Skeleton\Pdo\PdoSkeletonV2(
                $c->get('driverPDO')
                . ';Server=' . $c->get('database.hostPROC')
                . ";database=" . $c->get('database.namePROC'),
                $c->get('database.usernamePROC'),
                $c->get('database.passwordPROC')
            );
        },
        'PDO.oxaft' => function (ContainerInterface $c) {
            if (! isset($_SESSION['OXAFTDB_SERVER'])) {
                return $c->get(\PDO::class);
            }
            
            if ((bool)array_diff(
                [
                        $_SESSION['OXASQLDB_SERVER'],
                        $_SESSION['OXASQLDB_LOGIN'],
                        $_SESSION['OXASQLDB_NAME']
                    ],
                [
                        $_SESSION['OXAFTDB_SERVER'],
                        $_SESSION['OXAFTDB_LOGIN'],
                        $_SESSION['OXAFTDB_NAME']
                    ]
            ) === false
            ) {
                return $c->get(\PDO::class);
            }

            return new \Skeleton\Pdo\PdoSkeletonV2(
                $c->get('driverPDO')
                . ';Server=' . $c->get('database.hostFT')
                . ";database=" . $c->get('database.nameFT'),
                $c->get('database.usernameFT'),
                $c->get('database.passwordFT')
            );
        },
        'PDO.storage' =>  function (ContainerInterface $c) {

            $connexion = array(
                'DataBase' => $c->get('database.nameSQL'),
                'UID' => $c->get('database.usernameSQL'),
                'PWD' => $c->get('database.passwordSQL'),
                'CharacterSet' => 'UTF-8'
            );
            
            $conn = \sqlsrv_connect($c->get('database.hostSQL'), $connexion);
            return $conn;

            // return new \PDO("sqlsrv:server=" . $c->get('database.hostSQL') . ";database=" . $c->get('database.nameSQL'), $c->get('database.usernameSQL') , $c->get('database.passwordSQL'));
        },
        'PDO.oxadw' =>  function (ContainerInterface $c) {
            if (trim($c->get('database.hostDW')) == '') {
                return false;
            }
            try {
                return new \Skeleton\Pdo\PdoSkeletonV2(
                    $c->get('driverPDO')
                    . ';Server=' . $c->get('database.hostDW')
                    . ";database=" . $c->get('database.nameDW'),
                    $c->get('database.usernameDW'),
                    $c->get('database.passwordDW')
                );
            } catch (Exception $e) {
                return false;
            }
        },
        'settings' => [
            'displayErrorDetails' => true,
        ],
        'application.name' => 'oxaproc',
        'AvatarFileRepo' => function (ContainerInterface $c) {
            // TODO : get directory from ParseConfigFile directly instead of using SESSION
            return new AvatarFileService(Fichier::buildPath(
                realpath($_SESSION['_images']),
                'avatar'
            ));
        },
        'wincache' => function () {
            return new WinCache();
        },
        EnvHelper::class => function () {
            return new EnvHelper();
        },
        'translationService' => function (ContainerInterface $c) {
            if ($_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '127.0.0.1') {
                return new TradDev();
            }
            switch ($_SESSION['environnement'] ?? '') {
                case 'developpement':
                case 'nonregression':
                    return new TradRecette(
                        $c->get(\PDO::class),
                        $c->get('wincache'),
                        Trad::getPreferedLang(),
                        $_SESSION['_brokernumber']
                    );
            }

            return new Trad(
                $c->get(\PDO::class),
                $c->get('wincache'),
                Trad::getPreferedLang(),
                $_SESSION['_brokernumber']
            );
        },
        'ProvigisService' => function (ContainerInterface $c) {
            return new ProvigisService($c);
        },
        PartenaireService::class => function (ContainerInterface $c) {
            return new PartenaireService(
                $c->get(\PDO::class),
                $c->get('wincache'),
                $c
            );
        },
];
