<?php
    header('Access-Control-Allow-Credentials: true');
    //header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: OPTIONS,GET,HEAD,PUT,PATCH,POST,DELETE');
    header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with,Authorization');
    
    ini_set("memory_limit","16G");
    ini_set("max_execution_time",4);


    if (substr(basename($_SERVER['REQUEST_URI']),0,9)=='index.php'){ 
        if (isset($_REQUEST['TEMPLATE']) && ($_REQUEST['TEMPLATE']=='NO')){

        }else{
            exit(); 
        }
    }

    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        exit;
    }

    require_once dirname(dirname(__FILE__)).'/shim/IRoute.php';
    require_once dirname(dirname(__FILE__)).'/shim/IMiddleware.php';
    require_once dirname(dirname(__FILE__)).'/shim/Router.php';


    include 'DependTree.php';
    class DependTree extends Tualo\Office\Basic\DependTree
    {

    }
    include 'TualoApplication.php';
    class TualoApplication extends Tualo\Office\Basic\TualoApplication{

    }
    

    TualoApplication::set('requestPath',dirname($_SERVER["SCRIPT_NAME"]));
    TualoApplication::set('basePath', dirname($_SERVER['SCRIPT_FILENAME']) );

    require_once TualoApplication::get('basePath').'/cmp/cmp_basic/inc/generateGUID.php';
    require_once TualoApplication::get('basePath').'/cmp/cmp_basic/inc/format.php';
    
    require_once TualoApplication::get('basePath').'/cmp/cmp_basic/clss/BASIC/clss_database_inc.php';
    require_once TualoApplication::get('basePath').'/cmp/cmp_basic/clss/MYSQL/clss_database_inc.php';
    require_once TualoApplication::get('basePath').'/cmp/cmp_basic/clss/MYSQL/clss_recordset_inc.php';
    require_once TualoApplication::get('basePath').'/cmp/cmp_basic/clss/Session.php';

    

    include TualoApplication::get('basePath').'/vendor/autoload.php';
    include 'Route.php';
    class ORoute extends Tualo\Office\Basic\Route{

    }


    TualoApplication::set('configurationFile',TualoApplication::get('basePath').'/configuration/.htconfig');
    include 'basic/basicConfiguration.php';
    $basicConfiguration();
    include_once  TualoApplication::get('basePath').'/cmp/cmp_basic/clss/TualoDBSessionHandler.php';

    include 'basic/session.php';



    
    function my_encode($val){
        return $val;
    }
    function my_decode($val){
        return $val;
    }


    $error404 = function ($path){

        TualoApplication::contenttype('text/html');
        TualoApplication::stopmiddlewares();
//        TualoApplication::stopbuffering();

        $pug = new Pug([
            'pretty' => true,
        ]);
        try{
            $pugfile = TualoApplication::get('basePath').'/pages/custom/404.pug';
            if (!file_exists( $pugfile )){
                $pugfile = dirname(__FILE__).'/pages/basic/404.pug';
            }
            TualoApplication::body( 
                    $pug->renderFile($pugfile,array(
                    'title'=>'Fehler',
                    'message'=>'404: '.$path.' wurde nicht gefunden'
                ))
            );
            TualoApplication::end();
            exit();
        }catch(Exception $e){
            echo $e->getMessage();
        }
    };
    TualoApplication::set('404',$error404);


    $maintance = function (){
        if ((TualoApplication::has('maintanceMode')) && (TualoApplication::get('maintanceMode')=='on')){
            TualoApplication::contenttype('text/html');
            TualoApplication::stopmiddlewares();
            TualoApplication::stopbuffering();
    
            $pug = new Pug([
                'pretty' => true,
            ]);
            try{
                $pugfile = TualoApplication::get('basePath').'/pages/custom/maintance.pug';
                if (!file_exists( $pugfile )){
                    $pugfile = dirname(__FILE__).'/pages/basic/maintance.pug';
                }
                TualoApplication::body( $pug->renderFile($pugfile,array(
                        'title'=>'Wartungsarbeiten',
                        'message'=>'Das System ist vorübergehend nicht zu erreichen, versuchen Sie es in einigen Minuten nochmals'
                    ))
                );
            }catch(Exception $e){
                echo $e->getMessage();
            }
        }
    };

    
    $routing = function (){
                // Add base route (startpage)
            ORoute::add('/temp/(?P<sessionid>\w+)/(?P<path>.{0,})',function($matches){
                $parsed_url = parse_url($_SERVER['REQUEST_URI']);//Parse Uri
                $path = $parsed_url['path'];
                try{
                    
                    $path = $matches['path'];
                    $file = TualoApplication::get('tempPath').'/'.$matches['path'];
                    if ($matches['sessionid']!=TualoApplication::get('session')->id()) throw  new Exception('wrong session id');
                    if (!file_exists( $file )) throw  new Exception('file not found');
                    if (substr(basename($matches['path']),0,1)=='.')  throw new Exception('file not found');


                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename="'.basename($file).'"');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($file));
                    readfile($file);
                    exit();

                }catch(Exception $e){
                    $error404 = TualoApplication::get('404')($path);
                    $error404($path);
                }

            });
                
            ORoute::add('/',function(){
                TualoApplication::contenttype('text/html');
                $pug = new Pug([
                    'pretty' => true,
                ]);
                try{
                    $pugfile = TualoApplication::get('basePath').'/pages/custom/index.pug';
                    if (!file_exists( $pugfile )){
                        $pugfile = dirname(__FILE__).'/pages/basic/index.pug';
                    }
                    $params = array(
                        'title'             =>  TualoApplication::get('htmltitle','tualo office'),
                        'shortcut_iconurl'  => "./cmp/cmp_template_default/img/logo.ico",
                        'stylesheets'       =>  TualoApplication::stylesheet(),
                        'javascripts'       =>  TualoApplication::javascript()

                    );
                    if (defined('SHORTCUT_ICONURL')) {
                        $params[ 'shortcut_iconurl' ] = SHORTCUT_ICONURL;
                    }
                    TualoApplication::body( $pug->renderFile($pugfile,$params));

                }catch(Exception $e){
                    echo $e->getMessage();
                }
            });

            ORoute::add('/index.php',function(){
                TualoApplication::contenttype('text/html');
                TualoApplication::stopmiddlewares();
                TualoApplication::stopbuffering();
                try{
                    include "old.php";
                }catch(Exception $e){
                    echo $e->getMessage();
                }
            },array('get','post','put'));
            ORoute::run(TualoApplication::get('requestPath'));

            
    };

    
    
    ORoute::pathNotFound($error404);
    
    if (defined('TEMP_PATH')){
        TualoApplication::set('tempPath', TEMP_PATH );
    }else{
        TualoApplication::set('tempPath', TualoApplication::get('basePath') .'/temp' );
    } 
    
    define('__REAL_PATH__', TualoApplication::get('basePath') ); // old style definition please use TualoApplication::get('basePath') instead!
    
    


    //TualoApplication::use('basic',$basicConfiguration,-9999999);
    //include TualoApplication::get('basePath').'/cmp/cmp_basic/clss/Session.php';

    openlog("TualoApplication", LOG_PID | LOG_PERROR, LOG_LOCAL0);

    

    $tualoApplicationSessionsMiddleware();

    TualoApplication::initComponents();
    //syslog(LOG_WARNING,"".print_r( TualoApplication::components(),true ));
    
    
 
    foreach (glob(TualoApplication::get('basePath').'/cmp/*/middleware/*.php') as $filename) {
        include $filename;
    }

    foreach (glob(TualoApplication::get('basePath').'/cmp/*/routing/*.php') as $filename) {
        //syslog(LOG_WARNING,"$filename - ".session_id());
        include $filename;
    }

    $classes = get_declared_classes();
       
    foreach($classes as $cls){
        $class = new \ReflectionClass($cls);
        if ( $class->implementsInterface('Tualo\Office\Basic\IMiddleware') ) {
            $cls::register();
        }
    }

    



    foreach (glob(TualoApplication::get('basePath').'/cmp/*/classloader.json') as $filename) {
        $json = json_decode(file_get_contents($filename),true);
        if (is_null($json)){
        throw new Exception($filename." is invalid",1);
        }
        if (is_array($json)){
        foreach($json as $entry){
            include dirname($filename).'/'.$entry;
        }
        }
    }

    TualoApplication::use('maintance',$maintance);
    TualoApplication::use('routing',$routing);
    TualoApplication::run();
    closelog();
