<?php

class Bootstrap{
	function __construct(){
	
		Session::init();
		
		$link = isset($_GET['url']) ? $_GET['url'] : null;

		$arrayLink = explode('/',trim($link,'/'));

		$class =  $arrayLink[0] != '' ? $arrayLink[0] : 'index';
		$function = isset($arrayLink[1]) ? $arrayLink[1] : 'index';
	
		$this->validate($class,$function, $arrayLink);
	
		$path = 'controllers/' . $class . '.php';
		if(file_exists($path)){
			require_once $path;
			if(class_exists($class)){
				$mainClass = new $class();
				
				$mainClass->loadModel($class);
				if(method_exists($class,$function)){
					if(isset($arrayLink[2])){
						$mainClass->{$function}($arrayLink[2]);
					} else {
						$mainClass->{$function}('');
					}
				} else {
					$this->error();
				}
			} else {
				$this->error();
			}
		} else {
			$this->error();
		}
	}
	
	function validate($class,$function, $arrayLink){
		$session = Session::getSession('userDbUser');
		if($class == 'api'){
			$data = false;
			$ubs_data = Session::getSession('UBS_DATA');
			foreach($ubs_data as $each){
				if($each['0'] == $function) $data = $function;
			}
			if($data){
				require_once 'controllers/api.php';
				$mainClass = new $class();
				
				$mainClass->loadModel($class);
				
				$mainClass->getData($data, (isset($arrayLink[2]) ? $arrayLink[2] : 'index'));
				exit;
			}
		}elseif(!$session){
			require_once 'controllers/login.php';
			$login = new Login();
			$login->loadModel('login');
			if($class == 'index' && $function == 'login'){
				$login->login();
			} else {
				$login->index();
				exit;
			}
			exit;
		} elseif($class == 'logout'){
			Session::destroy();
			header('Location :'.URL.'');
		}
	}
	
	function error(){
		$views = new Views();
		$views->msg = 'Page is not accessible.';
		$views->render('views/error/index.php',true);
		exit;
	}
}