<?php

/////////////////////////////
// configure installation: //
/////////////////////////////

define("ROOT", "./");
require_once( ROOT.'lib/autoload.php' );

/** @var \Base $f3 */
$f3 = \Base::instance();
$f3->set('DEBUG',3);
$f3->set('CACHE',FALSE);
$f3->set('AUTOLOAD', ROOT.'app/');
$f3->set('UI', implode(';',array(
    ROOT.'app/views/',
    ROOT.'content/' // content folders can contain .html templates
)));

if(!is_dir($f3->get('TEMP'))) {
    mkdir($f3->get('TEMP'));
}



/////////////////////////
// main configuration: //
/////////////////////////

$f3->config( ROOT.'main.cfg' );
if(!setlocale(LC_TIME, 'de_DE.UTF-8')) {

    //echo "locale not set";
}

///////////////////////////////////////////////
// configuration based on configuration file //
///////////////////////////////////////////////
// set language
$languages = $f3->get('languages');
$f3->set('default_lang', array_shift($languages));
if (in_array(strtolower($f3->get('GET.lang')), $languages)) {
  $f3->set('LANG', strtolower($f3->get('GET.lang')));
} else {
  $f3->set('LANG', $f3->get('default_lang'));
}
// set content dir
if(array_key_exists($f3->get('LANG'), $f3->get('content'))) {
  $content_dir=$f3->get('content.'.$f3->get('LANG'));
} else {
  $content_dir=$f3->get('content.'.$f3->get('default_lang'));
}
$f3->set('CONTENT', $content_dir);


function menu_recursion($m,$root="") {
    $f3 = \Base::instance();
    $out=[];
    foreach ($m as $key=>$value) {
        $folder = $key == "index" ? "" : "/".$key;
        $path = $root.$folder;

        if (is_array($value)) {
            $submenu=menu_recursion($value,$path);
            $out[$path]=$submenu[$path];
            unset($submenu[$path]);
            $out[$path]['submenu']=$submenu;
        } else {
            $ex = explode(":=", $value);
            if (count($ex) > 1) {
                # external link
                $href = $ex[1];
            } else {
                # internal link
                $href = $f3->get('SITE_URL').$path;
            }
            $out[$path]['name']=$ex[0];
            $out[$path]['href']=$href;
            
            //print($path." - ".$ex[0]." - ".$href."<br>");
        }
    }
    return $out;
}
function read_menu($menu_name) {
    $f3 = \Base::instance();
    
    if(array_key_exists($f3->get('LANG'), $f3->get('nav.'.$menu_name))) {
        $menu=$f3->get('nav.'.$menu_name.'.'.$f3->get('LANG'));
    } else {
        $menu=$f3->get('nav.'.$menu_name.'.'.$f3->get('default_lang'));
    }

    if (is_array($menu)) {
        //var_dump($menu);
        //print("<br>");
        $menu=menu_recursion($menu);
    }

    $f3->set('navi.'.$menu_name, $menu);
    //var_dump($f3->get('navi.'.$menu_name));
    //print("<br>");
}

read_menu("main");
read_menu("footer");
read_menu("network");
read_menu("languages");

// this is needed so the menu can compare the current page with a link to it
// and use this information to determine the active state
$tmp_url = substr($_SERVER['REQUEST_URI'],strlen($f3->get('SITE_URL'))+1);
$url=substr($tmp_url,0,(strpos($tmp_url,'?') === false) ? 999 : strpos($tmp_url,'?'));
$f3->set('url', explode("/", $url));


///////////////////////////////////
// development utility functions //
///////////////////////////////////

function debug($Message=".") {
    if(DEBUG > 0) {
        echo "<br>".$Message;
    } 
}


##############################################################################
// this need to go away from here -----------------------------------------
// just to be more tidy etc.
function is_image($path) {
    $ex = explode('.',$path);
    $ext = array_pop($ex);
    return in_array($ext,array( 'jpg', 'jpeg', 'png' ));
}
function pic_cache($in1,$inwidth=360){
    $f3 = \Base::instance();
    if(is_image($in1)) {
        $info = pathinfo($in1);
        $fn = basename($in1,'.'.$info['extension']);
        $width=$inwidth;
        $name = md5($in1.$width);
        
        $name =  sprintf("%s%s.png",$fn,$name);
        
        $out ='rsc/img_display/s'.$name;
    
        if(!file_exists($in1)) { $in1='rsc/img/default.png'; }
    
        if(!file_exists($out)) {
            $img1 = new Image($in1);
            $img1->resize($width);
            $f3->write($out,$img1->dump('png',9));
        }
    } elseif(!strncmp("locallink:",$in1, strlen("locallink:"))) {
      $key = substr($in1, strlen("locallink:"));
      // localize internal links
      if($f3->get('LANG') != 'DE') {
        $key .= "?lang=".$f3->get('LANG');
      }
      $out = $key;
    } else {
        $out = $in1;
    }
    return $out;
}
//------------------------------------------------------------------------
###############################################################################

if ($f3->get("GET.admin")) {
    $admin = new \Controller\Admin;
    $f3->set('backend',$admin->index());
} else {
    $f3->set('backend',false);
}

// HTML preloading of images
// this could also find some better place
$f3->mset(array(
        'cached_images' => array(\Controller\Page::check_folder_for_backgroundimage('content/'))
    ));



$f3->run();
echo \Template::instance()->render($f3->get('template'));
