<?php

if(!defined('VALID_CMS')) { die('ACCESS DENIED'); }


	
//Массовое Редактирование товаров
		
		function cpPriceInput($itemid){
       $inCore = cmsCore::getInstance();
       $inDB = cmsDatabase::getInstance();


		   $price = $inDB->get_field('cms_torg_items', 'id='.$itemid, 'price');
		   $price = number_format($price, 2, '.', '');
		   $html = '<input type="text" name="price['.$itemid.']" value="'.$price.'" style="width:70px;background:transparent;border:1px solid #eee;"/>';
	

	     return $html;
    }
    function cpPrice2Input($itemid){
       $inCore = cmsCore::getInstance();
       $inDB = cmsDatabase::getInstance();

       $price2 = $inDB->get_field('cms_torg_items', 'id='.$itemid, 'price2');
		   $price2 = number_format($price2, 2, '.', '');
		   $html = '<input type="text" name="price2['.$itemid.']" value="'.$price2.'" style="width:70px;background:transparent;border:1px solid #eee;"/>';
	

	     return $html;
     }
    function cpKolvoInput($itemid){
      $inCore = cmsCore::getInstance();
      $inDB = cmsDatabase::getInstance();
		  $kolvo = $inDB->get_field('cms_torg_items', 'id='.$itemid, 'kolvo');
		  $html = '<input type="text" name="kolvo['.$itemid.']" value="'.$kolvo.'" style="width:30px;background:transparent;border:1px solid #eee;"/>';
	

	    return $html;
    }
    function cpTitleInput($itemid){
        $inCore = cmsCore::getInstance();
        $inDB = cmsDatabase::getInstance();
        
        $title = $inDB->get_field('cms_torg_items', 'id='.$itemid, 'title');

        $html = '<input type="text" name="title['.$itemid.']" value="'.$title.'" style="width:100%;background:transparent;border:1px solid #eee;padding:2px;"/>';
	

	      return $html;
    }

//


//Пагинация в списке товаров в личном разделе

function pageBartorg($user_id, $current, $perpage){
    $inDB   = cmsDatabase::getInstance();
	$html = '';
	global $_LANG;
	 if ($_REQUEST['cat_id']) $catsql= "AND category_id='".$_REQUEST['cat_id']."'"; else $catsql="";
	$result = $inDB->query("SELECT id FROM cms_torg_items WHERE user_id = '{$user_id}'  $catsql AND published=1 AND kolvo !=0 AND prodano!=1 AND archive=0");
	$records = $inDB->num_rows($result);
	
	if ($records){
		$pages = ceil($records / $perpage);
		
		 if ($_REQUEST['vid']=='list') $vid='list/'; 
 else  if ($_REQUEST['vid']=='price') $vid='price/'; 
 else $vid=""; 
 if ($_REQUEST['cat_id']) $catid='c'.$_REQUEST['cat_id']; else $catid="";		



	
		if($pages>1){
			$html .= '<div class="pagebar"><br/>';
			$html .= '<span class="pagebar_title"><strong style="color:#000">'.$_LANG['PAGES'].': </strong></span>';
			for ($p=1; $p<=$pages; $p++){
				if ($p != $current) {
					if ($p==1) { $pnum = 'p1.html'; } else { $pnum = 'p'.$p.'.html'; }
					$link = '/u'.$user_id.'/tovari/'.@$vid.''.@$catid.''.$pnum.'';					
					$html .= ' <a href="'.$link.'" class="pagebar_page">'.$p.'</a> ';		
				} else {
					$html .= '<span class="pagebar_current">'.$p.'</span>';
				}
			}
			$html .= '</div>';
		}
	}
	return $html;
}

//

function isNew($item_id, $shownew, $newint){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    if ($shownew){
        $sql = "SELECT id FROM cms_torg_items WHERE id = '{$item_id}' AND pubdate >= DATE_SUB(NOW(), INTERVAL {$newint})";
        $result = $inDB->query($sql) ;
        return $inDB->num_rows($result);
    } else { return 0; }
}

function getAlphaList($cat_id){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    $html = '';
    $sql = "SELECT UPPER(SUBSTRING(LTRIM( title ) , 1, 1)) AS first_letter, COUNT( id ) AS num
            FROM cms_torg_items
            WHERE category_id = '{$cat_id}' AND published = 1
            GROUP BY first_letter";
    $result = $inDB->query($sql) ;
    if ($inDB->num_rows($result)){
        $html .= '<div class="torg_alpha_list">';
        while($a = $inDB->fetch_assoc($result)){
            $html .= '<a class="torg_alpha_link" href="/torg/'.$cat_id.'/find-first/'.urlencode($a['first_letter']).'" title="'.$_LANG['ARTICLES'].': '.$a['num'].'">'.$a['first_letter'].'</a>';
        }
        $html .= '</div>';
    }
    return $html;
}







function orderForm($orderby, $orderto, $shop=false){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    $html = '';
    $html .= '<form action="'.$_SERVER['REQUEST_URI'].'" method="POST"><div class="torg_sortform"><table cellspacing="2" cellpadding="2" >' ."\n";
    $html .= '<tr>' ."\n";
  //  $html .= '<td width="87px"><b>Соритровка:</b></td>' ."\n";
    $html .= '<td valign="top"><select style="width:110px" name="orderby" id="orderby">' ."\n";
	
$html .= '<option value="up" '; if($orderby=='up') { $html .= 'selected'; } $html .= '>'.$_LANG['ORDERBY_DATE'].'</option>' ."\n";
$html .= '<option value="title" '; if($orderby=='title') { $html .= 'selected'; } $html .= '>'.$_LANG['ORDERBY_TITLE'].'</option>' ."\n";
$html .= '<option value="price" '; if($orderby=='price') { $html .= 'selected'; } $html .= '>'.$_LANG['ORDERBY_PRICE'].'</option>' ."\n";
    $html .= '<option value="rating" '; if($orderby=='rating') { $html .= 'selected'; } $html .= '>'.$_LANG['ORDERBY_RATING'].'</option>' ."\n";
    $html .= '<option value="hits" '; if($orderby=='hits') { $html .= 'selected'; } $html .= '>'.$_LANG['ORDERBY_HITS'].'</option>' ."\n";
    $html .= '</select> <select name="orderto" id="orderto"  style="width:115px">';
    $html .= '<option value="desc" '; if($orderto=='desc') { $html .= 'selected'; } $html .= '>'.$_LANG['ORDERBY_DESC'].'</option>' ."\n";
    $html .= '<option value="asc" '; if($orderto=='asc') { $html .= 'selected'; } $html .= '>'.$_LANG['ORDERBY_ASC'].'</option>' ."\n";
    $html .= '</select>';
    $html .= ' <input type="submit" style="width:97px" value="Сортировать" />' ."\n";
    $html .= '</td>' ."\n";
    $html .= '</tr>' ."\n";
    $html .= '</table></div></form>' ."\n";
    return $html;
}




function filtrForm($orderby, $orderto, $shop=false){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    $html = '';
    return $html;
}




function tagsList($cat_id){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $html = '';
    $sql = "SELECT t.*, COUNT(t.tag) as num, c.id as cat_id
                FROM cms_tags t, cms_torg_items i, cms_torg_cats c
                WHERE t.target='torg' AND t.item_id = i.id AND i.category_id = c.id AND c.id = $cat_id
                GROUP BY t.tag
                ORDER BY t.tag";
    $result = $inDB->query($sql) ;
    if ($inDB->num_rows($result)>0){
        while($tag = $inDB->fetch_assoc($result)){
            $html .= '<a href="#" onclick="addTag(\''.strtolower($tag['tag']).'\')">'.strtolower($tag['tag']).'</a> ('.$tag['num'].') ';
        }
    }
    return $html;
}

function tagLine($tagstr, $cat_id){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $html = '';
    if (!$tagstr) { return ''; }
    $tagstr = str_replace(', ', ',', $tagstr);
    $tagstr = str_replace(' ,', ',', $tagstr);
    $tags = explode(',', $tagstr);
    $num = 0;
    foreach($tags as $key=>$value){
        $value = strtolower($value);
        $html .= '<a href="/torg/'.$cat_id.'/tag/'.urlencode($value).'">'.$value.'</a>';
        if ($num < sizeof($tags)-1) { $html .= ', '; $num++; }
    }
    return $html;
}

function getContentCount($cat_id, &$total, $inDB){

    $sql = "SELECT c.*, IFNULL(COUNT(i.id), 0) as content_count
            FROM cms_torg_cats c
            LEFT JOIN cms_torg_items i ON i.category_id = c.id AND i.published = 1
            WHERE (c.parent_id = {$cat_id}) AND c.published = 1
            GROUP BY i.category_id
            ORDER BY c.title";

    $result = $inDB->query($sql);

    if ( !$inDB->num_rows($result)>0 ){ return ''; }

    $cats = array();

    while($cat = $inDB->fetch_assoc($result)){
        $total   += $cat['content_count'];
        getContentCount($cat['id'], $total, $inDB);
    }

    return ;
    
}

function subCatsList($parent_id, $left_key, $right_key){

    $inCore = cmsCore::getInstance();
    $inDB   = cmsDatabase::getInstance();

	
	   $html   = '';
    $model  = new cms_model_torg();

    if (!$parent_id) { $parent_id = $inDB->get_field('cms_torg_cats', 'parent_id=0', 'id'); }
	
    $cats = $model->getSubCats($parent_id, $left_key, $right_key);
	


    if ($cats){
	      $this_cat= $inCore->request('cat_id', 'int', 0);

        $smarty = $inCore->initSmarty('components', 'com_torg_cats.tpl');
        $smarty->assign('cfg', $inCore->loadComponentConfig('torg'));
        $smarty->assign('cats', $cats);
        $smarty->assign('this_cat', $this_cat);
        ob_start();

        $smarty->display('com_torg_cats.tpl');

        $html = ob_get_clean();
    }

    return $html;
    
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function torg(){

    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB   = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();

	    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) { $inCore->loadClass('billing'); }

	
    global $_LANG;
    global $_CFG;
 
    $inCore->loadModel('torg');
    $model = new cms_model_torg();

    $menutitle  = $inCore->menuTitle();
    if (!$menutitle) { $menutitle = $_LANG['torg']; }
    $cfg        = $inCore->loadComponentConfig('torg');
	
	// Проверяем включени ли компонент
	if(!$cfg['component_enabled']) { cmsCore::error404(); }

    if (!isset($cfg['email'])) { $cfg['email'] = 'shop@site.ru'; }
    if (!isset($cfg['delivery'])) { $cfg['delivery'] = 'Сведения о доставке'; }
    if (!isset($cfg['notice'])) { $cfg['notice'] = 0; }
    if (!isset($cfg['premod'])) { $cfg['premod'] = 1; }
    if (!isset($cfg['premod_msg'])) { $cfg['premod_msg'] = 1; }
    if (!isset($cfg['is_comments'])) { $cfg['is_comments'] = 1; }

    if ($inCore->inRequest('cat_id')){
        $id = $inCore->request('cat_id', 'int', 0);
    } else {
        $id = $inCore->request('id', 'int', 0);
    }

    $do = $inCore->request('do', 'str', 'view');

    $inCore->includeFile('components/torg/includes/shopcore.php');


	  //Подключаем CSS к странице
	//$inPage->addHeadCSS('templates/'.$_CFG['template'].'/css/torg.css');

    //////////////////////////// RATING SUBMISSION ///////////////////////////////////////////////////////////////////
    if ($inCore->inRequest('rating')){
   
	    $inUser = cmsUser::getInstance();
				$user_id = $inUser->id;
        $points     = $inCore->request('points', 'int', 0);
        $item_id    = $inCore->request('item_id', 'int', 0);
        $ip         = $_SERVER['REMOTE_ADDR'];
        if (!$model->alreadyVoted($item_id)){
            $inDB->query("INSERT INTO cms_torg_ratings (item_id, points, ip, user_id) VALUES ($item_id, $points, '$ip', '$user_id')") ;
            $inDB->query("DELETE FROM cms_torg_ratings WHERE item_id = $item_id AND ip = '0.0.0.0'") ;
			$url = $_SERVER['REQUEST_URI'];
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();
        }
    }
    //////////////////////////// Ibuy SUBMISSION ///////////////////////////////////////////////////////////////////
    if ($inCore->inRequest('bayed')){
	    $inUser = cmsUser::getInstance();
        $item_id    = $inCore->request('item_id', 'int', 0);
				$user_id = $inUser->id;
$login = $inUser->login;
$nickname = $inUser->nickname;
		        $ip         = $_SERVER['REMOTE_ADDR'];

		
       if (!alreadyIbuy($item_id)){		
	
$inDB->query("INSERT INTO cms_torg_ibuy (item_id, user_id, login, nickname, ip) VALUES ($item_id, '$user_id' , '$login' , '$nickname', '$ip')") ;
 $inDB->query("DELETE FROM cms_torg_ibuy WHERE item_id = '{$item_id}' AND ip = '0.0.0.0'") ;
$url = $_SERVER['REQUEST_URI'];
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

        }
    }	

	   //////////////////////////// stavka SUBMISSION ///////////////////////////////////////////////////////////////////
    if ($inCore->inRequest('stavka')){
        $points     = $inCore->request('points', 'int', 0);
        $item_id    = $inCore->request('item_id', 'int', 0);
		
		     $nickname     = $inCore->request('nickname', 'str', 0);
        $login    = $inCore->request('login', 'str', 0);
		
		$inUser = cmsUser::getInstance();
		$user_id = $inUser->id;
		
		
	
$inDB->query("INSERT INTO cms_torg_stavka (item_id, points, user_id, login, nickname, pubdate) VALUES ($item_id, $points, '$user_id' , '$login' , '$nickname', NOW())") ;
$maxstavka=$inCore->request('maxstavka', 'int', 0);	
$inDB->query("DELETE FROM cms_torg_stavka WHERE points = $maxstavka AND user_id = $user_id LIMIT 1") ;
$url = $_SERVER['REQUEST_URI'];
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();


    }
		   //////////////////////////// prodano SUBMISSION ///////////////////////////////////////////////////////////////////
    if ($inCore->inRequest('prodano')){
	
        $prodano     = $inCore->request('prodano', 'int', 0);
       	$inUser = cmsUser::getInstance();
		  $item_id    = $inCore->request('item_id', 'int', 0);
		$user_id = $inUser->id;

            $inDB->query("UPDATE cms_torg_items SET prodano=$prodano WHERE id = $item_id") ;             
$url = $_SERVER['REQUEST_URI'];
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();
		
    }
	

if ($do=='oplata' || $do=='ibuy'){


     $inCore->loadModel('users');
    $model_users = new cms_model_users();
$fastbuy=$inCore->request('fastbuy', 'int');
$eltovar=$inCore->request('eltovar', 'int');
$prodavec_id=$inCore->request('prodavec_id', 'int');
$prodavec=$inCore->request('prodavec', 'str');
$item_title=$inCore->request('item_title', 'str');
$item_id=$inCore->request('item_id', 'int');
$id=$inCore->request('id', 'int');
$item_price=$inCore->request('item_price', 'int');
$price_val=$cfg['price_val'];
$user_id = $inUser->id;
$user_nickname = $inUser->nickname;
$user_login = $inUser->login;
$model->oplata($item_id, $item_price, $prodavec_id);

if ($do=='ibuy'){
//отправляем сообщение
$message = '<b>Уведомляю Вас об оплате - '.$item_price.' '.$price_val.' за <a href="/torg/item'.$item_id.'.html">'.$item_title.'</a></b>';
$msg_id = cmsUser::sendMessage($user_id, $prodavec_id, $message);
// отправляем уведомление на email
$model_users->sendNotificationByEmail($user_id, $prodavec_id, $msg_id);
if ($eltovar) {$text='<div style="color:red">Ссылку на товар Вы получите на почту и в ЛС, сразу после того как продавец подтвердит оплату.</div>';}
$inCore->addSessionMessage('<b>Продавец уведомлен об оплате за товар, личным сообщением и на e-mail.</b>'.$text.'', 'info');
	    
} elseif ($do=='oplata'){
$summ = $item_price;
if (IS_BILLING) { cmsBilling::checkBalance('torg', 'buy_torg_item'); }
        if (IS_BILLING) {

            cmsBilling::process('torg', 'buy_torg_item');
	
                if ($inUser->balance >= $summ){
                    cmsBilling::pay($user_id, $summ, 'Оплата для <a href="/torg/u'.$prodavec_id.'">'.$prodavec.'</a> за товар: <a href="/torg/item'.$item_id.'.html">#'.$item_id.'</a>');
		    $inDB->query("UPDATE cms_user_zakazi SET opla4en=1, opla4en_date=NOW() WHERE id = {$id} AND from_id = {$user_id} LIMIT 1");     
 //отправляем сообщение
$message = '<b>Уведомляю Вас об оплате - '.$item_price.' баллов за <a href="/torg/item'.$item_id.'.html">'.$item_title.'</a></b>';
$msg_id = cmsUser::sendMessage($user_id, $prodavec_id, $message);
// отправляем уведомление на email
$model_users->sendNotificationByEmail($user_id, $prodavec_id, $msg_id);
if ($eltovar and !$fastbuy) {$fastbuy='<div style="color:red">Ссылку на товар Вы получите на почту и в ЛС, сразу после того как продавец подтвердит оплату.</div>';}
else if ($eltovar and !$fastbuy) {$fastbuy='<div style="color:red">Ссылка на товар была отправленна Вам на почту и в ЛС.</div>';}
 $inCore->addSessionMessage('<b>Оплата произведена успешно! Продавец уведомлен личным сообщением и на e-mail.</b> '.$fastbuy.'', 'info');
 	 if ($eltovar and $fastbuy) {    
	//отправляем ссылку на цифровой товар
	$inCore->includeFile('components/torg/model_eltovar.php');
	$model_eltovar = new cms_model_torg_eltovar();
        $model_eltovar->sendDigitalLinks($id);
	 }
                }  else {
		  $inCore->addSessionMessage('<b>Оплата не произведена! Не достаточно средств на Вашем балансе.</b> <a href="/billing">Пополните баланс >></a>', 'info');}               
            }

}
  
  
$inCore->redirectBack();


}



    //////////////////////////// SEARCH BY TAG ///////////////////////////////////////////////////////////////////////
    if ($do == 'tag') {

        $tag = $inCore->request('tag', 'str');
        $sql = "SELECT tag FROM cms_tags WHERE tag = '$tag' AND target='torg' LIMIT 1";
        $result = $inDB->query($sql) ;
        if ($inDB->num_rows($result)==1){
            $item = $inDB->fetch_assoc($result);
            $query = $item['tag'];
            $findsql = "SELECT *
                        FROM cms_torg_items
                        WHERE category_id = $id AND published = 1 AND tags LIKE '%$query%'";
            $do = 'cat';
        } else { echo $_LANG['NO_MATCHING_FOUND']; }

    }
    //////////////////////////// ADVANCED SEARCH ////////////////////////////////////////////////////////////////////
    if ($do == 'search') {

        //Perform search
        if (isset($_POST['gosearch'])){
            $fdata = $_POST['fdata'];
            $title = $inCore->request('title', 'str');
			

            $query = '';
            $fstr = 'a:%:{';

            if (is_array($fdata)){
                foreach($fdata as $key=>$value) {
                    $value = str_replace("'", '?', $value);
                    $value = str_replace("{", '?', $value);
                    $value = str_replace("}", '?', $value);
                    $value = str_replace(":", '?', $value);
                    $fstr .= 'i:'.$key.';s:%:"%'.trim($value).'%";';
                    $query .= $value;
                }

                $fstr .= '}';
                if ($query=='') { unset($query); }
				$query = $inCore->strClear($query);
                $findsql = "SELECT i.* , IFNULL(AVG(r.points),0) AS rating
                            FROM cms_torg_items i
                            LEFT JOIN cms_torg_ratings r ON r.item_id = i.id
                            WHERE i.published = 1  AND i.category_id = '$id' AND i.fieldsdata LIKE '%{$query}%' AND i.title LIKE '%$title%'";

                if ($_POST['tags'] != '') {
                    $findsql .= " AND (";
                    $tags = explode(' ', $inCore->request('tags', 'str'));
                    $t = 1;
                    foreach($tags as $key=>$value){
                        $findsql .= "(i.tags LIKE '%".$value."%')";
                        if ($t<sizeof($tags)) { $findsql .= " AND "; } else { $findsql .= ")"; }
                        $t++;
                    }
                }
                $findsql .=	"GROUP BY i.id";
                $advsearch = 1;
            }
            $do = 'cat';
        } else {
            //show search form
            $sql = "SELECT * FROM cms_torg_cats WHERE id = '{$id}'";
            $result = $inDB->query($sql) ;

            if ($inDB->num_rows($result)==1){
                $cat = $inDB->fetch_assoc($result);
                $fstruct = unserialize($cat['fieldsstruct']);

                //heading
                $inPage->addPathway($cat['title'], '/torg/'.$cat['id']);
                $inPage->addPathway($_LANG['SEARCH'], '/torg/'.$cat['id'].'/search.html');
                $inPage->setTitle($_LANG['SEARCH_IN_CAT'] . ' - ' . $menutitle);

                $inPage->addHeadJS('components/torg/js/search.js');

                $fstruct_ready = array();
                foreach($fstruct as $key=>$value) {
                    if (strstr($value, '/~h~/')) { $ftype = 'html'; $value=str_replace('/~h~/', '', $value); }
                    elseif (strstr($value, '/~l~/')) { $ftype = 'link'; $value=str_replace('/~l~/', '', $value); } else { $ftype='text'; }
                    if (strstr($value, '/~m~/')) {
                        $value = str_replace('/~m~/', '', $value);
                    }
                    $fstruct_ready[$key] = $value;
                }

                $inPage->backButton(false);

                //searchform
                $smarty = $inCore->initSmarty('components', 'com_torg_search.tpl');
                $smarty->assign('id', $id);
                $smarty->assign('cat', $cat);
                $smarty->assign('fstruct', $fstruct_ready);
                $smarty->display('com_torg_search.tpl');

            } else { cmsCore::error404(); }
        }//search form

    }

    //////////////////////////// SEARCH BY FIRST LETTER OF TITLE ///////////////////////////////////////////////////////
    if ($do == 'findfirst') {

        $id = $inCore->request('cat_id', 'int');

        $query = urldecode($inCore->request('text', 'str'));
        $query = str_replace("'", '?', $query);
        $query = str_replace("{", '?', $query);
        $query = str_replace("}", '?', $query);
        $query = str_replace(":", '?', $query);

        $findsql = "SELECT i.* , IFNULL(AVG( r.points ),0) AS rating
                    FROM cms_torg_items i
                    LEFT JOIN cms_torg_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = '{$id}' AND UPPER(LTRIM(i.title)) LIKE UPPER('$query%')
                    GROUP BY i.id";

        $do = 'cat';
        $advsearch = 0;

        $pagemode = 'findfirst';

    }

    //////////////////////////// SEARCH BY FIELD ////////////////////////////////////////////////////////////////////
    if ($do == 'find') {
        $id = $inCore->request('cat_id', 'int');

        $query = urldecode($inCore->request('text', 'str'));
        $query = str_replace("'", '?', $query);
        $query = str_replace("{", '?', $query);
        $query = str_replace("}", '?', $query);
        $query = str_replace(":", '?', $query);

        $findsql = "SELECT i.* , IFNULL(AVG(r.points),0) AS rating
                    FROM cms_torg_items i
                    LEFT JOIN cms_torg_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = $id AND i.fieldsdata LIKE '%$query%'
                    GROUP BY i.id";

        $do = 'cat';
        $advsearch = 0;

        $pagemode = 'find';
    }

	







	
if ($do == 'add_cat_item'){
$inCore = cmsCore::getInstance();
$inUser = cmsUser::getInstance();
if ($inUser->id){
$sql = "SELECT * FROM cms_torg_cats WHERE parent_id>0 AND NSLevel=1";
$result = $inDB->query($sql);

$inPage->addPathway($item['title'], '/torg/item'.$item['id'].'.html');
$inPage->setTitle("Добавление товара");

echo '<div class="moduletitle">Добавление товаров</div><div class="modulebody"><h6 style="font-size:13px">Выберите рубрику</h6><br/>';	

function listcat3($id,$sub){
$categories = mysql_query("SELECT id,title FROM cms_torg_cats WHERE parent_id='$id' AND published = 1"); 
while($category = mysql_fetch_assoc($categories)){      
$name_cat = $category['title'];
$count_ads = mysql_result(mysql_query("SELECT COUNT(id) FROM cms_torg_items WHERE category_id='".$category['id']."' AND published=1 AND kolvo != 0 AND prodano != 1 AND archive != 1 AND published = 1".$GLOBALS['subQuery']), 0);
if($sub=="2") $subclass="class=\"subclass\"";else $subclass="";
				
				
echo "<div class=\"torg_cat_item\"><a href='/torg/".$category['id']."/add.html' ".$subclass.">".$name_cat." <sup>(".@$count_ads.")</sup></a></div>";
			
if($category['NSLevel']>1){listcat3($category['id'],$sub+1);}
				
        }
}
$categories = mysql_query("SELECT icon,id,title FROM cms_torg_cats WHERE NSLevel =1 AND published = 1"); 
$num_rows = @mysql_num_rows($categories);

 
while($category = @mysql_fetch_assoc($categories)){

$subcats_count=$inDB->rows_count('cms_torg_cats', "parent_id={$category['id']} AND published=1");
$name_cat = $category['title'];
if (!$category['icon'])	{$category['icon']="folder_grey.png";} else {$category['icon']=$category['icon'];}	
echo "<div id=\"index_cats\" style='background:#fafafa url(/upload/torg/cat_icons/".$category['icon'].") left 5px no-repeat'>";
if ($subcats_count) {
echo "<a href=\"#\"  onclick=\"toggle(document.getElementById('cat".$category['id']."'));return false;\">".$name_cat." <sup>+".$subcats_count."</sup></a>";
} else {
 echo "<a href=\"/torg/".$category['id']."\" ".@$corrent_pcat.">".$name_cat."</a>";			 
}
echo "<div id=\"cat".$category['id']."\" style=\"padding-bottom:3px; padding-top:3px;display:none\">";
listcat3($category['id'],1);
echo "</div></div>";
       
     
}

echo "<div class='clear'></div></div>";	


} else 		{ $inCore->redirect('/login'); }

		
	 }
	 
		
		
    //////////////////////////// LIST OF CATEGORIES ////////////////////////////////////////////////////////////////////
    if ($do == 'view'){ //List of all categories
    $inUser = cmsUser::getInstance();
echo '<div class="moduletitle">Рубрикатор товаров</div><div class="modulebody"><br/>';	

function listcat3($id,$sub){
$categories = mysql_query("SELECT id,title FROM cms_torg_cats WHERE parent_id='$id' AND published = 1"); 
while($category = mysql_fetch_assoc($categories)){      
$name_cat = $category['title'];
$count_ads = mysql_result(mysql_query("SELECT COUNT(id) FROM cms_torg_items WHERE category_id='".$category['id']."' AND published=1 AND kolvo != 0 AND prodano != 1 AND archive != 1 AND published = 1".$GLOBALS['subQuery']), 0);
if($sub=="2") $subclass="class=\"subclass\"";else $subclass="";
				
				
echo "<div class=\"torg_cat_item\"><a href=\"/torg/".$category['id']."\" ".$subclass.">".$name_cat." <sup>(".@$count_ads.")</sup></a></div>";
			
if($category['NSLevel']>1){listcat3($category['id'],$sub+1);}
				
        }
}
$categories = mysql_query("SELECT icon,id,title FROM cms_torg_cats WHERE NSLevel =1 AND published = 1"); 
$num_rows = @mysql_num_rows($categories);

 
while($category = @mysql_fetch_assoc($categories)){

$subcats_count=$inDB->rows_count('cms_torg_cats', "parent_id={$category['id']} AND published=1");
$name_cat = $category['title'];
if (!$category['icon'])	{$category['icon']="folder_grey.png";} else {$category['icon']=$category['icon'];}	
echo "<div id=\"index_cats\" style='background:url(/upload/torg/cat_icons/".$category['icon'].") left 5px no-repeat'>";
if ($subcats_count) {
echo "<a href=\"#\"  onclick=\"toggle(document.getElementById('cat".$category['id']."'));return false;\">".$name_cat." <sup>+".$subcats_count."</sup></a>";
} else {
 echo "<a href=\"/torg/".$category['id']."\" ".@$corrent_pcat.">".$name_cat."</a>";			 
}
echo "<div id=\"cat".$category['id']."\" style=\"padding-bottom:3px; padding-top:3px;display:none\">";
listcat3($category['id'],1);
echo "</div></div>";
       
     
}
echo "<div class='clear'></div>";
 if ($inUser->id){
echo '<div class="cat_addbut"><a href="/torg/add.html"><img src="/templates/_default_/images/icons/add.png" align="absmiddle"> Добавить товар</a></div>';
}
echo "<div class='clear'></div></div>";	

				
	

    }
	
	
	

	
	
	
    //////////////////////////// VIEW CATEGORY ///////////////////////////////////////////////////////////////////////
    if ($do == 'cat'){
        //get category data
        $sql = "SELECT * FROM cms_torg_cats WHERE id = '{$id}'";
        $catres = $inDB->query($sql);

        $_SESSION['torg_last_url'] = $_SERVER['REQUEST_URI'];
        $inPage->addHeadJS('includes/jquery/lightbox/js/jquery.lightbox.js');
        $inPage->addHeadCSS('includes/jquery/lightbox/css/jquery.lightbox.css');



	function sCatsList($parent_id, $left_key, $right_key){

    $inCore = cmsCore::getInstance();
    $inDB   = cmsDatabase::getInstance();

    $html   = '';
    $model  = new cms_model_torg();

    if (!$parent_id) { $parent_id = $inDB->get_field('cms_torg_cats', 'parent_id=0', 'id'); }
	
    $cats = $model->getSubCats($parent_id, $left_key, $right_key);
	

    if ($cats){
        $smarty = $inCore->initSmarty('components', 'com_torg_cats.tpl');
        $smarty->assign('cfg', $inCore->loadComponentConfig('torg'));
        $smarty->assign('cats', $cats);

        ob_start();

        $smarty->display('com_torg_cats.tpl');

        $html = ob_get_clean();
    }

    return $html;
    
}
	



        if ($inDB->num_rows($catres)>0){
            
            $cat        = $inDB->fetch_assoc($catres);
            //$fstruct    = unserialize($cat['fieldsstruct']);

            //heading
            //PATHWAY ENTRY
            $left_key   = $cat['NSLeft'];
            $right_key  = $cat['NSRight'];

            $path_list  = $model->getCategoryPath($left_key, $right_key);

            if ($path_list){
                foreach($path_list as $pcat){
                   $inPage->addPathway($pcat['title'], '/torg/'.$pcat['id']);
               }
            }
           
            $inPage->addPathway($cat['title'], '/torg/'.$cat['id']);
            $inPage->setTitle($cat['title'] . ' - ' . $menutitle);

            //subcategories
      $subcats = subCatsList($cat['id'], $cat['NSLeft'], $cat['NSRight']);
	  
	  
	  
$pcats = sCatsList($parent_cat['id'], $cat['NSLeft'], $cat['NSRight']);





$sub = subCatsList($cat['parent_id'], $cat['NSLeft'], $cat['NSRight']);



if ($_REQUEST['op']=="au") $sqau="AND au=1"; else $sqau="";
if ($_REQUEST['op']=="instant") $sqinstant="AND instant=1";	else $sqinstant="";
if ($_REQUEST['op']=="sale") $sqsale="AND sale=1";	else $sqsale="";
if ($_REQUEST['op']=="torg") $sqtorg="AND torg=1";	else $sqtorg="";
if ($_REQUEST['op']=="obmen") $sqobmen="AND obmen=1";	else $sqobmen="";
if ($_REQUEST['op']=="free") $sqfree="AND free=1";	else $sqfree="";

            //alphabetic list
            if ($cat['showabc']){ $alphabet = getAlphaList($cat['id']);	} else { $alphabet = ''; }

            //Tool links
            $shopcartlink = $model->shopCartLink();

            //get items SQL
            if (!isset($findsql)){
                $sql = "SELECT
		i.*,
		IFNULL(AVG( r.points ), 0) AS rating, i.price as price, u.nickname, u.login
                        FROM cms_torg_items i 
                        LEFT JOIN cms_torg_ratings r ON r.item_id = i.id
                        LEFT JOIN cms_users u ON u.id = i.user_id
                        WHERE i.published = 1 AND i.category_id = '{$id}'
			$sqau $sqinstant $sqsale $sqtorg $sqobmen $sqfree AND i.kolvo != 0 AND i.prodano != 1 AND i.archive != 1
                        GROUP BY i.id";
		
				 
            } else {
                $sql = $findsql;
                if (!$advsearch){ $inPage->addPathway(ucfirst($query), $_SERVER['REQUEST_URI']); } else
                { $inPage->addPathway($_LANG['SEARCH_RESULT'], $_SERVER['REQUEST_URI']); }
            }

            //ordering
            if (isset($_POST['orderby'])) {
                $orderby = $inCore->request('orderby', 'str');
                $_SESSION['torg_orderby'] = $orderby;
            } elseif(isset($_SESSION['torg_orderby'])) {
                $orderby = $_SESSION['torg_orderby'];
            } else {
                $orderby = $cat['orderby'];
            }

            if (isset($_POST['orderto'])) {
                $orderto = $inCore->request('orderto', 'str');
                $_SESSION['torg_orderto'] = $orderto;
            } elseif(isset($_SESSION['torg_orderto'])) {
                $orderto = $_SESSION['torg_orderto'];
            } else {
                $orderto = $cat['orderto'];
            }

            $sql .=  " ORDER BY ".$orderby." ".$orderto;
            
            //get total items count
            $result = $inDB->query($sql);
            $itemscount = $inDB->num_rows($result);


			
			
		
		
		
			
			      
			
            //can user add items here?
$is_cat_access = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id);
$is_can_add = $is_cat_access || $inUser->is_admin;
			
		
if ($_REQUEST['action']=="list"){
$smarty = $inCore->initSmarty('components', 'com_torg_view_list.tpl');
} else {
$smarty = $inCore->initSmarty('components', 'com_torg_view.tpl');	
}
			
$smarty->assign('filter', $filter);
$smarty->assign('filter_str', $filter_str);
$smarty->assign('id', $id);
$smarty->assign('cat', $cat);
$smarty->assign('subcats', $subcats);
$smarty->assign('pcats', $pcats);
$smarty->assign('sub', $sub);
$smarty->assign('alphabet', $alphabet);
$smarty->assign('shopcartlink', $shopcartlink);
$smarty->assign('itemscount', $itemscount);
$smarty->assign('is_can_add', $is_can_add);
$smarty->assign('orderform', orderForm($orderby, $orderto, ($cat['view_type']=='shop')));
$smarty->assign('filtrform', filtrForm($orderby, $orderto, ($cat['view_type']=='shop')));


 
if ($itemscount>0){

//pagination
if (!@$advsearch) { $perpage = $cat['perpage']; } else { $perpage='10'; }
$page = $inCore->request('page', 'int', 1);

//request items using pagination
$sql .= " LIMIT ".(($page-1)*$perpage).", {$perpage}";
$result = $inDB->query($sql) ;

//search details, if needed
$search_details = '';
if (isset($findsql)){
if ($advsearch){
$search_details = '<div class="torg_queryform"><strong>'.$_LANG['SEARCH_RESULT'].' - </strong> '.$_LANG['FOUNDED'].': '.$itemscount.' | <a href="/torg/'.$cat['id'].'">'.$_LANG['CANCEL_SEARCH'].'</a></div>';
} else {
$search_details = '<div class="torg_queryform"><strong>'.$_LANG['SEARCH_BY_TAG'].'</strong> "'.ucfirst($query).'" ('.$_LANG['MATCHES'].': '.$itemscount.') <a href="/torg/'.$cat['id'].'">'.$_LANG['CANCEL_SEARCH'].'</a></div>';
}
}
$date=date('Y-m-d H:i:s');	
$items = array();
while($item = $inDB->fetch_assoc($result)){
  
//$item['comments_count']    = $inCore->getCommentsCount('torg', $item['id']);

$item['ratingdata'] = $model->ratingData($item['id']);
$item['ibuydata'] = $model->ibuyData($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['price'] = number_format(shopDiscountPrice($item['id'], $item['category_id'], $item['price']), 0, '.', ' ');
$item['price_old'] = number_format($item['price_old'], 0, '.', ' ');
$item['rating'] = $model->buildRating($item['ratingdata']['rating']);
//$item['is_new'] = isNew($item['id'], $cat['shownew'], $cat['newint']);
$item['rew_count']=$inDB->rows_count('cms_torg_rew', "target_id={$item['id']} AND published=1 AND parent_id=0");


                   

					 //товар в корзине?
            $item['is_in_cart'] = $model->isItemInCart($item['id']);

                    $items[] = $item;
                }



             
if (!$pagemode){
if ($_REQUEST['action']=="list") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-list');
elseif ($_REQUEST['action']=="list" and $_REQUEST['op']=="au") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-list-au');
elseif ($_REQUEST['action']=="list" and $_REQUEST['op']=="sale") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-list-sale');
elseif ($_REQUEST['action']=="list" and $_REQUEST['op']=="torg") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-list-torg');
elseif ($_REQUEST['action']=="list" and $_REQUEST['op']=="instant") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-list-instant');


elseif ($_REQUEST['op']=="au") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-au');
elseif ($_REQUEST['op']=="sale") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-sale');
elseif ($_REQUEST['op']=="torg") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-torg');
elseif ($_REQUEST['op']=="instant") $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%-instant');

else $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%');
					
} else {

if ($pagemode=='findfirst'){
$pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%/find-first/'.urlencode($query));
}

if ($pagemode=='find'){
$pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/torg/'.$id.'-%page%/find/'.urlencode($query));
}
}
$modvip  = $inDB->get_fields('cms_modules', 'content="mod_torg_vip"', 'id');
$smarty->assign('cfg_vip',  $inCore->loadModuleConfig($modvip['id']));		
$smarty->assign('cfg', $cfg);
$smarty->assign('page', $page);
//$smarty->assign('chars', $chars);
$smarty->assign('search_details', $search_details);
//$smarty->assign('fstruct', $fstruct);
$smarty->assign('items', $items);
$smarty->assign('comments', $comments);
$smarty->assign('pagebar', $pagebar);
		
			
}
			
if ($_REQUEST['action']=="list"){
$smarty->display('com_torg_view_list.tpl');
} else {
$smarty->display('com_torg_view.tpl');
}

     
} else { cmsCore::error404(); }

return true;

}

  //////////////////////////// VIEW ITEM DETAILS ///////////////////////////////////////////////////////////////////////
    if ($do == 'item'){
      



        $id = $inCore->request('id', 'int');
        $_SESSION['torg_last_url'] = $_SERVER['REQUEST_URI'];
		
		
		
        $sql = "SELECT i.*, u.login, u.nickname, ut.company, ut.torg_rating, c.title as cat_title
		FROM cms_torg_items i
		                LEFT JOIN cms_torg_cats c ON c.id = i.category_id
				LEFT JOIN cms_users u ON u.id = i.user_id
				LEFT JOIN cms_torg_users ut ON ut.id = i.user_id
		WHERE i.id = $id
		";
        $itemres = $inDB->query($sql);

 
      
   $cfg = $inCore->loadComponentConfig('torg');
        if ($inDB->num_rows($itemres)>0){
            $item = $inDB->fetch_assoc($itemres);







            if ((!$item['published'] || $item['on_premod']) && !$inUser->is_admin){
                $inCore->halt();
            }
$images = array();
$images = getImages($item['id']);
		   
            $fdata = unserialize($item['fieldsdata']);
		 $item['pubdate']  = cmsCore::dateformat($item['pubdate']);
            if ($item['meta_keys']) { $inPage->setKeywords($item['meta_keys']); }
            if ($item['meta_desc']) { $inPage->setDescription($item['meta_desc']); }

            $ratingdata = $model->ratingData($id);
			   $ibuydata = $model->ibuyData($id);
			   $stavkadata = $model->stavkaData($id);
			      $prodanodata = $model->prodanoData($id);
			

            $sql = "SELECT * FROM cms_torg_cats WHERE id = ".$item['category_id'];
            $catres = $inDB->query($sql) ;
            $cat = $inDB->fetch_assoc($catres);
            $fstruct = unserialize($cat['fieldsstruct']);

   	

            //PATHWAY ENTRY
            $left_key   = $cat['NSLeft'];
            $right_key  = $cat['NSRight'];

            $path_list  = $model->getCategoryPath($left_key, $right_key);

            if ($path_list){
                foreach($path_list as $pcat){
                    $inPage->addPathway($pcat['title'], '/torg/'.$pcat['id']);
                }
            }

            $inPage->addPathway($item['title'], '/torg/item'.$item['id'].'.html');
            $inPage->setTitle($item['title'] . ' - ' . $menutitle);


            if ($cat['view_type']=='shop'){

				$shopCartLink=$model->shopCartLink();
				
            }

            //update hits
            $inDB->query("UPDATE cms_torg_items SET hits = hits + 1 WHERE id = '{$id}'") ;

            //print item details

			
			$fields = array();
			
            if (sizeof($fstruct)>0){
                foreach($fstruct as $key=>$value){
                    if (@$fdata[$key]!=''){
                        if (strstr($value, '/~h~/')){
                            $value = str_replace('/~h~/', '', $value);
                            $htmlfield = true;
                        }
                        if (strstr($value, '/~m~/')){
                            $value = str_replace('/~m~/', '', $value);
                            $makelink = true;
                        } else {$makelink = false; }
                        $field = str_replace('<p>', '<p style="margin-top:0px; margin-bottom:5px">', $fdata[$key]);
                        if (strstr($value, '/~l~/')){
                            $field = '<a class="torg_detaillink" href="/load/url='.$field.'" target="_blank">'.str_replace('/~l~/', '', $value).'</a> ('.$inCore->fileDownloadCount($field).')';

                        } else {
 
                            if (isset($htmlfield)) {
                                if ($makelink) {
                                     $field = $inCore->getUCSearchLink($cat['id'], null, $key, strip_tags($field));
                                } else {
                                    //PROCESS FILTERS, if neccessary
                                    if ($cat['filters']){
                                        $filters = $inCore->getFilters();
                                        if ($filters){
                                            foreach($filters as $id=>$_data){
                                                require_once $_SERVER['DOCUMENT_ROOT'].'/filters/'.$_data['link'].'/filter.php';
                                                $_data['link']($field);
                                            }
                                        }
                                    }
                                     $field =  str_replace('\"', '"', $field);
                                }
                            } else {
                                if ($makelink) {
                                     $field =  $inCore->getUCSearchLink($cat['id'], null, $key, $field);
                                }
                            }
                            
                        }
						$fields[$value] = $field;
                    }
                }
            }
            if ($cat['view_type']=='shop'){
                $already = $model->shopIsInCart($item['id']);
                //$item['price'] = number_format(shopDiscountPrice($item['id'], $item['category_id'], $item['price']), 0, '.', ' ');
				
            }
			
			
            if ($item['on_moderate']){
                $user = $inDB->get_fields('cms_users', "id={$item['user_id']}", 'login, nickname');
                $getProfileLink = cmsUser::getProfileLink($user['login'], $user['nickname']);
            }

            if ($cat['is_ratings']){
				$ratingForm = $model->ratingForm($ratingdata, $item['id']);	

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


			$stavkaForm = $model->stavkaForm($stavkadata, $item['id']);
			$prodanoForm = $model->prodanoForm($prodanodata, $item['id']);	
			$ibuyForm = $model->ibuyForm($ibuydata, $item['id']);	
	                $au_ppsdate = $model->AuPPS($au_ppsdate, $item['id']);
                        $date=date('Y-m-d H:i:s');
                        $au_enddate = ($item['au_endtype'] == 2 ? $au_ppsdate['ppsend'] : $item['au_enddate']);
                        $au_end = ($au_enddate <= $date ? true : false);



include_once($_SERVER['DOCUMENT_ROOT'].'/components/users/includes/usercore.php');

$inUser = cmsUser::getInstance();

	
$usr['awards_html']			 = $cfg['sw_awards'] ? usrAwards($item['user_id']) : false;
$item['flogdate'] = strip_tags(usrStatus($item['user_id'], $item['flogdate'], false, $item['gender']));
$usr_status = ($item['flogdate'] == $_LANG['ONLINE'] ? '<span class="online">'.$_LANG['ONLINE'].'</span>' : '<span class="offline">'.$_LANG['OFFLINE'].'</span>');


$usr_klient=$inDB->rows_count('cms_user_zakazi', "from_id={$inUser->id} AND opla4en = 1 AND item_id={$item['id']}");
	
$usr['torg_count'] = $inDB->rows_count('cms_torg_items', "user_id={$item['user_id']} AND published=1  AND prodano != 1 AND kolvo != 0 AND archive != 1 AND category_id={$item['category_id']}");

$karm_vote=($usr_klient ? '<table><tr><td><img><a>' : '');
$usr['karma'] = strip_tags( $model->getTorgKarmaFormat($item['user_id'], false), $karm_vote );

$awards = $inDB->get_fields('cms_user_awards', "user_id={$item['user_id']}", 'title, description,imageurl');


	

$item = cmsCore::callEvent('GET_TORG_ITEM', $item);

$usrid=$inUser->id;
$item['is_in_cart'] = $model->isItemInCart($item['id']);
	  
$smarty = $inCore->initSmarty('components', 'com_torg_item.tpl');
      
$smarty->assign('images', $images);
$smarty->assign('shopCartLink', $shopCartLink);
$smarty->assign('getProfileLink', $getProfileLink);
$smarty->assign('tagline', tagLine($item['tags'], $cat['id']));
$smarty->assign('item', $item);
$smarty->assign('usrid', $usrid);
$smarty->assign('awards', $awards);
$smarty->assign('cat', $cat);					  
$smarty->assign('usr_karma', $usr['karma']);
$smarty->assign('torg_count', $usr['torg_count']);
$smarty->assign('usr_status', $usr_status);
$smarty->assign('comments_count', $usr['comments_count']);
$smarty->assign('fields', $fields);
$smarty->assign('ibuyForm', $ibuyForm);
$smarty->assign('ratingForm', $ratingForm);
$smarty->assign('stavkaForm', $stavkaForm);
$smarty->assign('prodanoForm', $prodanoForm);
$smarty->assign('au_ppsdate', $au_ppsdate);
$smarty->assign('au_end', $au_end);
$smarty->assign('date', $date);
$smarty->assign('cfg', $cfg);			
$smarty->assign('show_comments', $show_comments);
$smarty->assign('show_torg_rew', $show_torg_rew);	
$smarty->assign('usr_avatar', usrImage($item['user_id']));
$smarty->assign('usr_login', $item['login']);
$smarty->assign('usr_nickname', $item['nickname']);
$smarty->assign('usr_company', $item['company']);
$smarty->assign('usr_rating', $item['torg_rating']);
$smarty->assign('sdelki', $inDB->rows_count('cms_user_zakazi', "to_id={$item['user_id']} AND item_id={$item['id']} AND provesti=1"));
$smarty->assign('usr_klient', $usr_klient);
$smarty->assign('usrcfg', $model->loadTorgConfig('pages', $item['user_id']));
         $smarty->assign('is_admin', $inUser->is_admin);
$smarty->assign('awards_description', $awards['description']);
$smarty->assign('awards_imageurl', $awards['imageurl']);
$smarty->display('com_torg_item.tpl');


            //Выводим обзоры на товар, если есть нато разрешение для рубрики в которой находиться данный товар
if($inCore->isComponentInstalled('rew')){
               $model->includeRew();
                rew('torg',$item['id']);
}
            //show user comments
if($inCore->isComponentInstalled('comments')){
                $inCore->includeComments();
                comments('torg', $item['id']);
}
} else { cmsCore::error404(); }

        return true;
		
}
	
	


    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// S H O P /////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// ADD TO CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'addcart'){
	 $model = new cms_model_torg();
        $model->shopAddToCart($id, 1);
        header('location:/torg/viewcart.html');
    }
    ///////////////////////// VIEW CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'viewcart'){

        $inPage->backButton(false);
     shopCart();
    }
    ///////////////////////// DELETE FROM CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'cartremove'){
	 $model = new cms_model_torg();
        $model->shopRemoveFromCart($id);
        header('location:'.$_SERVER['HTTP_REFERER']);
    }
    ///////////////////////// CLEAR CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'clearcart'){
	 $model = new cms_model_torg();
        $model->shopClearCart();
        header('location:'.$_SERVER['HTTP_REFERER']);
    }
    ///////////////////////// CLEAR CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'savecart'){
        $itemcounts =  $inCore->request('kolvo', 'array');
        if (is_array($itemcounts)){
		 $model = new cms_model_torg();
            $model->shopUpdateCart($itemcounts);
        }
        header('location:'.$_SERVER['HTTP_REFERER']);
    }
    ///////////////////////// ORDER //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'order'){

       shopOrder($cfg);
    }
    ///////////////////////// ORDER //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'finish'){

   shopFinishOrder($cfg);
    }

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

		

    if ($do == 'add_item' || $do == 'edit_item'){
     $inCore = cmsCore::getInstance();
    $inUser = cmsUser::getInstance();

if ($do == 'add_item') {$addoredit="add_torg_item"; }
elseif ($do == 'edit_item') {$addoredit="edit_torg_item"; }
if (IS_BILLING) { cmsBilling::checkBalance('torg', $addoredit); }



 if ($inUser->id){
        $cat_id     = $inCore->request('cat_id', 'int');
        $cat        = $inDB->get_fields('cms_torg_cats', 'id='.$cat_id, '*');

        if (!$cat){ cmsCore::error404(); }

        $is_can_add = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id) || $inUser->is_admin;

        $left_key   = $cat['NSLeft'];
        $right_key  = $cat['NSRight'];
        $path_list  = $model->getCategoryPath($left_key, $right_key);
        if ($path_list){
            foreach($path_list as $pcat){
                $inPage->addPathway($pcat['title'], '/torg/'.$pcat['id']);
            }
        }
	$cats =	$inCore->getListItemsNS('cms_torg_cats', $cat_id);

        if ($do == 'add_item'){

            $inPage->setTitle("Добавление товара");
            $inPage->addPathway("Добавление товара");
            
            if (!$is_can_add){ $inCore->halt(); }

            $item = array();
            $fdata = array();
	                
 

	
 }
        
        if ($do == 'edit_item'){

            $inPage->setTitle("Редактирование товара");
            $inPage->addPathway("Редактирование товара");

            $item_id        = $inCore->request('item_id', 'int', 0);
            $item           = $inDB->get_fields('cms_torg_items', 'id='.$item_id, '*');
       
            if (!$item) { $inCore->halt(); }

            $is_cat_access  = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id);
            $is_can_edit    = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;

            if (!$is_can_edit) { $inCore->halt(); }
            $fdata = unserialize($item['fieldsdata']);
         //берем фотки для товара
     $photos = array();
            $photos = getImages($item_id);
            if($photos){$item['photos'] = $photos;}   
   
        }

	    
        $fields = array();

        $fstruct = unserialize($cat['fieldsstruct']);

        foreach($fstruct as $f_id=>$value){

            if (strstr($value, '/~h~/')) { $ftype = 'html'; $value=str_replace('/~h~/', '', $value); }
            elseif (strstr($value, '/~l~/')) { $ftype = 'link'; $value=str_replace('/~l~/', '', $value); } else { $ftype='text'; }

            if (strstr($value, '/~m~/')) { $makelink = true; $value=str_replace('/~m~/', '', $value); }
            else { $makelink = false; }

            $next['ftype']      = $ftype;
            $next['title']      = $value;
			
	    $next['nickname']      = $value;
            $next['login']      = $value;
            $next['com']      = $value;
            $next['avatar']      = $value;
			
		
			
            $next['opisanie']      = $value;
            $next['makelink']   = $makelink;

            if ($fdata[$f_id]){
                $next['value']  = str_replace('\"', '"', $fdata[$f_id]);
            } else {
                $next['value']  = '';
            }

            $fields[] = $next;
            
        }

     $inCore->includeFile('components/torg/model_users.php');
    $model_users = new cms_model_torg_users();

           $id = $inUser->id;
           $user_email = $inUser->email;
           $user_company = $inUser->nickname;
	   
if ($item['filename_orig']){ 
$item['file_icon'] = $inCore->fileIcon($item['filename_orig']);
}
$item['filesize_format'] = ($item['filesize']/1024 < 1024 ? round($item['filesize']/1024).' Кб' : round($item['filesize']/1024/1024, 1).' Мб');
  
        $smarty = $inCore->initSmarty('components', 'com_torg_add.tpl');
            $smarty->assign('do', $do);
            $smarty->assign('item', $item);
            $smarty->assign('fields', $fields);
            $smarty->assign('cat', $cat);
	         $smarty->assign('userid', $inUser->id);
	    $usr_itemscount = $inDB->rows_count('cms_torg_items', "user_id={$id}", '');
	    $smarty->assign('usr_itemscount', $usr_itemscount);
            $smarty->assign('usrcfg', $model_users->loadGroupConfig());	    


$smarty->assign('cats', $cats);
            $smarty->assign('cfg', $cfg);
            $smarty->assign('is_admin', $inUser->is_admin);
            $smarty->assign('cat_id', $cat_id);
       
$smarty->assign('is_billing', IS_BILLING);
if (IS_BILLING){ $smarty->assign('balance', $inUser->balance); }
	   $smarty->display('com_torg_add.tpl');
		
		
		

        return;
} else 		{ $inCore->redirect('/login'); }
    } 

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

    if ($do == 'submit_item'){
	     $andadd=$inCore->request('andadd', 'int');
        $opt        = $inCore->request('opt', 'str', 'add');
        $cat_id     = $inCore->request('cat_id', 'int');
        $cat        = $inDB->get_fields('cms_torg_cats', 'id='.$cat_id, '*');
        $item_id    = $inCore->request('item_id', 'int');

        if ($opt == 'add'){
            $item = array();
            $is_can_add = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id) || $inUser->is_admin;
            if (!$is_can_add){ $inCore->halt(); }
	     
        }

        if ($opt == 'edit'){
            $item = $inDB->get_fields('cms_torg_items', "id={$item_id}", '*');
            $is_cat_access  = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id);
            $is_can_edit    = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;
            if (!$is_can_edit){ $inCore->halt(); }

        }

        $inCore->includeGraphics();

        $inCore->loadLib('tags');
		
		
		
      $vipdays    = $inCore->request('vipdays', 'int', 0);
	  
	  

        //get variables
        $item['cat_id']         = $cat_id;
        $item['title']          = $inCore->request('title', 'str');
		
	$item['com']          = $inCore->request('com', 'str');
	$item['nickname']          = $inCore->request('nickname', 'str');
	$item['login']          = $inCore->request('login', 'str');
	$item['avatar']          = $inCore->request('avatar', 'str');


		  
        $item['published']      = ($cfg['premod']&&!$inUser->is_admin ? 0 : 1);
        $item['on_moderate']    = ($cfg['premod']&&!$inUser->is_admin ? 1 : 0);

        $item['fdata']          = $_POST['fdata'];
        foreach($item['fdata'] as $key=>$value) { $item['fdata'][$key] = trim($value); }

        $item['is_comments']    = $cfg['is_comments'];
        $item['meta_desc']      = $item['title'];
        $item['meta_keys']      = $item['title'];
        $item['tags']           = $inCore->request('tags', 'str');

        $item['pubdate']        = date('Y-m-d H:i');

        $item['canmany']        = 1;
		

$item['torg']        = 1;
$item['au']        = 1;
$item['au_endtype']        = 1;
$item['instant']        = 1;
$item['sale']        = 1;
$item['zakaz']        = 1;
$item['free']        = 1;
$item['obmen']        = 1;

		
        //get fields data
$item['fields']         = serialize($item['fdata']);
$item['fields']         = $inDB->escape_string($item['fields']);

$item['price']          = 0;
$item['price_old']          = 0;
$item['billing_buy']        = 0;
$item['wm_buy']        = 0;
$item['price_nds']          = 0;
$item['canmany']        = 1;

$item['price2']        = 0;
$item['price2_nds']        = 0;
$item['price_min']        = 0;
	
			   




		if ($inCore->inRequest('price')) {
                        $canmany        = $inCore->request('canmany', 'int');
			$price          = $inCore->request('price', 'str');
			$price          = str_replace(',', '.', $price);
			$price          = round($price, 2);
                        $item['price']  = $price;
			$price_old          = $inCore->request('price_old', 'str');
			$price_old          = str_replace(',', '.', $price_old);
			$price_old          = round($price_old, 2);
			$item['price_old']  = $price_old;
                        $item['canmany']= $canmany;
			$item['billing_buy'] = $inCore->request('billing_buy', 'int');
			$item['wm_buy'] = $inCore->request('wm_buy', 'int');
				}
	    
		
		
			
			$price_min          = $inCore->request('price_min', 'str');
			$price_min          = str_replace(',', '.', $price_min);
			$price_min          = round($price_min, 2);
                        $item['price_min']  = $price_min;
			
			$price2          = $inCore->request('price2', 'str');
			$price2          = str_replace(',', '.', $price2);
			$price2          = round($price2, 2);
                        $item['price2']  = $price2;
			
$price_nds        = $inCore->request('price_nds', 'int');
$item['price_nds']= $price_nds;	    
$price2_nds        = $inCore->request('price2_nds', 'int');
$item['price2_nds']= $price2_nds;	 
			
		
$art        = $inCore->request('art', 'str');
$item['art']= $art;	 

$kolvo  = $inCore->request('kolvo', 'str');
$item['kolvo']= $kolvo;	 
		
$sostoyanie        = $inCore->request('sostoyanie', 'int');
$item['sostoyanie']= $sostoyanie;
	   

$torg        = $inCore->request('torg', 'int');
$item['torg']= $torg;	  



$au        = $inCore->request('au', 'int');
$item['au']= $au;

$au_interval        = $inCore->request('au_interval', 'str');
$item['au_interval']= $au_interval;

$au_endtype       = $inCore->request('au_endtype', 'int');
$item['au_endtype']= $au_endtype;
if ($au_endtype==1) {
$au_enddate        = $inCore->request('enddate', 'str');
} else{
$au_enddate        = $inCore->request('endpps', 'str');   
}
$item['au_enddate']= $au_enddate;



$instant        = $inCore->request('instant', 'int');
$item['instant']= $instant;	


$sale        = $inCore->request('sale', 'int');
$item['sale']= $sale;	

$zakaz        = $inCore->request('zakaz', 'int');
$item['zakaz']= $zakaz;	

$zakaz_dney        = $inCore->request('zakaz_dney', 'str');
$item['zakaz_dney']= $zakaz_dney;	

$zakaz_predoplata        = $inCore->request('zakaz_predoplata', 'str');
$item['zakaz_predoplata']= $zakaz_predoplata;	

$free        = $inCore->request('free', 'int');
$item['free']= $free;	

$obmen        = $inCore->request('obmen', 'int');
$item['obmen']= $obmen;

$eltovar        = $inCore->request('eltovar', 'int');
$item['eltovar']= $eltovar;	

$free_text        = $inCore->request('free_text', 'str');
$item['free_text']= $free_text;	

$obmen_text        = $inCore->request('obmen_text', 'str');
$item['obmen_text']= $obmen_text;	


$eltovar_text        = $inCore->request('eltovar_text', 'str');
$item['eltovar_text']= $eltovar_text;

$eltovar_link      = $inCore->request('eltovar_link', 'str');
$item['eltovar_link']= $eltovar_link;	

			

		      if(!$errors){
         $img_errors = false;
         //добавляем основное изображение
         $file = uploadImage($cat_id, $item['id'], 'imageurl', 'one',false);
         if($file['error']){
            cmsCore::addSessionMessage($_LANG['UPLOADING_ERROR'].$file['name'].': '.$file['error'], 'error');
            $img_errors = true;
         }
         if($file['filename'] && !$img_errors){
            $model->addBasicPhoto($item['id'], $file['filename']);
         }
         //добавляем дополнительные фото
         $files = uploadImage($cat_id, $item['id'], 'upphotos', 'multi', false);
         foreach($files as $key=>$value){
            if($value['error']){
               cmsCore::addSessionMessage($_LANG['UPLOADING_ERROR'].$value['name'].': '.$value['error'], 'error');
               $img_errors = true;
            }
         }
	 
		 
		 
      }


        if ($opt=='add'){ 
		
				$item_id = $model->addItem($item);
				

				if (!$cfg['premod'] || $inUser->is_admin) {
					//регистрируем событие
					cmsActions::log('add_torg', array(
						'object' => $item['title'],
						'object_url' => '/torg/item'.$item_id.'.html',
						'object_id' => $item_id,
						'target' => $cat['title'],
						'target_url' => '/torg/'.$cat['id'],
						'target_id' => $cat['id'], 
						'description' => ''
					));
				}
		}
		
		
				
	


		
        if ($opt=='edit'){ $model->updateItem($item_id, $item); }
		


 

        if ($inUser->id != 1 && $cfg['premod'] && $cfg['premod_msg']){

            $link = '<a href="/torg/item'.$item_id.'.html">'.$item['title'].'</a>';
            $user = '<a href="'.cmsUser::getProfileURL($inUser->login).'">'.$inUser->nickname.'</a>';

            if ($opt=='add')  { $message = $_LANG['MSG_ITEM_SUBMIT']; }
            if ($opt=='edit') { $message = $_LANG['MSG_ITEM_EDITED']; }
            $message = str_replace('%user%', $user, $message);
            $message = str_replace('%link%', $link, $message);

            cmsUser::sendMessage(USER_UPDATER, 1, $message);
            
        }
if ($vipdays) {
		//vip товары - обозначаем время	
		
            $model->setVip($item_id, $vipdays);
   

        if (IS_BILLING) {
	       if ($opt=='add'){ 
            cmsBilling::process('torg', 'add_torg_item');
	       }
	       elseif ($opt=='edit'){ 
            cmsBilling::process('torg', 'edit_torg_item');
	    

	       }
            if ($cfg['vip_enabled'] && $vipdays && $cfg['vip_day_cost']){
                if ($vipdays > $cfg['vip_max_days']) { $vipdays = $cfg['vip_max_days']; }
                $summ = $vipdays * $cfg['vip_day_cost'];
                if ($inUser->balance >= $summ){
                    cmsBilling::pay($inUser->id, $summ, $_LANG['VIP_BUY_LOG']);
                    $model->setVip($item_id, $vipdays);
                }                
            }
        }
}
$item_user_id=$inUser->id;
$item_user_login=$inUser->login;
$item_user_group_id=$inUser->group_id;
$item_user_email=$inUser->email;
$nowdate        = date('Y-m-d H:i:s');
$shop_detected = $inDB->rows_count('cms_torg_users', "id={$item_user_id}", '1');
if (!$shop_detected) {
$sql = "INSERT INTO cms_torg_users (id,login, group_id,email, regdate) VALUES ('{$item_user_id}','{$item_user_login}','{$item_user_group_id}', '{$item_user_email}', '{$nowdate}')";
$inDB->query($sql);
}	
if (!$shop_detected) {
$inCore->redirect('/torg/settings'.$item_user_id.'.html');
} else {
   if ($andadd) { $inCore->redirect('/torg/'.$cat_id.'/add.html');}else{$inCore->redirect('/torg/'.$cat_id);}
}	
      
    }

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

    if ($do == 'accept_item'){

        $item_id = $inCore->request('item_id', 'int');

        if (!$item_id || !$inUser->is_admin){ $inCore->halt(); }

        $inDB->query("UPDATE cms_torg_items SET published=1, on_moderate=0 WHERE id={$item_id}");

        $item = $inDB->get_fields('cms_torg_items', "id={$item_id}", 'title, user_id, category_id');
		
		$cat  = $inDB->get_fields('cms_torg_cats', 'id='.$item['category_id'], 'id, title');
		
	





	//регистрируем событие
		cmsActions::log('add_torg', array(
				'object' => $item['title'],
				'user_id' => $item['user_id'],
				'object_url' => '/torg/item'.$item_id.'.html',
				'object_id' => $item_id,
				'target' => $cat['title'],
				'target_url' => '/torg/'.$cat['id'],
				'target_id' => $cat['id'], 
				'description' => ''
		));
        
        $item_link  = '<a href="/torg/item'.$item_id.'.html">'.$item['title'].'</a>';

        $message = str_replace('%link%', $item_link, $_LANG['MSG_ITEM_ACCEPTED']);

        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);

$inCore->redirectBack();


    }

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

    if ($do == 'delete_item'){

        $item_id = $inCore->request('item_id', 'int');

        if (!$item_id){ $inCore->halt(); }

        $item = $inDB->get_fields('cms_torg_items', "id={$item_id}", '*');

        if (!($item['user_id']==$inUser->id || $inUser->is_admin)){ $inCore->halt(); }

        $model->deleteItem($item_id);
if ($inUser->is_admin) {
        $message = str_replace('%item%', $item['title'], $_LANG['MSG_ITEM_REJECTED']);
        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);
}

        $inCore->redirect('/torg/u'.$item['user_id'].'/sklad');

    }
	
	//============================================================================//
//============================================================================//

    //
    // ДОБАВЛЕНИЕ ТОВАРА В КОРЗИНУ
    //

    if ($do=='add_to_cart' || $do=='add_to_cart_and_order'){

        $item_id    = $inCore->request('add_to_cart_item_id', 'int', 0);
        $qty = 1;
        $itemscount = $inCore->request('itemscount', 'int', 1);

        $model->addToCart($item_id, $qty, $itemscount);


if ($do=='add_to_cart_and_order') {
$inCore->redirect("/torg/order.html");
} else {$inCore->redirectBack();}
    }
   //
    
    // УДАЛЕНИЕ ТОВАРА ИЗ КОРЗИНЫ
    //

    if ($do=='delete_from_cart'){

        $item_id    = $inCore->request('delete_from_cart_item_id', 'int', 0);

        $model->deleteFromCart($item_id);

        $inCore->redirectBack();

    }
	


		
//Личный раздел пользователя

if ($_REQUEST['do']=='viewtorg'
    || $_REQUEST['do']=='provestizakazi'
    || $_REQUEST['do']=='viewzakazi'
    || $_REQUEST['do']=='viewzakazi-ok'
    || $_REQUEST['do']=='viewpokupki'
    || $_REQUEST['do']=='viewpokupki-order'
    || $_REQUEST['do']=='viewpokupki-ok'
    || $_REQUEST['do']=='delzakazi'
        || $_REQUEST['do']=='zakazibuyed'
    || $_REQUEST['do']=='pokupkitrue'
    || $_REQUEST['do']=='tovari_tocart'
    || $_REQUEST['do']=='tovari_to'
|| $_REQUEST['do']=='tovari-del'
|| $_REQUEST['do']=='tovari-del1'
|| $_REQUEST['do']=='tovari_torezerv'
|| $_REQUEST['do']=='tovari_norezerv'
|| $_REQUEST['do']=='tovari-torezerv'
|| $_REQUEST['do']=='tovari-norezerv'
|| $_REQUEST['do']=='viewtovari'
|| $_REQUEST['do']=='torg_settings'
|| $_REQUEST['do']=='torg_banners'
|| $_REQUEST['do']=='wall_add'
|| $_REQUEST['do']=='wall_delete'
|| $_REQUEST['do']=='sendemail' 
//|| $_REQUEST['op']=='tovari-edit' || $_REQUEST['op']=='go_import_xls' || $_REQUEST['op']=='import_xls' || $_REQUEST['op']=='tovari-edit' || $_REQUEST['op']=='go_import_xls'
){ 
	
	$inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB   = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    //global $_LANG;
	$inCore->includeFile('components/users/includes/usercore.php');

	
    $inCore->loadModel('users');
    $model = new cms_model_users();

    $cfg = $inCore->loadComponentConfig('torg');
	    $cfg_usr = $inCore->loadComponentConfig('users');
	// Проверяем включени ли компонент
	if(!$cfg['component_enabled']) { cmsCore::error404(); }
    $inCore->loadLanguage('components/users');


    //Определяем адрес для редиректа назад
    $back   = $inCore->getBackURL();
	
	$id     =   $inCore->request('id', 'int', 0);


 
	
    $inPage->setTitle($_LANG['USERS']);
		  //Подключаем CSS к странице
	$inPage->addHeadCSS('templates/'.$_CFG['template'].'/css/torgpages.css');
	

	
/////////////////////////////// VIEW torg ENTRIES ///////////////////////////////////////////////////////////////////////////////////////////
if ($do=='viewtorg'){ 
require_once("includes/viewtorg.php");
}
		
if ($do=='sendemail'){ 
if ($_REQUEST['mails']) {
$message=$_REQUEST['text'];
$message = str_replace("{ТОВАР}", $_REQUEST['item'], $message);
 
 $mails = explode(",", $_REQUEST['mails']);                
	 foreach ($mails as $adresat) {
$name = $inDB->get_field('cms_user_zakazi', 'email="'.$adresat.'"', 'from_nickname');
$bayer = $inDB->get_field('cms_user_zakazi', 'email="'.$adresat.'"', 'from_id');
$message=str_replace("{ПОКУПАТЕЛЬ}", $name, $message);	                    
	if ($adresat){
	 $inCore->mailText($adresat, $_REQUEST['sub'], $smessage);
	 $message='<h6>'.$_REQUEST['sub'].'</h6>'.$message;
	 cmsUser::sendMessage($inUser->id, $bayer, $message);
	$count++;}    
	    } if ($count){$msg="<div style='color:green'>Сообщение успешно отправлено ".$count." покупателям!</div>"; }
        
   if ($msg){
$url = '/torg/u'.$inUser->id.'/sklad';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();
   }
  	

}	
}	
if ($do=='provestizakazi'){ 
$usrid = $inUser->id;										
	$impl=implode(', ',$_POST['board_check']);
	
$date_p        = date('Y-m-d H:i');
$inDB->query("UPDATE cms_user_zakazi SET provesti=1, date_p='$date_p' WHERE to_id = $usrid AND item_id IN (".$impl.") ");
$inDB->query("UPDATE cms_torg_items SET kolvo = kolvo - 1 WHERE user_id=$usrid AND id IN (".$impl.") ");

 //отправляем сообщения
foreach ($_POST['board_check'] as $item) {
$usr = $inDB->get_field('cms_user_zakazi', "item_id=$item", 'from_id');

$message = 'Я провел <a href="/torg/item'.$item.'.html">Ваш заказ</a>. Можете <a href="/torg/u'.$usr.'/pokupki-order">приступить к его оплате >></a>';
if ($item){
cmsUser::sendMessage($usrid, $usr, $message);
echo $item;
$count++;} 
}

$url = '/torg/u'.$id.'/zakazi';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}
if ($do=='delzakazi'){ 
	$impl=implode(', ',$_POST['board_check']);
        $inDB->query("DELETE FROM cms_user_zakazi WHERE to_id = $id AND item_id IN (".$impl.") ");
		$url = '/torg/u'.$id.'/zakazi';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}	
if ($do=='zakazibuyed'){
$usrid = $inUser->id;	
$impl=implode(', ',$_POST['board_check']);
$inDB->query("UPDATE cms_user_zakazi SET opla4en = 1, opla4en_date = NOW() WHERE to_id = $usrid AND id IN  (".$impl.") ");

///////////////////////отправляем ссылку на цифровой товар
$inCore->loadModel('torg');
$modeltorg = new cms_model_torg();	
$cfg_pages=$modeltorg->loadTorgConfig('pages', $usrid);
$inCore->includeFile('components/torg/model_eltovar.php');
$model_eltovar = new cms_model_torg_eltovar();

foreach ($_POST['board_check'] as $item) {
   
$sql = "SELECT z.item_id, i.eltovar
FROM cms_user_zakazi z
LEFT JOIN cms_torg_items i ON i.id=z.item_id
WHERE z.id = '{$item}' AND z.to_id='{$usrid}' LIMIT 1";
$result = $inDB->query($sql);   
if(!$inDB->num_rows($result)){ return false; }
$eltovar = $inDB->fetch_assoc($result);
	
if ($eltovar['eltovar'] and !$cfg_pages['fastbuy']) {    
        $model_eltovar->sendDigitalLinks($item);
}
	 
}
/////////////////////////////////////////////////////////	 
	 
$url = '/torg/u'.$id.'/zakazi-ok';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}

	
	/////////////////////////////// VIEW ZAKAZI ENTRIES ///////////////////////////////////////////////////////////////////////////////////////////
if ($do=='viewzakazi'){
require_once("includes/viewzakazi.php");	
	
}
		
	
if ($do=='viewzakazi-ok'){ 
require_once("includes/viewzakazi-ok.php");		
}				
	


/////////////////////////////// VIEW Покупки ENTRIES ///////////////////////////////////////////////////////////////////////////////////////////
if ($do=='viewpokupki' || $do=='viewpokupki-order' || $do=='viewpokupki-ok'){ 
require_once("includes/viewpokupki.php");		
	
}
	       			

				
if ($do=='pokupkitrue'){ 
//////////////////////////// Подтверждение сделки
     $cfg        = $inCore->loadComponentConfig('torg');
$sale_karma_num =  $cfg['sale_karma_num'];
$sale_ratting_num = $cfg['sale_ratting_num'];
$userid = $inUser->id;	
$zid=$inCore->request('zid', 'int');
$prodavec_id=$inCore->request('prodavec_id', 'int');
$inDB->query("UPDATE cms_user_zakazi SET podtverjden = 1 WHERE id={$zid}");


//добавляем балы к рейтингу продавца и плюсуем к карме продавца
if ($cfg['sale_ratting']==1) {  
$inDB->query("UPDATE cms_torg_users SET torg_rating = torg_rating + $sale_ratting_num WHERE id={$prodavec_id}");
}
if ($cfg['sale_karma']==1) {
$inDB->query("INSERT cms_torg_karma (points, sender_id, senddate, user_id) Values('{$sale_karma_num}', 0, NOW(), {$prodavec_id})");
}
$url = '/torg/u'.$id.'/pokupki-ok';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();
/////////////////////////////////////////////
}



if ($do=='tovari_tocart'){ 
$id = $inUser->id;										
$usr['id']	 = $inUser->id;	
	$impl=implode(', ',$_POST['board_check']);
        $inDB->query("UPDATE cms_torg_items SET archive=1 WHERE user_id = $id AND id IN (".$impl.") ");
		$url = '/torg/u'.$id.'/tovari';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}
if ($do=='tovari_to'){ 
$id = $inUser->id;										
$usr['id']	 = $inUser->id;	
	$impl=implode(', ',$_POST['board_check']);
        $inDB->query("UPDATE cms_torg_items SET archive=0 WHERE user_id = $id AND id IN (".$impl.") ");
		$url = '/torg/u'.$id.'/tovari-cart';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}



if ($do=='tovari-del'){ 
	$impl=implode(', ',$_POST['board_check']);
	
        $inDB->query("UPDATE cms_torg_items SET prodano=1 WHERE user_id = $id AND id IN (".$impl.") ");
		$url = '/torg/u'.$id.'/tovari';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}	
if ($do=='tovari-del1'){ 

   $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
	    $model  = new cms_model_torg();
        $item_id = $inCore->request('item_id', 'int');

        if (!$item_id){ $inCore->halt(); }

        $item = $inDB->get_fields('cms_torg_items', "id={$item_id}", '*');

        if (!($item['user_id']==$inUser->id || $inUser->is_admin)){ $inCore->halt(); }

        $model->deleteItem($item_id);

        $message = str_replace('%item%', $item['title'], $_LANG['MSG_ITEM_REJECTED']);
        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);

        $inCore->redirect('/torg/u'.$id.'/tovari');

		
  
     //   $inDB->query("UPDATE cms_torg_items SET prodano=1 WHERE user_id = $id AND id='".$_REQUEST['item_id']."' ");
	//	$url = '/torg/u'.$id.'/tovari';
//if(!headers_sent())
//header('Location: '.$url);
//else
//echo '<script>window.location="'.$url.'";</script>';
//exit();

}
if ($do=='tovari_torezerv'){ 
$id = $inUser->id;										
$usr['id']	 = $inUser->id;	
	$impl=implode(', ',$_POST['board_check']);
	
        $inDB->query("UPDATE cms_torg_items SET prodano=2 WHERE user_id = $id AND id IN (".$impl.") ");
		$url = '/torg/u'.$id.'/tovari';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}
if ($do=='tovari_norezerv'){ 
$id = $inUser->id;										
$usr['id']	 = $inUser->id;	
	$impl=implode(', ',$_POST['board_check']);
	
        $inDB->query("UPDATE cms_torg_items SET prodano=0 WHERE user_id = $id AND id IN (".$impl.") ");
		$url = '/torg/u'.$id.'/tovari';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}

if ($do=='tovari-torezerv'){ 
$id = $inUser->id;										
$usr['id']	 = $inUser->id;	

	
        $inDB->query("UPDATE cms_torg_items SET prodano=2 WHERE user_id = $id AND id='".$_REQUEST['item_id']."' ");
		$url = '/torg/u'.$id.'/tovari';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}


if ($do=='tovari-norezerv'){ 
$id = $inUser->id;										
$usr['id']	 = $inUser->id;	
	
        $inDB->query("UPDATE cms_torg_items SET prodano=0 WHERE user_id = $id AND id='".$_REQUEST['item_id']."' ");
		$url = '/torg/u'.$id.'/tovari';
if(!headers_sent())
header('Location: '.$url);
else
echo '<script>window.location="'.$url.'";</script>';
exit();

}	
		

		
	/////////////////////////////// VIEW tovari ENTRIES ///////////////////////////////////////////////////////////////////////////////////////////
if ($do=='viewtovari'){

$torgitems=false;

	require_once("includes/viewtovari.php");	
	
}	




/////////////////////////////// EDIT PROFILE /////////////////////////////////////////////////////////////////////////////////////////
if ($do=='torg_settings' || $do=='torg_banners'){



require_once("includes/settings.php");	
}




	////////////////////////// DELETE FROM WALL ////////////////////////////////////////////////////////
	if ($do=='wall_delete'){
        $usertype   = $inCore->request('usertype',  'str', 'user');
        $record_id  = $inCore->request('record_id', 'int', 0);
        $my_id      = $inUser->id;
		if ($record_id && $my_id){
			
				if ($usertype=='user'){
					$can_delete = $inDB->get_fields('cms_torg_wall', "id = '$record_id' AND (user_id = '$my_id' OR author_id = '$my_id')", 'author_id, user_id');
					$author_id     = $can_delete['author_id'];
					$wall_user_id  = $can_delete['user_id'];
				}
                elseif ($usertype=='club'){
					$inCore->loadLib('clubs');
					$club_id        = $inDB->get_field('cms_torg_wall', "id = '$record_id'", 'user_id');
                    $is_club_admin  = clubUserIsAdmin($club_id, $my_id);
                    $is_club_moder  = clubUserIsRole($club_id, $my_id, 'moderator');
                    $is_author      = $inDB->rows_count('cms_torg_wall', "id = '$record_id' AND author_id = '$my_id'");
					$can_delete     = $is_author || $is_club_admin || $is_club_moder;
				}

				if ($can_delete || $inCore->userIsAdmin( $my_id )){
					$inDB->query("DELETE FROM cms_torg_wall WHERE id = '$record_id' LIMIT 1");
					switch ($usertype){
						case 'user': ($author_id == $my_id && $wall_user_id == $my_id) ? cmsActions::removeObjectLog('add_wall_my', $record_id) : cmsActions::removeObjectLog('add_wall', $record_id); break;
						case 'club': cmsActions::removeObjectLog('add_wall_club', $record_id); break;
					}
				}
				$inCore->addSessionMessage($_LANG['WALL_MESG_DEL'], 'info');
		}
        $inCore->redirectBack();
	}


////////////////////////// ADD TO WALL /////////////////////////////////////////
	if ($do=='wall_add'){
   $inCore->loadModel('users');
    $model = new cms_model_users();
        $usertype   = $inCore->request('usertype', 'str', 'user');
        $user_id    = $inCore->request('user_id', 'int', 0);
	      $points   = $inCore->request('points', 'int');
	      $points2   = $inCore->request('points2', 'int');
	      $points3   = $inCore->request('points3', 'int');
	          $item_id   = $inCore->request('item_id', 'int');
        $author_id  = $inUser->id;
		$message 	= $inCore->request('message', 'html', ''); 
		$message 	= $inCore->parseSmiles($message, true); 
		$message 	= $inDB->escape_string($message); 
		$errors 	= false;
		if (strlen($message)<2) { $inCore->addSessionMessage($_LANG['ERR_SEND_WALL'], 'error'); $errors = true; }

		if ($message && $user_id && $author_id && !$errors){
			switch ($usertype){
				case 'user': 	$usr  = $model->getUserShort($user_id);
								if (!$usr) { cmsCore::error404(); }
                $sql = "INSERT INTO cms_torg_wall (user_id, author_id, pubdate, content, usertype, points, points2, points3, item_id)
                        VALUES ('$user_id', '$author_id', NOW(), '$message', '$usertype', '$points', '$points2', '$points3', '$item_id')";
                $inDB->query($sql);
	   $inDB->query("UPDATE cms_user_zakazi SET otziv=1 WHERE item_id=$item_id AND to_id=$user_id  AND from_id=$author_id");
$wall_id = $inDB->get_last_id('cms_torg_wall');
							
                    //send email notification, if user want it
                    $usr['email_newmsg']   = $inDB->get_field('cms_user_profiles', "user_id='{$user_id}'", 'email_newmsg');
                    if ($usr['email_newmsg'] && $user_id != $author_id){
                            $inConf = cmsConfig::getInstance();
                            //fetch target user
$to_email       = $inDB->get_field('cms_users', 'id='.$user_id, 'email');
$postdate       = date('d/m/Y H:i:s');
$from_nick      = $inDB->get_field('cms_users', "id='{$author_id}'", 'nickname');
$profilelink    = HOST . cmsUser::getProfileURL($usr['login']);

                            $letter_path    = PATH.'/includes/letters/newwallpost.txt';
                            $letter         = file_get_contents($letter_path);

                            $letter= str_replace('{sitename}', $inConf->sitename, $letter);
                            $letter= str_replace('{profilelink}', $profilelink, $letter);
                            $letter= str_replace('{date}', $postdate, $letter);
                            $letter= str_replace('{from}', $from_nick, $letter);
                            $inCore->mailText($to_email, $_LANG['NEW_POST_ON_WALL'].'! - '.$inConf->sitename, $letter);
                    }
						break;
				
			
                }

		}
        $inCore->redirectBack();
	}



}//Личный раздел пользовотеля


    if ($do=='download'){

        $link_key = $inCore->request('link_key', 'str');
	
	$inCore->includeFile('components/torg/model_eltovar.php');
	$model_eltovar = new cms_model_torg_eltovar();
	
        $item = $model_eltovar->getDigitalDownload($link_key);

        if (!$item){ cmsCore::error404(); }

        if ($item['is_loaded']){
            $loaded_msg  = "<p>Файл уже был загружен. Повторная загрузка невозможна.</p>";
            $loaded_msg .= "<p>При необходимости обратитесь в <a href=\"/\">службу поддержки</a> магазина.</p>";
            $loaded_msg .= "<p><strong>Номер вашего заказа: #{$item['order_id']}</strong></p>";
            $inCore->halt($loaded_msg);
        }

        $file = '/upload/userfiles/'.$item['filename'];

        if (!file_exists(PATH. $file)) { $inCore->halt('Файл не найден. Обратитесь в службу поддержки магазина. Номер вашего заказа: #'.$item['order_id']); }

        header('Content-Disposition: attachment; filename='.$item['filename_orig'] . "\n");
        header('Content-Type: application/x-force-download; name="'.$file.'"' . "\n\n");

        echo file_get_contents(PATH . $file);

        $ip = $_SERVER['REMOTE_ADDR'];

        $inDB->query("UPDATE cms_torg_loads SET is_loaded=1, load_date = NOW(), load_ip='{$ip}' WHERE id = '{$item['id']}'");

        $inCore->halt();

    }
	$inCore->executePluginRoute($do);
	
	
} //function

?>
