<?php
// Включаем f3
ini_set('serialize_precision', -1);
ini_set('max_execution_time', 300);
ini_set('session.gc_maxlifetime', 43200);

function numberformat($a, $d, $d_separator='.', $th_separator='') {
	$int=floor($a);
	if($int==$a) {
		return $int;
	}

	return number_format($a, $d, $d_separator, $th_separator);
}

if( !function_exists('mb_str_split')){
    function mb_str_split(  $string = '', $length = 1 , $encoding = 'UTF-8' ){
        if(!empty($string)){ 
            $split = array();
            $mb_strlen = mb_strlen($string,$encoding);
            for($pi = 0; $pi < $mb_strlen; $pi += $length){
                $substr = mb_substr($string, $pi,$length,$encoding);
                if( !empty($substr)){ 
                    $split[] = $substr;
                }
            }
        }
        return $split;
    }
}


$f3=require('lib/base.php');

$f3->set('DEBUG',1);

// Загружаем конфиг
$f3->config('app/config.ini');
// Загржаем роут
$f3->config('app/routes.ini');

$f3->set('ONERROR', function(){
	global $f3;
	$error=$f3->get('ERROR');
	if(!preg_match('//u', $error['text'])) {
		foreach ($error as $key => $value) {
			$error[$key]=iconv('windows-1251', 'utf-8', $value);
			$f3->set('ERROR', $error);
		}
	}
	$logs_model=$f3->get('logs_model');
	if($logs_model) {
		$logs_model->save_log(implode('<br>', $error), 'error');
	}
	$messages=new \Models\Messages();
	if($f3->get('AJAX')) {
		$f3->status(200);
		$data=$messages->page_data('error');
		$f3->set('page_data', $data);
		echo \Template::instance()->render($data['inc']);
	}
	elseif(mb_strpos($error['trace'], "Models\Cd")>0) {
		if($f3->get('GET.cd_unset')) {
			$f3->reroute('/');
		}
		$f3->set('page_data', $messages->page_data('cd_error'));
		echo \Template::instance()->render('layout.htm');
	}
	elseif(mb_strpos($error['trace'], "Models\Scales")>0) {
		if($f3->get('GET.scales_unset')) {
			$f3->reroute('/');
		}
		$f3->set('page_data', $messages->page_data('scales_error'));
		echo \Template::instance()->render('layout.htm');
	}
	else {
		$f3->set('page_data', $messages->page_data('error'));
		echo \Template::instance()->render('layout.htm');
	}
});

$f3->run();