<?
 global $_LANG;
//в кавычках $yakey, Введите Ваш API ключ, который можете получить здесь: http://api.yandex.ru/maps/form.xml/
$yakey="ADuX9U8BAAAAfJgVUAIAipxiGDL85Ni-exoYjqmJGbSKc5wAAAAAAAAAAAA5CeQrZT5zRfDFCfmkP9EFfso69w==";

    $model = new cms_model_torg();
    $shop_detected = $inDB->rows_count('cms_torg_users', "id={$id}");
if (!$shop_detected) {
    $inCore->redirectBack();

}
    $pagecfg = $model->loadTorgConfig('pages', $id);
$mapobj_id=($pagecfg['mapobj_id']?'MI.id = '.$pagecfg['mapobj_id']:'MI.user_id = TU.id');
  
  $usrsql = "SELECT TU.*, P.*, U.nickname,
    MI.seolink as obj_link,
  MI.id as obj_id
  FROM cms_torg_users TU
  LEFT JOIN cms_user_profiles P ON P.user_id = TU.id
  LEFT JOIN cms_users U ON U.id = TU.id
  LEFT JOIN cms_map_items MI ON $mapobj_id
  WHERE TU.id = $id";

	
$usrresult = $inDB->query($usrsql);
	
if ($inDB->num_rows($usrresult)>0){
    
$user = array();
$maps = array();
$usr = $inDB->fetch_assoc($usrresult);

}
		
		$inPage->addPathway('Личные разделы', '/sites');
		$inPage->addPathway($usr['page_title']);
                $inPage->setTitle($usr['page_title'].' - Личные разделы');

		
	if($cfg['sw_wall']){
	    
               $usr_wall_html = $model->getTorgWall($usr['id']);
                $usr_addwall_html = $model->getTorgAddWall($usr['id']);
	}
		
$usr['avatar'] = usrLink(usrImageNOdb($usr['id'], 'small', $usr['imageurl'], $usr['is_deleted']), $usr['login'], $menuid);
$usr['flogdate'] = strip_tags(usrStatus($usr['id'], $usr['flogdate'], false, $usr['gender']));
$usr['status'] = ($usr['flogdate'] == $_LANG['ONLINE'] ? '<span class="on">'.$_LANG['ONLINE'].'</span>' : '<span class="off">'.$_LANG['OFFLINE'].'</span>');
$usr['regdate']         = cmsCore::dateDiffNow($usr['regdate']); 
$usr['torg_count'] = $inDB->rows_count('cms_torg_items', "user_id={$usr['id']} AND published=1   AND prodano != 1 AND kolvo != 0 AND archive != 1");

$usr['karma'] = strip_tags( $model->getTorgKarmaFormat($usr['id'], false), '' );




 if ($_REQUEST['vid']=='list') $vid_cat='list/'; 
 else  if ($_REQUEST['vid']=='price') $vid_cat='price/'; 
 else $vid_cat=""; 
 

if (isset($_REQUEST['cat_id'])) {
    $catid='/c'.$_REQUEST['cat_id'];
    $cat_title = $inDB->get_field('cms_torg_cats', "id = '{$_REQUEST['cat_id']}'", 'title');
 } else {$catid="/";}

 
 
 
if ($_REQUEST['op']=='view_news' || $_REQUEST['op']=='view_events'){
///////Новости, события
if ($_REQUEST['op']=='view_news') {
		     $inPage->setTitle('Новости - '.$usr['page_title'].' - Личные разделы');
}
if ($_REQUEST['op']=='view_events') {
			     $inPage->setTitle('События - '.$usr['page_title'].' - Личные разделы');
}

    	$sqlevents=($_REQUEST['op']=="view_events" ? "AND is_event=1" : "AND is_event=0");
		$sql_news = "SELECT *
			FROM cms_torg_pages WHERE user_id={$usr['id']} AND is_news=1 $sqlevents		
			ORDER BY pubdate DESC";		

		$result_news = $inDB->query($sql_news);
		if ($inDB->num_rows($result_news)){
			$news = array();
			while($con = $inDB->fetch_assoc($result_news)){
			    $con['link']=($_REQUEST['op']=='view_news' ? '/u'.$usr['id'].'/news/'.$con['url'].'.html' : '/u'.$usr['id'].'/events/'.$con['url'].'.html');
			    	
				$con['eventstart']  = cmsCore::dateformat($con['event_start']);
				$con['eventend']  = cmsCore::dateformat($con['event_end']);
				$news[] = $con;
			}
	
		}
/////    
}




if ($_REQUEST['op']=="view_page" || $_REQUEST['op']=="view_news_one" || $_REQUEST['op']=="view_event"){
    	
	    
$url 	= $inCore->request('url', 'str', '');
if ($_REQUEST['op']=="view_news_one" || $_REQUEST['op']=="view_event"){
$view_page    = $inDB->get_fields('cms_torg_pages',  "user_id='{$id}' AND url='{$url}' AND is_news=1", 'id,news_content,title,hot_news,is_event,event_start,event_end,event_adress,pubdate');
$inPage->setTitle($view_page['title'].' - Новости, события - '.$usr['page_title'].' - Личные разделы');
}else{
 $view_page    = $inDB->get_fields('cms_torg_pages',  "user_id='{$id}' AND url='{$url}' AND is_news=0", 'id,message,title');
 $inPage->setTitle($view_page['title'].' - '.$usr['page_title'].' - Личные разделы');
}
}
$sql_p = "SELECT title, url, show_link
			FROM cms_torg_pages
			WHERE user_id={$id} AND is_news=0
			ORDER BY id";	
$result_up = $inDB->query($sql_p);


if ($inDB->num_rows($result_up)>0){
$ups = array();
while($up = $inDB->fetch_assoc($result_up)){
$ups[] = $up;
}
}
$awards = $inDB->get_field('cms_user_awards', "user_id = '{$usr['id']}'", 'title, description,imageurl');

if ($inUser->id){
$moderator = ($inCore->userIsAdmin($inUser->id) || $inCore->isUserCan('torg/moderate') || $upage['user_id'] == $inUser->id);
} else {
$moderator = false;
}
	

	
	
	if ($_REQUEST['op']!=="view_page" and $_REQUEST['op']!=="view_news_one" and $_REQUEST['op']!=="view_event" and $_REQUEST['op']!=="view_news" and $_REQUEST['op']!=="view_events"){

if ($pagecfg['show_vitrin'] || $_REQUEST['op']=="tovari" || $_REQUEST['cat_id']) {
    if ($_REQUEST['op']=="tovari"){
	    $inPage->setTitle('Товары - '.$usr['page_title'].' - Личные разделы');
    }
	    
if (isset($_REQUEST['cat_id'])) $sql_cat_id="AND category_id='".$_REQUEST['cat_id']."'"; else $sql_cat_id=""; 
if (isset($_REQUEST['cat_id'])) $vid_cat_id='/c'.$_REQUEST['cat_id'].'.html'; else $vid_cat_id=""; 

$isql = "SELECT *, IF(DATE_FORMAT(pubdate, '%d-%m-%Y')=DATE_FORMAT(NOW(), '%d-%m-%Y'), DATE_FORMAT(pubdate, '<strong>{$_LANG['TODAY']}</strong>'), DATE_FORMAT(pubdate, '%d-%m-%Y'))  as fpubdate
	 FROM cms_torg_items
	 WHERE user_id = $id $sql_cat_id AND published=1 AND kolvo !=0 AND prodano!=1 AND archive!=1
	 ORDER BY id DESC
	";
		
		$perpage = 12;
		if (isset($_REQUEST['page'])) { $page = abs((int)$_REQUEST['page']); } else { $page = 1; }
		$isql .= "LIMIT ".($page-1)*$perpage.", $perpage";
		
		

    
if ($page==1) $nupage = 'p1.html'; else $nupage='p'.$_REQUEST['page'].'.html';
$date=date('Y-m-d H:i:s');
$iresult = $inDB->query($isql);
if ($inDB->num_rows($iresult)>0){
$items = array();

while($item = $inDB->fetch_assoc($iresult)){
    


$item['ratingdata'] = $model->ratingData($item['id']);
$item['stavkaData'] = $model->stavkaData($item['id']);
$item['stavka'] = $model->buildStavka($item['stavkaData']['stavka']);


$item['au_ppsdate'] = $model->AuPPS($au_ppsdate, $item['id']);
$au_enddate = ($item['au_endtype'] == 2 ? $item['au_ppsdate']['ppsend'] : $item['au_enddate']);
$item['au_end'] = ($au_enddate < $date ? true : false);
if (!$item['au_ppsdate']['ppsend'] and $item['au_endtype']==2) $item['au_end']=false;
			
$item['prodanodata'] = $model->prodanoData($item['id']);
$item['fdata'] = unserialize($item['fieldsdata']);
$item['price'] = number_format(shopDiscountPrice($item['id'], $item['category_id'], $item['price']), 0, '.', ' ');
$item['prodano'] = $model->buildProdano($item['prodanodata']['prodano']);
$item['rating'] = $model->buildRating($item['ratingdata']['rating']);
$item['bayed'] = $model->buildRating($item['ibuydata']['bayed']);
$item['is_in_cart'] = $model->isItemInCart($item['id']);
$item['rew_count']=$inDB->rows_count('cms_torg_rew', "target_id={$item['id']} AND published=1 AND parent_id=0");

$items[] = $item;
}
}	

}
}



 

if ($pagecfg['modcat']) {
 // рубрикатор	   
$sq_cat = "SELECT i.category_id, c.title as cat_title, COUNT(i.id) as torg_count 
FROM cms_torg_items i
LEFT JOIN cms_torg_cats c ON c.id = i.category_id
WHERE i.user_id = $id AND i.published = 1 AND i.prodano != 1 AND i.kolvo != 0  AND i.archive != 1
GROUP BY i.category_id
";															
$result_cat = $inDB->query($sq_cat);
if ($inDB->num_rows($result_cat)>0){
$itemcats = array();
while($item_cats = $inDB->fetch_assoc($result_cat)){
$itemcats[] = $item_cats;
}
}
}

if ($pagecfg['modsdelki']) {
// Сделки    
$sql_zakazi = "SELECT from_id, from_nickname, from_login, opla4en_date, message
FROM cms_user_zakazi WHERE to_id={$id} AND opla4en = 1 AND podtverjden=1 ORDER BY opla4en_date DESC LIMIT 6";
$result_zakazi = $inDB->query($sql_zakazi);
if ($inDB->num_rows($result_zakazi)>0){
$zakazi = array();
while($sdelki = $inDB->fetch_assoc($result_zakazi)){		
$sdelki['opla4en_date']  = cmsCore::dateformat($sdelki['opla4en_date']);
$zakazi[] = $sdelki;
}
}
           
}

if ($pagecfg['modclub']) {
    // Клуб    
	$usr_club=$inDB->get_fields('cms_clubs',  "admin_id='{$id}' AND published=1", 'title,description');
}
	



// InstantMaps: Объекты > Адресаты объекта

if ($inCore->isComponentInstalled('maps') and $cfg['mapsinfo'] and $pagecfg['show_com'] and $usr['obj_id']) {
        //Подключаем CSS к странице
    $inPage->addHeadCSS('templates/'.$_CFG['template'].'/css/inmaps.css');
        require_once PATH.'/languages/ru/components/maps.php';
 
 //загружаем модель
    $inCore->loadModel('maps');
    $map_model = new cms_model_maps();

    //загрузим конфиг компонента
    $map_cfg = $map_model->getConfig();
   //получаем объект по ссылке
        $map_item = $map_model->getItemBySeolink($usr['obj_link']);

        if ($map_item['images']){
            $inPage->addHeadJS('includes/jquery/lightbox/js/jquery.lightbox.js');
            $inPage->addHeadCSS('includes/jquery/lightbox/css/jquery.lightbox.css');
        }
 // ------- готовим карту -----------------

        if (in_array($map_cfg['maps_engine'], array('yandex', 'narod', 'custom'))){
            $key = $map_cfg['yandex_key'];
        } else {
            $key = $map_cfg[$map_cfg['maps_engine'].'_key'];
        }

        $inCore->includeFile('components/maps/systems/'.$map_cfg['maps_engine'].'/info.php');
        $inPage->addHeadJS('components/maps/systems/'.$map_cfg['maps_engine'].'/geo.js');
        $inPage->addHeadJS('components/maps/js/map.js');
        $api_key = str_replace('#key#', $key, $GLOBALS['MAP_API_URL']);
        $inPage->page_head[] = $api_key;

        if ($cfg['desc_filters']){
            $filters = $inCore->getFilters();
            if ($filters){
                foreach($filters as $id=>$_data){
                    require_once PATH.'/filters/'.$_data['link'].'/filter.php';
                    $_data['link']($item['description']);
                }
            }
        }



}




	
$homepage = ($_SERVER['REQUEST_URI']=='/u'.$id ? true:false);

if ($usr['adress8'] and $homepage) {
  ?>
  <script src="http://api-maps.yandex.ru/1.1/index.xml?key=<?=$yakey?>" type="text/javascript"></script>
	<script type="text/javascript">

	var map, geoResult;
		window.onload = function init () {
		map = new YMaps.Map(document.getElementById("YMapsID"));
		map.addControl(new YMaps.TypeControl());
		map.addControl(new YMaps.ToolBar());
		map.addControl(new YMaps.Zoom());
		map.addControl(new YMaps.MiniMap());
		map.addControl(new YMaps.ScaleLine());
		map.removeOverlay(geoResult);
		map.enableScrollZoom();
		var geocoder = new YMaps.Geocoder('<?=@$usr['adress'] ?>',
{results: 1, boundedBy: map.getBounds()});
			YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
			if (this.length()) {
				geoResult = this.get(0);
				map.addOverlay(geoResult);
				geoResult.setIconContent('<?=@$usr['company'] ?>');
				geoResult.setBalloonContent('<?=@$usr['adress'] ?>');
				map.setBounds(geoResult.getBounds());
			}else {
			}
		});
	}
</script>
  <?
}
      
	
	$smarty = $inCore->initSmarty('components', 'com_torg_user_shop.tpl');
	$smarty->assign('cfg', $cfg);
	$smarty->assign('pagecfg', $pagecfg);
	$smarty->assign('id', $id);
	$smarty->assign('usr', $usr);
	$smarty->assign('ups', $ups);
	$smarty->assign('page_url', $url);
	$smarty->assign('items', $items);
	$smarty->assign('cat_title', $cat_title);
	$smarty->assign('au_ppsdate', $au_ppsdate);

        $smarty->assign('vsego_sdelok', $inDB->rows_count('cms_user_zakazi', "to_id={$id} AND opla4en = 1 AND podtverjden=1"));
        $smarty->assign('vsego_zakazov_users', $inDB->rows_count('cms_user_zakazi', "from_id={$inUser->id} AND opla4en = 1 AND otziv=0"));
	
	$smarty->assign('mod_sdelki', $zakazi);
	$smarty->assign('mod_club', $usr_club);
	$smarty->assign('mod_cats', $itemcats);



	$smarty->assign('vid_cat', $vid_cat);
	$smarty->assign('catid', $catid);
	$smarty->assign('nupage', $nupage);
	$smarty->assign('objnews', $objnews);
	$smarty->assign('usr_wall_html', $usr_wall_html);
        $smarty->assign('usr_addwall_html', $usr_addwall_html);		      
	$smarty->assign('wall_points', $model->getTorgWallPoints($usr['id'], false));
    
    
        $smarty->assign('homepage', $homepage);
	
	if ($pagecfg['page_banner']) {
	$banner = $inDB->get_field('cms_torg_banners', "user_id = '{$usr['id']}'", 'id');
	$smarty->assign('user_banner', $inCore->getTorgBannerById($banner['id']));
	}
	
		$smarty->assign('news', $news);
	
	
		
        //Объект с компонента InstantMaps
	$smarty->assign('map_cfg', $map_cfg);
	$smarty->assign('map_item', $map_item);
	

	
		$smarty->assign('is_admin', $inUser->is_admin);
		$smarty->assign('is_user', $inUser->id);
	$smarty->assign('moderator', $moderator);
	$smarty->assign('page_content', $page_content);
	$smarty->assign('view_page', $view_page);
	$smarty->assign('nupage', $nupage);
	$smarty->assign('pageBar', pageBartorg($id, $page, $perpage));
	$smarty->assign('mapsInstalled', $inCore->isComponentInstalled('maps'));
	$smarty->assign('user_in', $inUser->id);
	$smarty->display('com_torg_user_shop.tpl');
      return true;
	
	?>