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



function shopCart(){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inPage = cmsPage::getInstance();
    $inUser = cmsUser::getInstance();
	global $_LANG;
	if (isset($inUser->id)){ $user_id = $inUser->id; } else { $user_id = 0; }
	$sid = session_id();

		$inPage->backButton(false);
	 	$inPage->setTitle($_LANG['CART']);
		$inPage->addPathway($_LANG['CART']);

		$inPage->printHeading($_LANG['CART']);

		if ($user_id){ $user_sql = "(c.user_id=$user_id OR session_id='$sid')"; } else { $user_sql = "(c.user_id=0 AND c.session_id='$sid')"; }

		$sql = "SELECT i.title as title, i.mailp as mailp, i.id as id, i.canmany as canmany, c.id as cid, cat.id as category_id, cat.title as category, c.itemscount as itemscount, i.price as price
				FROM cms_torg_items i, cms_torg_cart c, cms_torg_cats cat
				WHERE $user_sql AND c.item_id = i.id AND i.category_id = cat.id
				ORDER BY c.pubdate";
		$rs = $inDB->query($sql) ;
		
		if ($inDB->num_rows($rs)){
			//BUILD LIST
			//delete confirmation js
			echo '<script type="text/javascript">'."\n";
				echo "function deleteItem(id){
						if(confirm('".$_LANG['DEL_POSITION_FROM_CART']."')){
							window.location.href = '/torg/cartremove'+id+'.html';	
						}
					}";
				echo "function clearCart(){
						if(confirm('".$_LANG['CLEAR_CART']."?')){
							window.location.href = '/torg/clearcart.html';	
						}
					}";				
				echo "function saveCart(){
						document.cartform.submit();	
					}";									
			echo '</script>'."\n";
			//table
			echo '<div class="o" style="border:1px solid #dee8ef;margin-bottom:10px"><form action="/torg/savecart.html" method="POST" name="cartform">';
			echo '<table width="100%" cellpadding="5" cellspacing="0" border="0">';
			echo '<tr>';
				echo '<td width="16">&nbsp;</td>';
				echo '<td width="50%"><strong>'.$_LANG['ITEM'].'</strong></td>';
				echo '<td width="10%"><strong>'.$_LANG['CAT'].'</strong></td>';
				echo '<td width="20%" align="center"><strong>'.$_LANG['QTY'].'</strong></td>';
				echo '<td width="10%"  align="center"><strong>'.$_LANG['PRICE'].'</strong></td>';
				echo '<td width="20" align="center">&nbsp;</td>';
			echo '</tr>';
			$row=0; $total = 0;
			while($item = $inDB->fetch_assoc($rs)){
                
				$row++;
				if ($row%2) { $class="search_row1"; } else { $class="search_row2"; }

				$item['realprice']      = $item['price'];
                $item['price']          = shopDiscountPrice($item['id'], $item['category_id'], $item['price']);
                $item['totalprice']     = $item['price'] * $item['itemscount'];
				$item['price']          = number_format($item['price'], 2, '.', '');
				$item['totalprice']     = number_format($item['totalprice'], 2, '.', '');
                $total += $item['totalprice'];

				echo '<tr>';
					echo '<td class="'.$class.'"><img src="/components/torg/images/icons/cart.png" border="0"></td>';
					echo '<td class="'.$class.'"><a href="/torg/item'.$item['id'].'.html">'.$item['title'].'</a></td>';
					echo '<td class="'.$class.'"><a href="/torg/'.$item['category_id'].'">'.$item['category'].'</a></td>';
					echo '<td class="'.$class.'" align="center">'.$item['price'].' x '.shopItemsCounter($item['cid'], $item['itemscount'], $item['canmany']).' =</td>';
					
					echo '<td class="'.$class.'" align="center"><strong>'.$item['totalprice'].'</strong></td>';
					echo '<td class="'.$class.'" align="center">';
							echo '<a href="javascript:deleteItem('.$item['id'].')" title="'.$_LANG['DELETE'].'"><img src="/admin/images/actions/delete.gif" border="0"/></a>';
					echo '</td>';
				echo '</tr>';
                
			}
			echo '</table>';
			echo '</form></div>';

            shopDiscountsInfo($total, true);
			$total = number_format($total, 2, '.', '');
			echo '<div id="cart_total">';
				echo '<div id="torg_price" style="float:right"><span>'.$_LANG['CART_TOTAL'].':</span> <b style="font-family:Georgia, Times New Roman, Times, serif; font-size:20px">'.$total.'</b> <font style="font-family:Georgia, "Times New Roman", Times, serif; ">'.$_LANG['RUB'].'</font></div>';
			echo '</div>';
			
			
			
			
						//buttons
			echo '<div style="clear:botch"><br/><br/><br/></div><div id="cart_buttons">';
				echo '<div id="cart_buttons1">';
					echo '<a href="javascript:saveCart()" title="'.$_LANG['SAVE'].'">';
						echo '<img src="/components/torg/images/shop/savecart.jpg" border="0" alt="'.$_LANG['SAVE'].'"/>';
					echo '</a> ';
					echo '<a href="javascript:clearCart();" title="'.$_LANG['CLEAR_CART'].'">';
						echo '<img src="/components/torg/images/shop/clearcart.jpg" border="0" alt="'.$_LANG['CLEAR_CART'].'"/>';
					echo '</a> ';
				echo '</div>';
				echo '<div id="cart_buttons2">';
					echo '<a href="/torg" title="'.$_LANG['BACK_TO_SHOP'].'">';
						echo '<img src="/components/torg/images/shop/cartback.jpg" border="0" alt="'.$_LANG['BACK_TO_SHOP'].'"/>';
					echo '</a> ';
					echo '<a href="/torg/order.html" title="'.$_LANG['CART_ORDER'].'">';
						echo '<img src="/components/torg/images/shop/cartorder.jpg" border="0" alt="'.$_LANG['CART_ORDER'].'"/>';
					echo '</a> ';
				echo '</div>';
			echo '</div>';
		} else {
			//NO ITEMS
			echo '<p>'.$_LANG['NOITEMS_IN_CART'].'</p>';
			echo '<div id="cart_buttons2">';
				echo '<a href="/torg" title="'.$_LANG['BACK_TO_SHOP'].'">';
					echo '<img src="/components/torg/images/shop/cartback.jpg" border="0" alt="'.$_LANG['BACK_TO_SHOP'].'"/>';
				echo '</a> ';
			echo '</div>';

		}

}

function shopOrder($cfg){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inPage = cmsPage::getInstance();
    $inUser = cmsUser::getInstance();
	global $_LANG;
	if (isset($inUser->id)){ $user_id = $inUser->id; } else { $user_id = 0; }	
	$sid = session_id();
	
		$inPage->backButton(false);
	 	$inPage->setTitle($_LANG['CART_ORDERING']);
		$inPage->addPathway($_LANG['CART'], '/torg/viewcart.html');
		$inPage->addPathway($_LANG['CART_ORDERING'], $_SERVER['REQUEST_URI']);

		echo '<div class="con_heading">'.$_LANG['CART_ORDERING'].'</div>';
		
		echo '<div class="con_description">'.nl2br($cfg['delivery']).'</div>';
		
		if ($user_id){ $user_sql = "(c.user_id=$user_id OR session_id='$sid')"; } else { $user_sql = "(c.user_id=0 AND c.session_id='$sid')"; }
			$sql = "SELECT i.title as title, i.mailp as mailp,  i.user_id as userid,  i.id as id, i.canmany as canmany, c.id as cid, cat.id as category_id, cat.title as category, c.itemscount as itemscount, i.price as price
		
				FROM cms_torg_items i, cms_torg_cart c, cms_torg_cats cat
				WHERE $user_sql AND c.item_id = i.id AND i.category_id = cat.id
				ORDER BY c.pubdate";
				
   
		$rs = $inDB->query($sql) ;
		
		if ($inDB->num_rows($rs)){
			//BUILD LIST
			//table
			
			echo '<div class="o" style="border:1px solid #c1d9f3;margin-bottom:10px"><form action="/torg/savecart.html" method="POST" name="cartform">';
			echo '<table width="100%" cellpadding="7" cellspacing="1" border="0" style="background:#c1d9f3">';
			echo '<tr>';
            echo '<td width="25%" style="color:red;"><div style="padding-left:5px"><strong>'.$_LANG['prodavec'].' \ '.$_LANG['CAT'].'</strong></div></td>';
             			
		        echo '<td style="color:red" width="40%"><strong>'.$_LANG['ITEM'].'</strong></td>';
            	echo '<td width="20%" align="center"><strong>'.$_LANG['QTY'].'</strong></td>';
							echo '<td width="15%"  align="center" style="color:red"><strong>'.$_LANG['PRICE'].'</strong></td>';
			echo '</tr>';
			$row=0; $total = 0;
			while($item = $inDB->fetch_assoc($rs)){
				$row++;
				if ($row%2) { $class="search_row1"; } else { $class="search_row2"; }

                $item['realprice'] = $item['price'];
                $item['price'] = shopDiscountPrice($item['id'], $item['category_id'], $item['price']);
                $item['totalprice'] = $item['price'] * $item['itemscount'];
				$item['price'] = number_format($item['price'], 2, '.', '');
				$item['totalprice'] = number_format($item['totalprice'], 2, '.', '');
                $total += $item['totalprice'];
				echo '<tr>';
                
		$usr = $inDB->get_fields('cms_users', "id={$item['userid']}", 'nickname, login, company');
		
echo '<td class="'.$class.'"><div style="padding-left:5px"><img src="/templates/_default_/images/icons/register.png" align=absmiddle> <b>'.cmsUser::getProfileLink($usr['login'], $usr['nickname']).'</b><div><a href="/index.php?view=search&query='.$usr['company'].'&gosearch.x=11&gosearch.y=10">'.$usr['company'].'</a></div></div><img src="/templates/_default_/images/icons/folder.png" align=absmiddle style="margin-left:5px"> <a href="/torg/'.$item['category_id'].'">'.$item['category'].'</a></td>';
echo '<td class="'.$class.'"><img src="/components/torg/images/icons/cart.png" border="0" align=absmiddle> <a style="font:bold 14px Arial;color:#000" href="/torg/item'.$item['id'].'.html">'.$item['title'].'</a></td>';

echo '<td class="'.$class.'" align="center">'.$item['price'].'<b> x '.$item['itemscount'].'</b></td>';
echo '<td class="'.$class.'" align="center" style="font:bold 14px Arial;color:#000">'.$item['totalprice'].'</td>';
echo '</tr>';			
			}
			echo '</table>';
			echo '</form>';
			
			shopDiscountsInfo($total);
            $total = number_format($total, 2, '.', '');
			
echo '<div id="torg_price" style="float:right"><span>'.$_LANG['TOTAL_PRICE'].':</span> <b style="font-family:Georgia, Times New Roman, Times, serif; font-size:20px">'.$total.'</b> <font style="font-family:Georgia, "Times New Roman", Times, serif; ">'.$_LANG['RUB'].'</font></div>';
	
				
			echo '<div style="clear:botch"><br/><br/><br/></div></div>';            





            IF ($id = $inUser->id)//  ПРОВЕРЯЕМ, ГОСТЬ ИЛИ ЗАРЕГИНЫЙ ЧЕЛ
           {
		  
           $email = $inUser->email;//  ВЫТАСКИВАЕМ E-MAIL ПОЛЬЗОВАТЕЛЯ (ЕСЛИ ОН ЗАРЕГИЛСЯ)
           $company = $inUser->company;
        
                    $phone = $inUser->phone.' '.$inUser->mob;
                    $fio = $inUser->nickname;

           $text = 'Вы оформляете заказ от имени: '.$name;
           }
           else
           {
                 $company     = 'Введите название компании';
                 $comment       = 'Дополнительная информация';
                 $fio       = 'Укажите свои ФИО';
                 $phone       = 'Укажите свой телефон';
           		 $email       = 'Укажите свой e-mail';
                 $text = 'Вы не зарегистрированы! И Вам придется вручную вводить свои контакты!';
          }


		//DELIVERY INFO FORM
		

			echo '<div class="o" style="border:1px solid #c1d9f3;margin:10px 0;width:520px;padding:10px 0;background:#fafafa"><form action="/torg/finish.html" method="POST">';
			echo '<div style="padding:6px 20px;font-size:14px"><b>'.$text.'</b></div><table width="100%" cellspacing="0" cellpadding="5">';
			echo '<tr>';
				echo '<td width="40%" align="right">'.$_LANG['FIO_CUSTOMER'].': </td>';
				?>
				<td width="60%" align="left"><input name="customer_fio" type="text" size="45" onkeyup="lookup(this.value);" value="<?=$fio;?>" onblur="if(this.value=='') this.value='Укажите свои ФИО'" onfocus="if(this.value=='Укажите свои ФИО') this.value='' " /></td>
			    <?
			echo '</tr>';
			echo '<tr>';
				echo '<td width="40%" align="right">'.$_LANG['ORGANIZATION'].': </td>';
				?>
				<td width="60%" align="left"><input name="customer_company" type="text" size="45" onkeyup="lookup(this.value);" value="<?=$company;?>" onblur="if(this.value=='') this.value='Введите название компании'" onfocus="if(this.value=='Введите название компании') this.value='' "/></td>
			    <?
			echo '</tr>';
			echo '<tr>';
				echo '<td width="40%" align="right">'.$_LANG['CONTACT_PHONE'].': </td>';
				?>
				<td width="60%" align="left">
				<input name="customer_phone" type="text" size="45" onkeyup="lookup(this.value);" value="<?=$phone;?>" onblur="if(this.value=='') this.value='Укажите свой телефон'" onfocus="if(this.value=='Укажите свой телефон') this.value='' "/></td>
			    <?
			echo '</tr>';
			echo '<tr>';
				echo '<td width="40%" align="right">E-mail: </td>';
				?>
				<td width="60%" align="left"><input name="customer_email" type="text" size="45" onkeyup="lookup(this.value);" value="<?=$email;?>" onblur="if(this.value=='') this.value='Укажите свой e-mail'" onfocus="if(this.value=='Укажите свой e-mail') this.value='' "/></td>
			    <?
			echo '</tr>';
			echo '<tr>';
					echo '<tr>';
				echo '<td width="40%" align="right">Адрес для доставки: </td>';
				?>
				<td width="60%" align="left"><input name="customer_adress" type="text" size="45" onkeyup="lookup(this.value);" value="<?=$adress;?>" onblur="if(this.value=='') this.value='Доставка не требуеться'" onfocus="if(this.value=='Доставка не требуеться') this.value='' "/></td>
			    <?
			echo '</tr>';
			echo '<tr>';
				echo '<td width="40%" align="right">'.$_LANG['CUSTOMER_COMMENT'].': </td>';
				?>
				<td width="60%" align="left"><input name="customer_comment" type="text" size="45" onkeyup="lookup(this.value);" value="<?=$comment;?>" /></td>
			    <?
			echo '</tr>';
            echo '<tr>';
                echo '<td width="40%" align="right">&nbsp;</td>';
				echo '<td width="60%" align="left">';
						echo cmsPage::getCaptcha();
				echo '</td>';
			echo '</tr>';

			echo '<tr>';
				echo '<td width="30%" align="right">&nbsp;</td>';
				echo '<td width="70%" align="right"><input name="order" type="submit" style="padding:5px;font-weight:bold;margin-right:17px" value="'.$_LANG['SUBMIT_ORDER'].'" /></td>';
			echo '</tr>';
			echo '</table>';
			echo '</form></div>';

		} else {
			//NO ITEMS
			echo '<p>'.$_LANG['NOITEMS_IN_CART'].'</p>';
			echo '<div id="cart_buttons2">';
				echo '<a href="/torg" title="'.$_LANG['BACK_TO_SHOP'].'">';
					echo '<img src="/components/torg/images/shop/cartback.jpg" border="0" alt="'.$_LANG['BACK_TO_SHOP'].'"/>';
				echo '</a> ';
			echo '</div>';

		}

}

function shopDiscountsInfo(&$total, $is_cart=false){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $total_orig = $total;

    $sql = "SELECT title, sign, unit, value, if_limit FROM cms_torg_discount WHERE cat_id = 0 AND sign>=2 ORDER BY sign DESC";
    $res = $inDB->query($sql) ;

    if($inDB->num_rows($res)){
        echo '<table width="100%" cellpadding="5" cellspacing="0" border="0">';
        while ($dis = $inDB->fetch_assoc($res)){
            $show_dis = false;
            $show_sign = '+';
            if ($dis['sign']==2){
                if ($dis['unit']=='%'){ $total = $total + ($total*($dis['value']/100)); }
                if ($dis['unit']=='руб.'){ $total = $total + $dis['value']; }
                $show_dis = true;
                $show_sign = '+';
            }
            if ($dis['sign']==3){
                $show_dis = ($total_orig >= $dis['if_limit']);
                if ($show_dis){
                    if ($dis['unit']=='%'){ $total = $total - ($total*($dis['value']/100)); }
                    if ($dis['unit']=='руб.'){ $total = $total - $dis['value']; }
                    $show_sign = '-';
                }
            }
            if ($show_dis){
                echo '<tr>';
                    echo '<td width="16" align="center">'.$show_sign.'</td>';
                    echo '<td>'.$dis['title'].'</td>';
                    echo '<td width="200">&nbsp</td>';
                    echo '<td width="120" align="center">&nbsp</td>';
                    if ($dis['unit']=='руб.'){
                        echo '<td width="100" align="center">'.number_format($dis['value'], 2, '.', '').'</td>';
                    } else {
                        echo '<td width="100" align="center">'.$dis['value'].'%</td>';
                    }
                    if ($is_cart){
                        echo '<td width="20">&nbsp;</td>';
                    }
                echo '</tr>';
            }
        }
        echo '</table>';
    }
}

function shopDiscountPrice($item_id, $cat_id, $price){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $sql = "SELECT sign, unit, value FROM cms_torg_discount WHERE cat_id = $cat_id OR cat_id = 0 AND sign<2";
    $res = $inDB->query($sql) ;

    if($inDB->num_rows($res)){
        while ($dis = $inDB->fetch_assoc($res)){
            if ($dis['unit']=='%'){ $price = $price + ($price*($dis['value']/100))*$dis['sign']; }
            if ($dis['unit']=='руб.'){ $price = $price + $dis['value']*$dis['sign']; }
        }
    }
    return $price;
}

function shopFinishOrder($cfg){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inPage = cmsPage::getInstance();
    $inUser = cmsUser::getInstance();
    $inConf = cmsConfig::getInstance();
     $model = new cms_model_torg();
    global $_CFG;
    global $_LANG;
	if (isset($inUser->id)){ $user_id = $inUser->id; } else { $user_id = 0; }
	$sid = session_id();

		$inPage->backButton(false);
	 	$inPage->setTitle($_LANG['ORDER_COMPLETE']);

		if ($user_id){ $user_sql = "(c.user_id=$user_id OR session_id='$sid')"; } else { $user_sql = "(c.user_id=0 AND c.session_id='$sid')"; }

		$sql = "SELECT i.title as title, i.mailp as mailp,  i.user_id as userid, i.company as company, i.id as id, i.canmany as canmany, i.price as price, i.zakaz as zakaz,
						c.id as cid, c.itemscount as itemscount,
						cat.id as category_id, cat.title as category
				FROM cms_torg_items i, cms_torg_cart c, cms_torg_cats cat
				WHERE $user_sql AND c.item_id = i.id AND i.category_id = cat.id
				ORDER BY c.pubdate";
		$rs = $inDB->query($sql) ;

		if ($inDB->num_rows($rs)){
			//check user data
			$customer = array();
			if(!empty($_REQUEST['customer_fio'])) { $customer['fio'] = $inCore->request('customer_fio', 'str'); } else { $error .= $_LANG['EMPTY_NAME'].'<br/>'; }
			if(!empty($_REQUEST['customer_phone'])) { $customer['phone'] = $inCore->request('customer_phone', 'str'); } else { $error .= $_LANG['EMPTY_PHONE'].'<br/>'; }
			$customer['company'] = $inCore->request('customer_company', 'str');
            $customer['email']   = $inCore->request('customer_email', 'str');
			$customer['comment'] = $inCore->request('customer_comment', 'str');
				$customer['adress'] = $inCore->request('customer_adress', 'str');
			

	
			if(!$inCore->checkCaptchaCode($_REQUEST['code'])) { $error .= $_LANG['ERR_CAPTCHA'].'<br/>'; }

   if($error==''){
        while($item = $inDB->fetch_assoc($rs)){
					$row++;
				    //$usere = $inDB->get_fields('cms_users', "id={$item['userid']}", 'email, login'); 
	   //$item['mailp'] = $usere['email'];
                    //$item['company']     = $usere['login'];
					$usr = $inDB->get_fields('cms_users', "id={$item['userid']}", 'nickname, email, login');
					$item['mailp']     = $usr['email'];
                    $item['company']     = $usr['nickname'];
                    $item['price']          = shopDiscountPrice($item['id'], $item['category_id'], $item['price']);
                    $item['totalprice']     = $item['price'] * $item['itemscount'];
                    $item['price']          = number_format($item['price'], 2, '.', '');
                    $item['totalprice']     = number_format($item['totalprice'], 2, '.', '');
                    $total += $item['totalprice'];
					$mail_message .= $row . '. ' . $item['title'] . ' (' . $item['itemscount'] . '  x ' . $item['price'] . ' '.$_LANG['RUB'].') = ' . $item['totalprice'] . ' '.$_LANG['RUB'] . "\n";
					


$sql = "INSERT INTO cms_torg_mail (email_prod, company_prod, poz, rubric, col, price, fio_pocup, company, phone, email_pocup, dop, adress, work)
VALUES ('{$item['mailp']}', '{$item['company']}', '{$item['title']}', '{$item['category']}', '{$item['itemscount']}', '{$item['price']}', '{$customer['fio']}', '{$customer['company']}', '{$customer['phone']}', '{$customer['email']}',  '{$customer['comment']}', '{$customer['adress']}', 0)";
	

$to_id      = $item['userid'];
$from_id    = $inUser->id;
	
$message = 'Оформил заказ на <a href="/torg/item'.$item['id'].'.html"><b>'.$item['title'].'</b></a> (кол-во: '.$item['itemscount'].')<br/><b>Телефон для связи:</b> '.$customer['phone'].'<br/><b>Адрес для доставки:</b><br/>'.$customer['adress'].'<br/><i>'.$customer['comment'].'</i>';
$sql_pm = "INSERT INTO cms_user_msg (to_id, from_id, senddate, is_new, message)
VALUES ('$to_id', '$from_id', NOW(), 1, '$message')";	

$message_zakazi = '<a href="/torg/item'.$item['id'].'.html"><b>'.$item['title'].'</b></a>';
$contacts = ''.$customer['phone'].'';
$adress = ''.$customer['adress'].'';
$short = '<i>'.$customer['comment'].'</i>';
$email = ''.$customer['email'].'';
$from_nickname = $inUser->nickname;
$from_login = $inUser->login;

$sql_zakazi = "INSERT INTO cms_user_zakazi (to_id, from_id, from_nickname, from_login, senddate, is_new, message, itemscount, price, totalprice, item_id, short, contacts, adress, email)
VALUES ('$to_id', '$from_id', '$from_nickname', '$from_login', NOW(), 1, '$message_zakazi', '{$item['itemscount']}', '{$item['price']}', '{$item['totalprice']}', '{$item['id']}', '$short', '$contacts', '$adress', '$email')";

$zakaz_plus = $item['zakaz'] + 1;
$sql_zakaz_plus = "UPDATE cms_torg_items SET zakaz=$zakaz_plus WHERE id={$item['id']} AND user_id={$to_id}";

    	$inDB->query($sql) ;
		 	$inDB->query($sql_pm) ;
				$inDB->query($sql_zakazi) ;
					$inDB->query($sql_zakaz_plus) ;
                }

			
					
                //echo '<div class="con_heading">'.$_LANG['THANK'].'!</div>';
				//echo '<p style="clear:both"><b>'.$_LANG['CUSTOMER_EMAIL_SUBJECT'].'.</b><br/>'.$_LANG['CUSTOMER_EMAIL_TEXT'].'</p>';



        $n = 0;

        //echo 'Юзер ID'.$user_id;
        echo '<h2>Спасибо! Ваша заявка отправлена.</h2><br />';
        echo 'Описание Вашей заявки:<br /><br />';
        echo '<table border = "1"><tr><td width="20%"> ПОСТАВЩИК </td><td width="25%"> РУБРИКА </td><td width="30%"> ПОЗИЦИЯ </td><td width="10%"> КОЛИЧЕСТВО </td><td width="%15"> ЦЕНА </td></tr>';
        $sql = "SELECT DISTINCT email_prod FROM cms_torg_mail WHERE work = 0";
        $ss = $inDB->query($sql) ;
        while ($row=mysql_fetch_array ($ss)) {
        $n++;
        $email_prod = $row['email_prod'];
        //echo 'Продавцу с этим e-mail: '.$email_prod.' отправим:';
        //echo '<br />';
        		$sqll = "SELECT * FROM cms_torg_mail WHERE email_prod = '$email_prod' AND work = 0";
        		$sss = $inDB->query($sqll) ;
        		while ($rows=mysql_fetch_array ($sss)) {

	   
        			echo '<tr><td>'.$rows['company_prod'].'</td><td>'.$rows['rubric'].'</td>';
        			echo '<td>'.$rows['poz'].'</td>';
        			echo '<td>'.$rows['col'].'</td>';

        			echo '<td>'.$rows['price'].'</td></tr>';
							echo '<td>'.$rows['adress'].'</td>';

        			//echo 'Ваши ФИО: '.$rows['fio_pocup'];
        			//echo ' - ';
        			//echo 'Ваша компания: '.$rows['company'];
        			//echo ' - ';
        			//echo 'Ваш телефон: '.$rows['phone'];
        			//echo ' - ';
        			//echo 'Ваш E-Mail: '.$rows['email_pocup'];
        			//echo ' - ';
        			//echo 'Дополнительно Вы указали: '.$rows['dop'];
        		    //echo 'Записываем её в новую таблицу<br />';
                     $sqla = "INSERT INTO cms_torg_mail_2 (email_prod_2, poz_2, rubric_2, col_2, price_2, fio_pocup_2, company_2, phone_2, email_pocup_2, dop_2, adress_2, work_2)
				    VALUES ('{$email_prod}', '{$rows['poz']}', '{$rows['rubric']}', '{$rows['col']}', '{$rows['price']}', '{$rows['fio_pocup']}', '{$rows['company']}', '{$rows['phone']}', '{$rows['email_pocup']}', '{$rows['dop']}', '{$rows['adress']}', 0)";
    	            $inDB->query($sqla) ;

        		}



                //echo '<br />Отправляем!!!!!!!!!<br />';
        		//message heading

        		$sqx = "SELECT * FROM cms_torg_mail_2";
        		$ssx = $inDB->query($sqx) ;
        		while ($rowx=mysql_fetch_array ($ssx)) {
        			    $fio_pocup = $rowx['fio_pocup_2'];
        			    $company = $rowx['company_2'];
        			    $phone = $rowx['phone_2'];
        			    $email_pocup = $rowx['email_pocup_2'];
						$adress = $rowx['adress_2'];
        			    $dop = $rowx['dop_2'];
						 $adress = $rowx['adress_2'];

        		}
				$mail_message = '';
				$mail_message .= $_LANG['GET_ORDER_FROM_torg']." \"".$inConf->sitename."\".\n\n";
				$mail_message .= $_LANG['CUSTOMER']."\n-----------------------------\n";
				//$mail_message = $rowx['fio_pocup_2'];
				$mail_message .= $_LANG['FIO'].": " . $fio_pocup . "\n";
				$mail_message .= $_LANG['COMPANY'].": " . $company . "\n";
				$mail_message .= $_LANG['PHONE'].": " . $phone . "\n";
				$mail_message .= "Адрес для доставки: " . $adress . "\n";
                $mail_message .= "EMAIL: " . $email_pocup . "\n";
				$mail_message .= $_LANG['ORDER_COMMENT'].": " . @$dop . "\n\n";
				//list of items
				$mail_message .= $_LANG['ORDER']."\n---------------------------------\n";
                $sqlld = "SELECT * FROM cms_torg_mail_2";
        		$ssq = $inDB->query($sqlld) ;
        		while ($rowl=mysql_fetch_array ($ssq)) {
        			  $mail_message .= "Рубрика: ".$rowl['rubric_2'].", Позиция: ".$rowl['poz_2']." в количестве: ".$rowl['col_2']." по цене: ".$rowl['price_2'] . "\n";


        		}
                $inCore->mailText($email_prod, $_LANG['EMAIL_SUBJECT'], $mail_message);
                $sqllw = "DELETE FROM cms_torg_mail_2 WHERE email_pocup_2 = '$email_pocup'";
        		$sst = $inDB->query($sqllw) ;

    			}
                 echo '</table><br /><br />';

        		//echo '</table><br /><br />';



                $sqla = "UPDATE cms_torg_mail SET work = 1 WHERE email_pocup = '$email_pocup'";
    			$ssw = $inDB->query($sqla) ;


                $model->shopClearCart();

        		echo 'Отправка Вами данной заявки не обязывает Вас к обязательной покупке!<br /><br />';
        		echo 'Количество поставщиков, получивщих Ваш заказ: '.$n;
        		echo '<br /><br />';
        		echo '<p><a href="/torg">'.$_LANG['tocat'].'</a></p>';


        } else {
				//order failed
				echo '<div class="con_heading">'.$_LANG['ERROR'].'!</div>';
				echo '<p style="clear:both; color:red">'.$error.'</p>';
				echo '<p><a href="#" onClick="window.history.back()">'.$_LANG['BACK'].'</a></p>';
			}


      }

     
}



function shopItemsCounter($cartitem_id, $count, $canmany=1){
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
	$count_field = '';
	if ($canmany) { $count_field = '<input type="text" style="text-align: center; font-size:9px; border:solid 1px black" size="5" name="kolvo['.$cartitem_id.']" value="'.$count.'"/>'; }
	else { $count_field = '<input type="hidden" name="kolvo['.$cartitem_id.']" value="1"/>1'; }
	return $count_field;
}







function uploadImage($cat_id, $item_id, $formname, $type= 'one'){
   $inCore = cmsCore::getInstance();

   //проверяем закачку файла
   if(!isset($_FILES["{$formname}"]["tmp_name"])){return false;}

   //проверяем основные директории
   if(!file_exists(PATH."/images/torg")){ mkdir(PATH."/images/torg");}
   if(!file_exists(PATH."/images/torg/small")){ mkdir(PATH."/images/torg/small");}
   if(!file_exists(PATH."/images/torg/medium")){ mkdir(PATH."/images/torg/medium");}

$cat = '';

   //создаем директории для категории и объекта
   if(!file_exists(PATH."/images/torg/small/{$cat}{$item_id}")){ mkdir(PATH."/images/torg/small/{$cat}{$item_id}");}
   if(!file_exists(PATH."/images/torg/medium/{$cat}{$item_id}")){ mkdir(PATH."/images/torg/medium/{$cat}{$item_id}");}
   
   
   $cfg = $inCore->loadComponentConfig('torg');
   $inCore->includeGraphics();
   //загрузка одного изображения
   if($type == 'one'){
     if (!isset($_FILES["{$formname}"]["name"]) || $_FILES["{$formname}"]["name"] == ''){return false;}

     $file = array();
     //проверяем расширение
     $path_parts             = pathinfo($_FILES["{$formname}"]["name"]);
     $ext                    = strtolower($path_parts['extension']);
     if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'png' && $ext != 'bmp') {
       $file['error'] = $_LANG['INADMISSIBLE_EXTENSION_OF_A_FILE'];

     }else{
     
        $file['filename'] = md5(rand().$_FILES["{$formname}"]["name"]).'.jpg';
        $tmp_name   = $_FILES["{$formname}"]["tmp_name"];
        if (@move_uploaded_file($tmp_name, PATH."/images/torg/{$file['filename']}")){

            @img_resize(PATH."/images/torg/{$file['filename']}", PATH."/images/torg/small/{$cat}{$item_id}/{$file['filename']}", $cfg['img_small_w'], $cfg['img_small_w'], $cfg['img_sqr']);
            @img_resize(PATH."/images/torg/{$file['filename']}", PATH."/images/torg/medium/{$cat}{$item_id}/{$file['filename']}", $cfg['img_big_w'], $cfg['img_big_w'], $cfg['img_sqr']);

            @unlink(PATH."/images/torg/{$file['filename']}");
            @chmod(PATH."/images/torg/small/{$cat}{$item_id}/{$file['filename']}", 0755);
            @chmod(PATH."/images/torg/medium/{$cat}{$item_id}/{$file['filename']}", 0755);

            $file['name'] =  $_FILES["{$formname}"]["name"];
        }
    }

    if(isset($_FILES["{$formname}"]["error"])){
      $file['error'] = $_FILES["{$formname}"]["error"];
    }


  }
  //мультизагрузка
  if($type == 'multi'){

     if (!isset($_FILES["{$formname}"]["name"][0]) || $_FILES["{$formname}"]["name"][0] ==''){return false;}
     $one_file =array();
     $files = array();
     $count = sizeof($_FILES["{$formname}"]["name"]);
     
     for( $i=0; $i<= $count; $i++){
       //проверяем расширение
       $path_parts             = pathinfo($_FILES["{$formname}"]["name"][$i]);
       $ext                    = strtolower($path_parts['extension']);
       if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'png' && $ext != 'bmp') {
          $one_file['error'] = $_LANG['INADMISSIBLE_EXTENSION_OF_A_FILE'];

       }else{

          $one_file['filename'] = md5(rand().$_FILES["{$formname}"]["name"][$i]).'.jpg';
          $tmp_name   = $_FILES["{$formname}"]["tmp_name"][$i];
          if (@move_uploaded_file($tmp_name, PATH."/images/torg/{$one_file['filename']}")){

              @img_resize(PATH."/images/torg/{$one_file['filename']}", PATH."/images/torg/small/{$cat}{$item_id}/{$one_file['filename']}", $cfg['img_small_w'], $cfg['img_small_w'], $cfg['img_sqr']);
              @img_resize(PATH."/images/torg/{$one_file['filename']}", PATH."/images/torg/medium/{$cat}{$item_id}/{$one_file['filename']}", $cfg['img_big_w'], $cfg['img_big_w'], $cfg['img_sqr']);

              @unlink(PATH."/images/torg/{$one_file['filename']}");
              @chmod(PATH."/images/torg/small/{$cat}{$item_id}/{$one_file['filename']}", 0755);
              @chmod(PATH."/images/torg/medium/{$cat}{$item_id}/{$one_file['filename']}", 0755);

              $one_file['name'] =  $_FILES["{$formname}"]["name"][$i];
          }
      }

      if(isset($_FILES["{$formname}"]["error"][$i])){
         $one_file['error'] = $_FILES["{$formname}"]["error"][$i];
      }

      $files[] = $one_file;

    }
  }

  if($file || $files){
     return $file ? $file : $files;

  }else{
    return false;
  }
}

function getImages($item_id){

  if(!file_exists(PATH."/images/torg/small/{$item_id}")){return false;}

  $files = array();
  $d = @opendir(PATH."/images/torg/small/{$item_id}");
  if(!$d){return false;}
  while(($filename=readdir($d)) !== false){
      if($filename == '.' || $filename == '..'){continue;}
      if(preg_match('/\.jpg$/is', $filename) == 0){continue;}
      $files[] =  $filename;
  }
  closedir($d);
  
  return $files ? $files : false;
}



?>
