<?php

/**
 * @author    Daniel Franke <info@df-web.net>
 * @copyright 2009 - 2019
 *
 * @var $hyperlink
 *
 * $Date: 2019-05-25 23:13:15 +0200 (Sat, 25 May 2019) $
 * $Rev: 555 $
 */

use Jenssegers\Agent\Agent;
use LkwSim\Index\Filemanagement;
use Twig\Environment;
use Twig\Extension\DebugExtension;
use Twig\Loader\FilesystemLoader;
use User\User;

session_start();

require_once(__DIR__ . '/setup.php');
require_once(__DIR__ . '/index/Filemanagement.class.php');

$file       = new Filemanagement();
$site_title = '';
list($script, $template, $site_title) = $file->load();

if ($template != 'logout' && User::hasValidSession())
{
    header('location:' . $hyperlink->game('wohnung'));
    exit;
}

$_isException = 0;
$_success     = false;

if (Session::has('success'))
{
    $_success = Session::get('success');
    Session::delete('success');
}

if ( ! isset($_COOKIE['mobile-version']))
{
    $agent = new Agent();
    if ($agent->isMobile())
    {
        setcookie('mobile-version', '1');
    }
}

$loader = new FilesystemLoader('templates');
$twig   = new Environment($loader, ['debug' => true]);
$twig->addExtension(new DebugExtension());
$twig->addGlobal('Helper', new Helper());
$twig->addGlobal('cookie', $_COOKIE);
$twig->addGlobal('session', $_SESSION);
$twig->addGlobal('server', $_SERVER);
$twig->addGlobal('hyperlink', $hyperlink);
$twig->addGlobal('file', $file);
$twig->addGlobal('site_title', $site_title);

// Templates
$scriptFile        = __DIR__ . '/index/scripts/' . $script . '.php';
$templateVariables = [];

try
{
    //Einbinden der individuellen Skript-Datei
    if ($script && is_readable($scriptFile))
    {
        require_once($scriptFile);
    }
}
catch (myException $e)
{
    $twig->addGlobal('e', $e);
    $_isException = 1;
}

$twig->addGlobal('_isException', $_isException);
$twig->addGlobal('_success', $_success);

if (isset($templateVariables['reason']))
{
    $templateVariables = array_merge($templateVariables, [
        'classname' => strpos($templateVariables['reason'], 'erfolgreich') ? 'alert-success' : 'alert-warning',
    ]);
}

if ($template === 'logout')
{
    $template          = 'start';
    $templateVariables = array_merge($templateVariables, ['logout' => true]);
}

echo $twig->render('landy/' . $template . '.twig', $templateVariables);
