<?


        $torgcfg = $inCore->loadComponentConfig('torg');
	$opt = $inCore->request('opt', 'str', 'edit');
	$user_id = $inUser->id;
	$user_nickname = $inUser->nickname;
	$user_login = $inUser->login;
	$user_email = $inUser->email;

	$model = new cms_model_torg();
	$pagecfg=$model->loadTorgConfig('pages', $user_id);
	
	$instbilling=$inCore->isComponentInstalled('billing');
$inCore->includeFile('components/torg/model_users.php');	
$model_group = new cms_model_torg_users();
$banner_id = ($inDB->rows_count('cms_torg_banners', "user_id=$user_id") ? true:false);	
		

if ($banner_id) {
$inCore->loadModel('torgbanners');
$modbanner = new cms_model_torgbanners();	
$usrcan_addbanner=$model->isTorgUserCan('banner/add');


    
	

function bannerCTRbyID($id){
	    $inDB = cmsDatabase::getInstance();   
	$b = $inDB->get_fields('cms_torg_banners', 'id='.$id, 'clicks, hits');
	if ($b['hits']>0) { 
		$ctr = round((($b['clicks']/$b['hits']) * 100), 2);
	} else {
		$ctr = 0;	
	}
	return $ctr . '%';
}

function bannerHitsbyID($id){
	       $inDB = cmsDatabase::getInstance();
	$b = $inDB->get_fields('cms_torg_banners', 'id='.$id, 'maxhits, hits');
	if (!$b['maxhits']) { return $b['hits']; } else { return $b['hits'] . '/' . $b['maxhits']; }
}

 $sql_b = "SELECT * FROM cms_torg_banners WHERE user_id=$user_id LIMIT 1";
$result_b = $inDB->query($sql_b);
if ($inDB->num_rows($result_b)){
$banner = array();
$banner = $inDB->fetch_assoc($result_b);

}
$cat_id     = $banner['cat_id'];
 $cat        = $inDB->get_fields('cms_torg_cats', 'id='.$cat_id, '*');						
}
else {
$cat_id     = 1000;
$cat        = $inDB->get_fields('cms_torg_cats', 'parent_id=0', '*');	    
}	
if (!$cat){ cmsCore::error404(); }

$left_key   = $cat['NSLeft'];
$right_key  = $cat['NSRight'];
$path_list  = $model->getCategoryPath($left_key, $right_key);

$cats =	$inCore->getListItemsNS('cms_torg_cats', $cat_id);

                          
	

	
	if (usrCheckAuth()){
	
		if ($user_id){
		
				if ($opt == 'save'){
					$errors = false;
					
				
					$inCore->loadModel('registration');
					$modreg = new cms_model_registration();
					//if (!$inCore->userIsAdmin($user_id)){
//if($modreg->getBadNickname($user_nickname)) { cmsCore::addSessionMessage($_LANG['ERR_NICK_EXISTS'], 'error'); $errors = true; }
					//}
                             							
					
			
                   
			
					
					if (!$errors){
						
				
	
$cfg_page = array();	


                                        $company = $inCore->request('company', 'str');
					$phone = $inCore->request('phone', 'str');
					$mob = $inCore->request('mob', 'str');					
					$adress = $inCore->request('adress', 'str');
				        $icq = $inCore->request('icq', 'str');
					$email = $inCore->request('email', 'str');	
					$page_title = $inCore->request('page_title', 'str');
					$page_descr        = $inCore->request('page_descr', 'html', '');
					$page_show_com = $inCore->request('page_show_com', 'int');		
					$page_show_home = $inCore->request('page_show_home', 'int');	
                                       $page_show_vitrin = $inCore->request('page_show_vitrin', 'int');	
                                        $page_vitrin_title = $inCore->request('page_vitrin_title', 'str');
					    $buy_info = $inCore->request('buy_info', 'str');
					    $usrgroup = $inCore->request('usrgroup', 'int');
					    
					    
				
 $cfg_page['fastbuy'] = $inCore->request('fastbuy', 'int');					
$cfg_page['plogo']       = $inCore->request('plogo', 'int', 0);
$cfg_page['show_com']       = $inCore->request('show_com', 'int', 0);
$cfg_page['show_vitrin']       = $inCore->request('show_vitrin', 'int', 0);
$cfg_page['pageonhome']       = $inCore->request('pageonhome', 'int', 0);
$cfg_page['modclub']       = $inCore->request('modclub', 'int', 0);
$cfg_page['modsdelki']       = $inCore->request('modsdelki', 'int', 0);
$cfg_page['modcat']       = $inCore->request('modcat', 'int', 0);
$cfg_page['modotzivi']       = $inCore->request('modotzivi', 'int', 0);
$cfg_page['mapobj_id']       = $inCore->request('mapobj_id', 'int', 0);


$tematika_shop      = $inCore->request('tematika_shop', 'int', 0);
$tematika_uslugi       = $inCore->request('tematika_uslugi', 'int', 0);
$tematika_info       = $inCore->request('tematika_info', 'int', 0);

$cfg_page['page_banner']       = $inCore->request('page_banner', 'int', 0);
   
					
$model->saveTorgConfig('pages', $cfg_page, $user_id);						
	

                              if ($_FILES['page_logo']['name']) {
			
				
					 $inCore->includeGraphics();
					 
					 $uploaddir = PATH.'/images/torg_plogo/';
					 if (!is_dir($uploaddir)) { @mkdir($uploaddir); }
           			 @chmod($uploaddir, 0755);
					 
					 $realfile   = $_FILES['page_logo']['name'];
					 $path_parts = pathinfo($realfile);
					 $ext        = strtolower($path_parts['extension']);
					 
					 if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'png' && $ext != 'bmp') { cmsCore::addSessionMessage(''.$_LANG['AFISHA_ERROR_ADD_FIEL'].'', 'error'); $inCore->redirectBack(); exit; }
					 
						$filename 		= md5($realfile . '-' . $user_id . '-' . time()).'.jpg';
			
					 if(!$filename){
					 	cmsCore::addSessionMessage('123', 'error'); $inCore->redirectBack(); exit;
					 }
					$uploadfile		= $uploaddir . $realfile;
			$uploadavatar 	= $uploaddir . $filename;
			$uploadthumb 	= $uploaddir . 'small/' . $filename;
			$source			= $_FILES['page_logo']['tmp_name'];
			$errorCode 		= $_FILES['page_logo']['error'];
					 
					 if (!$inCore->moveUploadedFile($_FILES['page_logo']['tmp_name'], $uploadfile, $_FILES['page_logo']['error'])){
					 	cmsCore::addSessionMessage(''.$_LANG['AFISHA_ERROR_ADD_ERROR_PICTURE'].'', 'error');
						$inCore->redirectBack(); exit;
					 }
	//DELETE OLD AVATAR
			$sql = "SELECT page_logo FROM cms_torg_users WHERE id = '$user_id'";
			$result = $inDB->query($sql) ;
			if ($inDB->num_rows($result)){
				$old = $inDB->fetch_assoc($result);
				if ($old['page_logo'] && $old['page_logo']!='nopic.jpg'){
					@unlink(PATH.'/images/torg_plogo/'.$old['page_logo']);
					@unlink(PATH.'/images/torg_plogo/small/'.$old['page_logo']);
				}
			}
				
//CREATE THUMBNAIL
			$smallw = 105;
			 $medw = 215; 
			  $medh = 90;
						
			@img_resize($uploadfile, $uploadavatar, $medw, $medh);
			@img_resize($uploadfile, $uploadthumb, $smallw, $smallw);
						
			//DELETE ORIGINAL							
			@unlink($uploadfile);
			
		
		//MODIFY PROFILE
			$sql = "UPDATE cms_torg_users
					SET page_logo = '$filename'
					WHERE id = '$user_id'
					LIMIT 1";

			$inDB->query($sql);
						
}

	
	
	

	
$usr_ak = ($inDB->rows_count('cms_torg_users', "id=$user_id") ? true:false);
				
if ($usr_ak) {
$sql = "UPDATE cms_torg_users SET
login='$user_login',
company='$company',
phone='$phone',
mob='$mob',
icq='$icq',
email='$email',
adress='$adress',
page_title='$page_title',
page_descr='$page_descr',
page_vitrin_title='$page_vitrin_title',
buy_info='$buy_info',
group_id='$usrgroup',
tematika_shop='$tematika_shop',
tematika_uslugi='$tematika_uslugi',
tematika_info='$tematika_info'
WHERE id = {$user_id}";
}
else if(!$usr_ak){	    	
$sql = "INSERT INTO cms_torg_users (id, login, company, phone, mob,icq, email,adress, page_title,
page_descr, page_vitrin_title, buy_info, group_id, regdate)
VALUES ('{$user_id}', '$user_login', '$company', '$phone', '$mob', '$icq', '$email',  '$adress', '$page_title',
'$page_descr', '$page_vitrin_title', '$buy_info', '$usrgroup', NOW())";
}

  $inDB->query($sql);
  
  if ($usrgroup) {
$grp_price=$model_group->loadGroupConfig($usr_group['id']);
$summ=$grp_price['grp_price'];
$grp = $inDB->get_fields('cms_torg_user_groups', "id={$usrgroup}", 'title');
$users = $inDB->get_fields('cms_torg_users', "id={$user_id}", 'page_title,torg_rating');
	
  if($instbilling){
  //if (IS_BILLING) { cmsBilling::checkBalance('torg', 'grp_price'); }
      //  if (IS_BILLING) {

            cmsBilling::process('torg', 'grp_price');
	
                if ($inUser->balance >= $summ){
//минусуем баллов, если биллинг подключен
cmsBilling::pay($user_id, $summ, 'Оплата за вступление в группу - <b>'.$grp['title'].'</b>');
 //отправляем сообщение
$message = 'Пользователь <a href="/u'.$inUser->id.'.html">'.$users['page_title'].'</a> вступил в группу - <b>'.$grp['title'].'</b>';
$msg_id = cmsUser::sendMessage(1, $prodavec_id, $message);
             }  else {
$inCore->addSessionMessage('<b>Оплата не произведена! Не достаточно средств на Вашем балансе.</b> <a href="/billing">Пополните баланс >></a>', 'info');
}               
           // }

//}
  } else if(!$instbilling){
         if ($users['torg_rating'] >= $summ){	
//минусуем рейтинг, если биллинг не подключен
$inDB->query("UPDATE cms_torg_users SET torg_rating=torg_rating-$summ WHERE id=$user_id");
//отправляем сообщение
$message = 'Пользователь <a href="/u'.$inUser->id.'.html">'.$users['page_title'].'</a> вступил в группу - <b>'.$grp['title'].'</b>';
$msg_id = cmsUser::sendMessage(1, $prodavec_id, $message);
	
  } else {
$inCore->addSessionMessage('<b>Оплата не произведена! Не достаточно рейтинга.</b>', 'info');
}               
  
}
  }
  
if ($cfg['banner'] and $usrcan_addbanner) {
if (!$banner_id) {
$title = $inCore->request('title', 'str', 'Банер без названия');
			$link  = $inCore->request('link', 'str');
			
			$typeimg = $inCore->request('typeimg', 'str');
			$maxhits = $inCore->request('maxhits', 'int');

			$maxuser = 0;
			
			$published = $inCore->request('published', 'int', 0);
			$cat_id = $inCore->request('cat_id', 'int');
			
			$position = $inCore->request('position', 'str');
			
			$uploaddir = PATH.'/images/torg_banners/';		
			
			if (!is_dir($uploaddir)) { @mkdir($uploaddir); }

			$realfile = $_FILES['banner']['name'];
				$path_parts = pathinfo($realfile);
				$ext = strtolower($path_parts['extension']);
	
				if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'swf') {
				         cmsCore::addSessionMessage('тип файла неверный', 'info');
					      $inCore->redirectBack();
				    }

			$realfile = substr($realfile, 0, strrpos($realfile, '.'));
			$realfile = preg_replace ('/[^a-zA-Z0-9]/i', '', $realfile);
			$filename = $inDB->escape_string($realfile . '.' . $ext);

			$uploadfile = $uploaddir . $filename;
												
			if (@move_uploaded_file($_FILES['banner']['tmp_name'], $uploadfile)) {			
					$sql = "INSERT INTO cms_torg_banners (position, typeimg, fileurl, hits, clicks, maxhits, maxuser, user_id, pubdate, title, link, published, cat_id)
							VALUES ('$position', '$typeimg', '$filename', 0, 0, '$maxhits', '$maxuser', '$user_id', NOW(), '$title', '$link', '$published', '$cat_id')";	
					$inDB->query($sql);
			} else {
			   cmsCore::addSessionMessage('Ошибка загрузки баннера или файл не загружен!', 'info');
					      $inCore->redirectBack();	    
				   
			}
			

} else if ($banner_id) {
// редактирование

			$bid=$banner['id'];
			$title = $inCore->request('title', 'str', 'Банер без названия');
			$link  = $inCore->request('link', 'str');
			
			$typeimg = $inCore->request('typeimg', 'str');
			$maxhits = $inCore->request('maxhits', 'int');
			$maxuser = 0;
			$cat_id = $inCore->request('cat_id', 'int');
			$published = $inCore->request('published', 'int', 0);
			
			$position = $inCore->request('position', 'str');
			
			if ($_FILES['banner']['size']){

                $uploaddir = PATH.'/images/torg_banners/';

				$realfile = $_FILES['banner']['name'];
				$path_parts = pathinfo($realfile);
				$ext = strtolower($path_parts['extension']);
	
				if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'swf') {
				         cmsCore::addSessionMessage('тип файла неверный', 'info');
					      $inCore->redirectBack();
				    }
	
				$realfile = substr($realfile, 0, strrpos($realfile, '.'));
				$realfile = preg_replace ('/[^a-zA-Z0-9]/i', '', $realfile);
				$filename = $inDB->escape_string($realfile . '.' . $ext);
	
				$uploadfile = $uploaddir . $filename;

                if (@move_uploaded_file($_FILES['banner']['tmp_name'], $uploadfile)) {
                        $sql = "UPDATE cms_torg_banners SET fileurl = '$filename' WHERE id = $bid AND user_id = '$user_id'";
                       $inDB->query($sql);
                } else { $msg .= 'Ошибка загрузки баннера!'; }
            }
					
			$sql = "UPDATE cms_torg_banners
					SET position = '$position',
						title = '$title',
						published = '$published',
						maxhits = '$maxhits',
						maxuser = '$maxuser',
						typeimg = '$typeimg',
						link = '$link',
						cat_id = '$cat_id'
					WHERE id = $bid AND user_id = $user_id";
			
			
			$inDB->query($sql);	    
	    
}


}
$_LANG['PROFILE_SAVED'] = "Настройки личного раздела успешно сохранены!";
                        cmsCore::addSessionMessage($_LANG['PROFILE_SAVED'], 'info');
					      $inCore->redirectBack();
					} else  { cmsCore::addSessionMessage('Ошибка!', 'info');}
                    
				}				
				
			
				

			$sql = "SELECT ut.*, p.*
				    FROM cms_torg_users ut
					LEFT JOIN cms_user_profiles p ON p.user_id = '$user_id'
				
					WHERE ut.id = '$user_id'
					LIMIT 1
					";					
			$result = $inDB->query($sql);
			
		
				$usr = $inDB->fetch_assoc($result);
		$_LANG['CONFIG_PROFILE']="Настройки личного раздела";
				$inPage->setTitle($_LANG['CONFIG_PROFILE'].' - '.$user_nickname);
				$inPage->addPathway($user_nickname, cmsUser::getProfileURL($user_login));
				$inPage->addPathway($_LANG['CONFIG_PROFILE']);
				
				if (!$usr['is_locked']){																	
				if ($opt == 'edit'||$opt=='save'||$opt=='changepass'){
					
							
		


$sql_p = "SELECT title, id
FROM cms_torg_pages
WHERE user_id={$user_id}";	
$result_up = $inDB->query($sql_p);

 if ($inDB->num_rows($result_up)){

 $user_pages = array();
while($user_pages = $inDB->fetch_assoc($result_up)){
$upages[] = $user_pages;
	
}

}


$sql_usrgroup = "SELECT title, id FROM cms_torg_user_groups ORDER BY id ASC";	
$result_usrgroup = $inDB->query($sql_usrgroup);
if ($inDB->num_rows($result_usrgroup)){
$usr_group = array();
while($usr_group = $inDB->fetch_assoc($result_usrgroup)){
$usr_group['config']=$model_group->loadGroupConfig($usr_group['id']);
$usr_group['access_banner']=$model->isTorgUserCans('banner/add',$usr_group['id']);

$usrgroup[] = $usr_group;
}
}



if ($pagecfg['show_com']) {
	
$sql_obj = "SELECT i.title, i.id, m.addr_street, m.addr_house, m.addr_prefix
FROM cms_map_items i
LEFT JOIN cms_map_markers m ON m.item_id=i.id
WHERE i.user_id={$user_id}";	
$result_obj = $inDB->query($sql_obj);

 if ($inDB->num_rows($result_obj)){

 $map_obj = array();
while($map_obj = $inDB->fetch_assoc($result_obj)){
	
$mapobj[] = $map_obj;
	
}

}

}




	
$inPage->initAutocomplete();


$user = $inDB->get_fields('cms_torg_users', "id={$user_id}", 'company, mob, phone, adress');		
$smarty = $inCore->initSmarty('components', 'com_torg_settings.tpl');
$smarty->assign('cfg', $torgcfg);
$smarty->assign('pagecfg', $pagecfg);
$smarty->assign('opt', $opt);
$smarty->assign('usr', $usr);
$smarty->assign('user_id', $inUser->id);
$smarty->assign('user_nickname', $inUser->nickname);
$smarty->assign('user_login', $inUser->login);
$smarty->assign('user_email', $inUser->email);
$smarty->assign('usrcan_addbanner', $usrcan_addbanner);
$smarty->assign('instmaps', $inCore->isComponentInstalled('maps'));
$smarty->assign('instbilling', $instbilling);
$smarty->assign('usr_group', $usrgroup);


$smarty->assign('map_obj', $mapobj);
	


if ($banner_id){
 $smarty->assign('user_banner', $inCore->getTorgBannerById($banner['id']));
 $smarty->assign('user_banner_hits', bannerHitsbyID($banner['id']));
 $smarty->assign('user_banner_ctr', bannerCTRbyID($banner['id']));
}
 $smarty->assign('banner', $banner);
$smarty->assign('do', $do);
$smarty->assign('upages', $upages);	
$smarty->assign('cats', $cats);
$smarty->assign('cat', $cat);
$smarty->assign('cat_id', $cat_id);



				
					
					$smarty->assign('autocomplete_js', $autocomplete_js);
					
					$smarty->display('com_torg_settings.tpl');
				}
				
			} else { echo $_LANG['locked']; }
		
		} else { echo usrAccessDenied(); }
	
	} else { cmsUser::goToLogin(); }


 
 ?>