<?
### Версия ПО (ДМ) 1.0.0.0 ( (c)2018 MISOFT Продукт защищен регистрацией патента и авторских прав! www.misoft.studio )
######################################################################################################################

define( 'ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] );

include_once ROOT_DIR . '/engine/config.php';

$id = ( int ) $_POST['shpa'];
$InvId = $_POST['InvId'];
$OutSum = $_POST['OutSum'];
$pwd2 = $config_site['robokassa_pw2']; /// Пароль №2
$SignatureValue = strtoupper( $_POST['SignatureValue'] );
$crc = strtoupper( md5( $OutSum . ':' . $InvId . ':' . $pwd2 . ':shpa=' . $id ) );

if ( $crc != $SignatureValue ) exit();

$get_sum_basket = mysql_fetch_array( mysql_query( "SELECT SUM(price) as sum FROM basket WHERE iduser = '" . $id . "' OR nouser_order = '" . $id . "' " ) );
    
    if ( $_POST['OutSum'] >= $get_sum_basket['sum'] ) {
        
		$get_basket = mysql_query( "SELECT * FROM basket WHERE iduser = '" . $id . "' AND nouser_order = '0'" );
        
		#Проверяем режим оплаты от авторизированного пользователя, в случае не успеха, переходив к проверки от не авторизированного
		if ( mysql_num_rows( $get_basket ) > 0 ) {
        
		  while ( $row_basket = mysql_fetch_array( $get_basket ) ) {
            switch ( $row_basket['type'] ) {
			  #Серфинг
			  case 0:
				mysql_query( "UPDATE dynlink SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 0, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				#Проверка, если площадка в серфинге Plus
				$serf_plus = mysql_query( "SELECT id FROM dynlink WHERE id = '" . $row_basket['ident'] . "' and plus = 1 LIMIT 1" );
				if ( mysql_num_rows( $serf_plus ) > 0 ) {
				  mysql_query( "INSERT INTO dynlink_plus SET iduser = '" . $id . "', date = '" . time() . "' + 172800" );
				}
				break;
			  #Контекстная реклама
			  case 1:
				mysql_query( "UPDATE klink SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 1, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				break;
			  #Тесты
			  case 2:
				mysql_query( "UPDATE tests SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 2, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				break;
			  #Баннеры 200 х 300
			  case 3:
				mysql_query( "UPDATE banners SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 3, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				break;
			  #Баннеры 468 х 60
			  case 4:
				mysql_query( "UPDATE banners SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 3, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				break;
			  #Задания
			  case 5:
				mysql_query( "UPDATE tasks SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 4, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				break;
			  #V.I.P задания
			  case 6:
				$pr_task = mysql_query( "SELECT id, viptime FROM tasks WHERE id = '" . $row_basket['ident'] . "' LIMIT 1" );
				if ( mysql_num_rows( $pr_task ) > 0 ) {
				  $pr_task_row = mysql_fetch_array( $pr_task );
				  if ( $pr_task_row['viptime'] >= time() ) {
					$time_vip = $row_basket['price'] * 86400;
					mysql_query( "UPDATE tasks SET viptime = viptime + '$time_vip' WHERE id = '" . $pr_task_row['id'] . "'" );
					mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $pr_task_row['id'] . "', price = '" . $row_basket['price'] . "', type = 4, date = '" . time() . "', h_text = 'Размещение задания <b>№" . $row_basket['ident'] . "</b> в V.I.P блоке', payopt = 5" );
				  } else {
					$time_vip = $row_basket['price'] * 86400 + time();
					mysql_query( "UPDATE tasks SET  vip = 1, viptime = '$time_vip' WHERE id = '" . $pr_task_row['id'] . "'" );
					mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $pr_task_row['id'] . "', price = '" . $row_basket['price'] . "', type = 4, date = '" . time() . "', h_text = 'Размещение задания <b>№" . $row_basket['ident'] . "</b> в V.I.P блоке', payopt = 5" );
				  }
				}
				break;
			  #Рекламный счет	
			  case 15:
				mysql_query( "UPDATE user SET adv_money = adv_money + '" . $row_basket['price'] . "'WHERE id = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $pr_task_row['id'] . "', price = '" . $row_basket['price'] . "', type = 100, date = '" . time() . "', h_text = 'Пополнение рекламного счета ', payopt = 5" );
				break;
			  #Ярмарка
			  case 14:
				$referalsINFO = mysql_fetch_assoc(mysql_query("SELECT id, referer, referer2 FROM user WHERE id = '" . $row_basket['ident'] . "'"));
				$imINFO = mysql_fetch_assoc(mysql_query("SELECT id, referer, autoback FROM user WHERE id = '" . $row_basket['iduser'] . "'"));
				$priceREFERAL = ($config['coefficient_fair'] * $row_basket['price']);
				$ThePercentageSystem = ($row_basket['price'] - $priceREFERAL);
				#Начисляем вознаграждение за продажу с вычетом проц. сист
				mysql_query("UPDATE user SET money = money + '" . $priceREFERAL . "', earnings_fair = earnings_fair + '" . $priceREFERAL . "' WHERE id = '" . $referalsINFO['referer'] . "'");
				#Переписываем рефералу которого продают нового реферала первого и второго уровней
				mysql_query("UPDATE user SET referer = '" . $row_basket['iduser'] . "', referer2 = '" . $imINFO['referer'] . "', toref = '0', toref2 = '0', autoback = '" . $imINFO['autoback'] . "', price = '0' WHERE id = '" . $row_basket['ident'] . "'");
				#Пишем в историю операций продавцу о том что его реферал продался
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $referalsINFO['referer'] . "', price = '" . $priceREFERAL . "', type = 14, date = '" . time() . "', h_text = 'Поздравляем ваш реферал <b>ID" . $row_basket['ident'] . "</b> продан на ярмарке (комиссия системы ".$ThePercentageSystem." ".$config['valutaname'].")', payopt = 51" );
				#Пишем событие в ленту пользователю
				$ref_info_fair_dev = mysql_fetch_assoc(mysql_query("SELECT username FROM user WHERE id = '" . $row_basket['ident'] . "'"));
				mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Ваш реферал (".$ref_info_fair_dev['username'].", id".$row_basket['ident'].") был продан на бирже, вы заработали ".$priceREFERAL." ".$config['valutaname']." Примите наши поздравления, так держать!', iduser = '" . $referalsINFO['referer'] . "' " );
				#Пишем в историю операций покупателю о том что он купил реферала
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $row_basket['iduser'] . "', price = '" . $row_basket['price'] . "', type = 14, date = '" . time() . "', h_text = 'Вы купили реферала <b>ID" . $row_basket['ident'] . "</b> на ярмарке', payopt = 5" );
				#Пишем в выручку суму прибили проекта от продажи
				mysql_query( "UPDATE viruchka SET money = money + '".$ThePercentageSystem."' WHERE ident = '15'" );
				break;
			  #Рекламная цепочка
			  case 18:
				mysql_query( "UPDATE chain SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 18, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				break;
			  #Статическая реклама
			  case 20:
				mysql_query( "UPDATE statlink SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 20, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 5" );
				break;
			  #Авто-серфинг
			  case 16:
				mysql_query( "UPDATE autodynlink SET balance = balance + '" . $row_basket['price'] . "' WHERE id = '" . $row_basket['ident'] . "' and iduser = '" . $id . "'" );
				mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $id . "', price = '" . $row_basket['price'] . "', type = 16, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['ident'] . "</b>', payopt = 8" );
				break;
			}
          }
        
          #Конкурс от админа
		  $get_act_user = mysql_fetch_array( mysql_query( "SELECT activate FROM user WHERE id = '" . $id . "'" ) );
          if($get_act_user['activate'] == 1) {
			$chKonkurs = mysql_query( "SELECT id, type FROM konkurs WHERE type = 0 LIMIT 1" );
			if ( mysql_num_rows( $chKonkurs ) > 0 ) {
			  $chKonkursRow = mysql_fetch_array( $chKonkurs );
			  $chKonkursTemp = mysql_query( "SELECT id FROM konkurs_temp WHERE iduser = '" . $id . "' and id_konkurs = '" . $chKonkursRow['id'] . "' and type = 0" );
			  if ( mysql_num_rows( $chKonkursTemp ) > 0 ) {
				mysql_query( "UPDATE konkurs_temp SET summ = summ + '" . $get_sum_basket['sum'] . "' WHERE iduser = '" . $id . "' and type = 0 LIMIT 1" );
			  } else {
				mysql_query( "INSERT INTO konkurs_temp SET id_konkurs = '" . $chKonkursRow['id'] . "', iduser = '" . $id . "', summ = '" . $get_sum_basket['sum'] . "', type = 0" );
			  }
			}
          }
        
          #Начисление рейтинга и вознаграждений
          if ( $get_sum_basket['sum'] <= 100 and $get_sum_basket['sum'] >= 5 ) {
            $get_reyting = 1;
            #$get_money = $get_sum_basket['sum'] * 0.1;
          } else
          if ( $get_sum_basket['sum'] <= 200 and $get_sum_basket['sum'] > 100 ) {
            $get_reyting = 10;
            #$get_money = $get_sum_basket['sum'] * 0.1;
          } else
          if ( $get_sum_basket['sum'] <= 300 and $get_sum_basket['sum'] > 200 ) {
            $get_reyting = 20;
            #$get_money = $get_sum_basket['sum'] * 0.1;
          } else
          if ( $get_sum_basket['sum'] <= 400 and $get_sum_basket['sum'] > 300 ) {
            $get_reyting = 30;
            #$get_money = $get_sum_basket['sum'] * 0.1;
          } else
          if ( $get_sum_basket['sum'] <= 500 and $get_sum_basket['sum'] > 400 ) {
            $get_reyting = 40;
            #$get_money = $get_sum_basket['sum'] * 0.1;
          } else
          if ( $get_sum_basket['sum'] > 500 ) {
            $get_reyting = 50;
            #$get_money = $get_sum_basket['sum'] * 0.1;
          } else {
            $get_reyting = 0;
            $get_money = 0;
          }
        
          $get_money = 0;
        
		  #Накопительная карта
          $savingscards = $get_sum_basket['sum'] / 100;
        
          mysql_query( "UPDATE user SET golos = golos + 1 WHERE id = '" . $id . "'" );
          mysql_query( "UPDATE user SET money = money + '" . $get_money . "', reyting = reyting + '" . $get_reyting . "', allpay = allpay + '" . $get_sum_basket['sum'] . "', savingscards = savingscards + $savingscards  WHERE id = '" . $id . "'" );
          mysql_query( "DELETE FROM basket WHERE iduser = '" . $id . "'" );
    
	    } else {
			  
		  $get_basket = mysql_query( "SELECT * FROM basket WHERE iduser = '0' AND nouser_order = '" . $id . "'" );
		  
		  #Проверяем режим оплаты от не-авторизированного пользователя
		  if ( mysql_num_rows( $get_basket ) > 0 ) {
			while ( $row_basket = mysql_fetch_array( $get_basket ) ) {
			  switch ( $row_basket['type'] ) {
				#Серфинг
				case 0:
				  mysql_query( "UPDATE dynlink SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 0, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b>', payopt = 5" );
				  break;
				#Контекстная реклама
				case 1:
				  mysql_query( "UPDATE klink SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 1, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b>', payopt = 5" );
				  break;
				#Тесты
				case 2:
				  mysql_query( "UPDATE tests SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 2, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b>', payopt = 5" );
				  break;
				#Баннеры 200 х 300
				case 3:
				  mysql_query( "UPDATE banners SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 3, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b> ', payopt = 5" );
				  break;
				#Баннеры 468 х 60
				case 4:
				  mysql_query( "UPDATE banners SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 3, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b>', payopt = 5" );
				  break;
				#Рекламная цепочка
				case 18:
				  mysql_query( "UPDATE chain SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 18, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b>', payopt = 5" );
				  break;
				#Статическая реклама
				case 20:
				  mysql_query( "UPDATE statlink SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 20, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b>', payopt = 5" );
				  break;
				#Авто-серфинг
				case 16:
				  mysql_query( "UPDATE autodynlink SET balance = balance + '" . $row_basket['price'] . "', paused = '1' WHERE nouser_order = '" . $row_basket['nouser_order'] . "' and nouser = '1'" );
				  mysql_query( "INSERT INTO history_reklama_pay SET price = '" . $row_basket['price'] . "', type = 16, date = '" . time() . "', h_text = 'Пополнение рекламной площадки <b>№" . $row_basket['nouser_order'] . "</b>', payopt = 5" );
				  break;
			  }
			}
			mysql_query( "DELETE FROM basket WHERE iduser = '0' AND nouser_order = '" . $id . "'" );
		  }
		}
	
	}

?>