<?php

require __DIR__.'/sysgod/bootstrap.php';

session_start();

include INCLUDE_PATH.'database.php';
include INCLUDE_PATH.'view.php';
include INCLUDE_PATH.'script.php';
include INCLUDE_PATH.'language.php';
include INCLUDE_PATH.'utf8.php';
include INCLUDE_PATH.'mailer.php';


$database = new database( $database_config , MEMCACHE_KEY);

// priema parameter id-to na sajta
$smarty = new bh_smarty(SITE_PATH);
$script = new script;

$database->connect();

//print_r($language->dictionary);



require __DIR__.'/common/functions.php';



$module = $script->parameter(1);


// [ LANGUAGE CHANGE

$poslang = $script->parameter(0);

$lang_dir = '';

if(strpos(($_SERVER['SERVER_NAME'] ?? ''),'homesbg.ru') !== false or $poslang == 'ru'){
	//$module = 'main';
	$_SESSION['site_language'] = 'ru';
	$lang_dir = '/ru';
}elseif(strpos(($_SERVER['SERVER_NAME'] ?? ''),'imotitebg.com') !== false or $poslang == 'bg'){
	$_SESSION['site_language'] = 'bg';
	$lang_dir = '/bg';
} else {
	$_SESSION['site_language'] = 'en';
}


// only the two existing themes: "" (old) and ".new"; the value ends up in template paths
if(isset($_GET['theme']) && ($_GET['theme'] ?? '') == 'new')
	$_SESSION['theme'] = '.new';
elseif(isset($_GET['theme']) && ($_GET['theme'] ?? '') ==''){
	$_SESSION['theme'] = '';
} 

if(!isset($_SESSION['theme']) || (($_SESSION['theme'] ?? null) != '' && ($_SESSION['theme'] ?? null) != '.new'))	$_SESSION['theme'] = '.new';

//$_SESSION['theme'] = '.new';
	
	

if($module == 'language'){
	$module = 'main';

	$_SESSION['site_language'] = $script->parameter(2);

	header("Location: /");
	exit;
}
// ] LANGUAGE CHANGE




if(($_SESSION['site_language'] ?? null) != '')
	$language = new language(($_SESSION['site_language'] ?? null));
else
	$language = new language('en');

//echo $module;
$page = $database->get_records("SELECT * FROM pages WHERE url_name = '".$database->escape(str_replace('-', ' ', $module))."'", true);


$do_not_unsubscribe = array('office@bulgarianhouse.com', 'bulgarianproperties4all@gmail.com', 'office@homesbg.ru', 'office@imotitebg.com');

if(isset($_GET['unsubscribe']) && !in_array(($_GET['unsubscribe'] ?? ''), $do_not_unsubscribe)){
	$unsubscribe_email = $database->escape(($_GET['unsubscribe'] ?? ''));
	$database->query("UPDATE emails SET newsletter = 0 WHERE email LIKE '".$unsubscribe_email."'");
	die('Your email '.htmlspecialchars(($_GET['unsubscribe'] ?? ''), ENT_QUOTES, 'UTF-8').' has been removed from our mail list.');
}

if(!empty($page)){

	$module = $page['module'];
	$template = $page['template'];

	if($page['language'] != $language->get_current())	$language = new language($page['language']);
} else {


	if($script->parameter(1) != ''){
		

		die_404();
		
		
	} else {
		$module = 'main';
		$template = 'main';

		$page = $database->get_records("SELECT * FROM pages WHERE module = '".str_replace('-', ' ', $module)."' AND language = '".$language->get_current()."'", true);
	}
}



if($lang_dir != '/ru' && $language->get_current() == 'ru'){

	header( "HTTP/1.1 301 Moved Permanently" );
	header( "Location: /ru".($_SERVER['REQUEST_URI'] ?? '')); 
	//die_404();
	exit;
}

if($lang_dir != '/bg'  && $language->get_current() == 'bg'){

	header( "HTTP/1.1 301 Moved Permanently" );
	header( "Location: /bg".($_SERVER['REQUEST_URI'] ?? '')); 
	//die_404();
	exit;
}



if( (strlen($poslang) == 2 and $poslang != $language->get_current()) or ($poslang == '' and $language->get_current() != 'en' ) ){
	header( "HTTP/1.1 301 Moved Permanently" );
	header( "Location: ".$lang_dir.'/'); 
	//die_404();
	exit;
}


$smarty->assign('page', $page);
$smarty->assign('_page', $page);



/////////////////////////////////////////////////////////////////////////////////


$languages = $database->get_records("
	SELECT l.*, p.name as url FROM languages as l 
	JOIN pages as p ON l.iso = p.language 
	WHERE p.module = 'main' 
	
");



$smarty->assign('languages', $languages);

$pages = $database->get_records("SELECT * FROM pages WHERE language = '".$language->get_current()."'");

for($i = 0; $i < count($pages); $i ++){

	$language->add_entry('u', $pages[$i]['module'], $pages[$i]['url_name']);
	$language->load_module($pages[$i]['module']);
}

$smarty->assign('pages', $pages);

$database->set_cache_expire(24 * 3600);
$regions = $database->get_records("SELECT DISTINCT r.* FROM regions as r  JOIN offers as o ON r.group_id = o.region WHERE r.language = '".$language->get_current()."' AND o.active = 1 ORDER BY r.name ASC");

for($i = 0; $i < count($regions); $i ++){
    $database->set_cache_expire(24 * 3600);
	$regions[$i]['subregions'] = $database->get_records("SELECT DISTINCT sr.* FROM subregions as sr JOIN offers as o ON sr.group_id = o.subregion WHERE sr.region_id = '".$regions[$i]['id']."' AND sr.language = '".$language->get_current()."' AND o.active = 1 ORDER BY sr.name ASC");

}




$smarty->assign('regions', $regions);

$database->set_cache_expire(24 * 3600);
$types = $database->get_records("SELECT * FROM types WHERE language = '".$language->get_current()."' ORDER BY name ASC");

$smarty->assign('types', $types);

$database->set_cache_expire(24 * 3600);
$locations = $database->get_records("SELECT * FROM locations WHERE language = '".$language->get_current()."' ORDER BY name ASC");

$smarty->assign('locations', $locations);

// random banner graphics in the main template
$banners['left'] = rand(1, 4).'.jpg';
$banners['right'] = rand(5, 7).'.jpg';

$smarty->assign('banners', $banners);

////////////////////////////////////////////////////////////////////////////////


$command = $language->reverse('u:'.$script->parameter(2));
$item = $script->parameter(3);


if($command == '' || is_numeric($command))	$command = 'main';

//echo $command;

// the public site has no login of its own
$is_logged = 0;
$smarty->assign('is_logged', $is_logged);

$smarty->assign('user', ($_SESSION['user'] ?? null));

//print_r($language->dictionary);

// smarty modifier
$smarty->register_modifier('as', 'addslashes');
$smarty->register_modifier('ss', 'stripslashes');
$smarty->register_modifier('slower', 'utf8_strtolower');
$smarty->register_modifier('urle', 'rawurlencode');
$smarty->register_modifier('purl', 'purl');
$smarty->register_modifier('st', 'strip_tags');
$smarty->register_modifier('st_custom', 'strip_tags_custom');

$smarty->register_modifier('hsc', 'htmlspecialchars');
$smarty->register_modifier('hsc_custom', 'htmlspecialchars');

$smarty->assign('item', $item);

$smarty->assign('module', $module);
$smarty->assign('language', $language);


$smarty->assign('SITE_NAME', SITE_NAME);


$search_locations = get_select_options('locations');
$search_types = get_select_options('types');
$search_regions = get_select_options('regions');
//$search_subregions = get_select_options('subregions');

$smarty->assign('search_locations', $search_locations);
$smarty->assign('search_types', $search_types);
$smarty->assign('search_regions', $search_regions);

$database->set_cache_expire(24 * 3600);
$global_news = $database->get_records("
	SELECT * 
	FROM news 
	WHERE language = '". $language->get_current() ."' 
	AND active = 1 
	ORDER BY date DESC 
	LIMIT 7"
);

$smarty->assign('global_news', $global_news);

$database->set_cache_expire(24 * 3600);
$global_offers = $database->get_records("
	SELECT SQL_CALC_FOUND_ROWS o.*, i.name as i_name, i.description as i_description FROM offers as o 
	JOIN images as i ON i.group_id = o.group_id 
	WHERE o.language = '". $language->get_current() ."' 
	AND i.default = 1 
	AND active = 1 
	ORDER BY o.date DESC
	LIMIT 7"
);


for( $i = 0; $i < count($global_offers); $i ++){
	$global_offers[$i]['region_text'] = get_select_option('regions', $global_offers[$i]['region']);
	$global_offers[$i]['type_text'] = get_select_option('types', $global_offers[$i]['type']);
}

$smarty->assign('global_offers', $global_offers);


$global_comment = $database->get_records("
	SELECT * 
	FROM comments
	WHERE approved = 1 
	ORDER BY RAND() DESC
	LIMIT 1", true
);

if(is_array($global_comment)){
	$global_comment['date_format'] = date("m/d/Y", strtotime($global_comment['date']));
	$global_comment['email_format'] = str_replace('@', ' (at) ', $global_comment['email']);
}


$smarty->assign('global_comment', $global_comment);





$global_offers_count = 5000 + $database->get_result("SELECT COUNT(group_id) FROM offers WHERE status != 1 AND language = '".$language->get_current()."'");

$smarty->assign('global_offers_count', $global_offers_count);

$command_template = $command;

include SITE_PATH."./modules/".$module."/".$command.".php";

$smarty->assign('command', $script->parameter(2));
$smarty->assign('lang_dir', $lang_dir);



//echo SITE_PATH.'modules/'.$module.'/'.$command.'.tpl.html';
$module_template = SITE_PATH.'modules/'.$module.'/'.$command_template.($_SESSION['theme'] ?? null).'.tpl.html';

// a few modules have no template for the new theme: use the old one
// (Smarty 2 silently rendered nothing; Smarty 5 stops with an error)
if(!is_file($module_template))	$module_template = SITE_PATH.'modules/'.$module.'/'.$command_template.'.tpl.html';

$template_content = $smarty->fetch($module_template);

$smarty->assign('template_content', $template_content);


$smarty->display($template.($_SESSION['theme'] ?? null).'.tpl.html');


$database->close();


?>