<?
if ($level == 0){
  die(__('Только для зарегистрированных пользователей'));
}

if (isset($ID) && $level == 4 && !isset($_GET['admin'])) {
  $ank = $sql -> fetch("SELECT * FROM `users` WHERE `id` = '$ID' LIMIT 1");
}

if (!isset($ank['id']) && isset($user) || $level < 3) {
  $ank = $user;
}

$ank['wmr'] = round($ank['wmr'], 2);

if ($level == 4 && isset($_GET['act']) && isset($_GET['pays'])) {
  die('111');
  $act = (int) $_GET['act'];
  $pays = (int) $_GET['pays'];
  $wmr = $sql -> fetch("SELECT * FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `id` = '$pays' AND `out_time` = '0'");
  
  if ($wmr['out_wmr'] == '1') {
      $err[] = __('Сделка уже завершена');
  }
  
  if (!isset($err)) {
      if ($act == 1) {
             
          /**
          * Отчисление реферальских
          */
          
          $referals = $sql->select("SELECT `shop_pays`.`wmr`, `shop_pays`.`id`, `referals`.`id_user` AS `user`, `referals`.`id_referal` AS `referal` FROM `shop_pays` LEFT JOIN `referals` ON `referals`.`id_referal` = `shop_pays`.`id_author` OR `referals`.`id_referal` = `shop_pays`.`id_user` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `out_time` = '0' AND `id` = '$wmr[id]' AND `referals`.`active` = '1'");
          
          if (is_array($referals)) {
            $arrayResult = prepare_ref($referals, 'id');
            send_ref($referals);
          }
          

          $out = round($wmr['wmr'] - ($wmr['wmr'] / 100 * $system['pct_pays']), 2);
          $sql -> update("UPDATE `shop_pays` SET `pays` = '1', `out_time` = '$time', `out_wmr` = '1', `ok` = '3' WHERE `id` = '$wmr[id]'");
          $sql -> update("UPDATE `users` SET `wmr` = `wmr` + '$out' WHERE `id` = '$ank[id]' LIMIT 1");
          $ank['wmr'] = $ank['wmr'] + $out;  
          $_SESSION['message'] = __('Сделка успешно завершена досрочно');
        } elseif ($act == 2) {
          $out = round($wmr['wmr'], 2);
          $sql -> update("UPDATE `shop_pays` SET `pays` = '0', `time_pays` = '0', `out_time` = '0', `out_wmr` = '0', `ok` = '0', `wmr` = '0', `wmid` = '0', `purse` = '0'  WHERE `id` = '$wmr[id]'");
          
          $sql -> update("UPDATE `users` SET `wmr` = `wmr` + '$out' WHERE `id` = '$wmr[id_user]' LIMIT 1");
          
          // Обновление информации о товаре
          $sql -> update("UPDATE `shop_goods` SET `time_pays` = '0', `count_pays` = `count_pays` - '1', `rating` = `rating` - '1' WHERE `id` = '$wmr[id_goods]' LIMIT 1");
          $sql -> update("UPDATE `users` SET `rating` = `rating` - '1' WHERE `id` = '$wmr[id_author]' LIMIT 1");
          
          if ($user['id'] != $system['admin_id']) {
              journal($system['admin_id'], 'other', 'Пользователю ' . login($wmr['id_user'], 0) . " возвращены средства в размере [b]$out wmr[/b], за купленный товар [url=/goods/" . $wmr['id_goods'] . "]" . $wmr['name'] . "[/url]\r\nСделку отменил $user[login]");
          }
          journal($wmr['id_user'], 'goods', "Средства за покупку товара [url=/goods/" . $wmr['id_goods'] . "]" . $wmr['name'] . "[/url] были возвращены на личный счет.\n\rЧтобы узнать причину возврата, вы можете создать тикет в [url=/?func=support]Службе поддержки[/url]");
          journal($wmr['id_author'], 'goods', "Средства за продажу вашего товара [url=/goods/" . $wmr['id_goods'] . "]" . $wmr['name'] . "[/url]  были возвращены покупателю [url=/?func=user.profile&id=" . $wmr['id_user'] . "]" . login($wmr['id_user'], 0) . "[/url] на его личный счет.\n\rЧтобы узнать причину возврата, вы можете создать тикет в [url=/?func=support]Службе поддержки[/url]");
          $msglog = "Возврат средств за купленный товар [url=/goods/" . $wmr['id_goods'] . "]" . $wmr['name'] . "[/url]";
    	  $sql -> insert("INSERT INTO `billing_log` (`time`, `type`, `id_user`, `coins`, `msg`) VALUES ('$time', 'return', '$wmr[id_user]', '" . $out . "', '$msglog')");

          /*sms оповещение*/
$TelSms = $sql -> fetch("SELECT * FROM `users` WHERE `id` = '" . $wmr['id_author'] . "' AND `date_last` < '". time() ."' LIMIT 1");
if ($TelSms['MyTelefonOk'] == 1 && $TelSms['tel_vozrat']== 1 && $TelSms['date_last'] < time()-600 && $TelSms['wmr'] >= 1)
{

    if ($sql -> select("SELECT * FROM `smsantiflud` WHERE `id_user` = '".$TelSms['id']."' AND `mod` = 'vozrat'") == 0)
    {
    include_once FUNC.'smsc_api.php';
    $r = send_sms($TelSms['MyTelefon'], "Возврат денег за проданный товар 4i4i.Ru");

    if ($r[1] > 0)
        {
					
        $sql -> update("UPDATE `users` SET `wmr` = `wmr` - '1' WHERE `id` = '".$TelSms['id']."' LIMIT 1");
		$BySMS = "Списание за смс оповещение о возврате денег на мобильный телефон.";
        $sql -> insert("INSERT INTO `billing_log` (`time`, `type`, `id_user`, `coins`, `msg`) VALUES ('".time()."', 'Mysms', '$TelSms[id]', '-1', '$BySMS')");
		$sql -> insert("INSERT INTO `smsantiflud`(`time`, `id_user`, `mod`) VALUES('".time()."', '".$TelSms['id']."', 'vozrat')");
        }
    }
}
/*sms оповещение*/
          $_SESSION['message'] = __('Сделка отменена, деньги возвращены покупателю');
        }
  } 
}

if (isset($_GET['vivod']) && isset($_POST['wmr'])) {
    //die('222');

  $rub = round($_POST['wmr'] - ($_POST['wmr'] / 100 * $system['pct_out']), 2);
  $wmr2 = round($_POST['wmr'], 2);
  if ($rub < $system['min_out_money']) {
    $err[] = __('Минимальная сумма вывода') . ' ' . $system['min_out_money'] . ' wmr';
  } elseif ($rub > $ank['wmr']) {
    $err[] = __('У вас нет такой суммы');
  } elseif (!$ank['purse']) {
    $err[] = __('R кошелек имеет не верное значение');
  } elseif (!$system['wmpurse']) {
    $err[] = __('Не подключен WM кошелек магазина');
  } elseif ($rub <= 0) {
    $err[] = __('Укажите сумму для вывода');
  } elseif ($system['shop_money_open'] == 0) {
    $err[] = __('Вывод cредств временно приостановлен');
  }
  
  if (!isset($err)) {
    $sql -> insert("INSERT INTO `log_wmout` (`wmr`, `time`, `id_user`) VALUES ('$rub', '$time', '$ank[id]')");
    $idcash = $sql -> insert_id();
    
    // Подключение функций вывода
    require FUNC . 'incfunc.webmoney.php';
    
    $tranid = $idcash;
    $purse = $system['wmpurse'];
    $rpurse = $ank['purse'].'';
    $amount = $rub;
    $period = "0";
    $pcode = "";
    //$desc = "Vyvod ".$wmr2." wmr | 4i4i.Ru | ".$ank['login']."";
	$desc = "4i4i.Ru - вывод средств ".$wmr2." wmr пользователем ".$ank['login']."";
	$desc = iconv('UTF-8', 'CP1251', ' '.$desc.' ');
    $wminvid = "0";
    $onlyauth = "1";
    
    $result = _WMXML2($tranid, $purse, $rpurse, $amount, $period, $pcode, $desc, $wminvid, $onlyauth);
    
    if ($result['retval'] == '0') {
      journal($system['admin_id'], 'other', login($ank['id'], 0) . " вывел средства в размере [b]$rub wmr[/b] (код запроса: $result[retval])");
      
      $msglog = "Вывод средств на расчетный кошелек: $rpurse";
    	$sql -> insert("INSERT INTO `billing_log` (`time`, `type`, `id_user`, `coins`, `msg`) VALUES ('$time', 'vivod', '$ank[id]', '-" . $rub . "', '$msglog')");
      
      $sql -> update("UPDATE `log_wmout` SET `end` = '1' WHERE `id` = '$idcash'");
      $sql -> update("UPDATE `users` SET `wmr` = `wmr` - '$rub' WHERE `id` = '$ank[id]'");
      $ank['wmr'] = ($ank['wmr'] - $rub);
      $messages[] = __('Вывод средств успешно завершен');
    } else {
      journal($system['admin_id'], 'other', login($ank['id'], 0) . " не смог вывести средства [b]$rub wmr[/b], (код ошибки: $result[retval])");
      $err[] = __('Ошибка транзакции') . ': (' . __('код ошибки') . ' ' . $result['retval'] . ')';
    }
  }
}

if ($sql -> selectCount("SELECT COUNT(*) FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '1' AND `out_time` = '0'") > 0) {

  /**
  * Отчисление реферальских
  */
  $referals = $sql->select("SELECT `shop_pays`.`wmr`, `shop_pays`.`id`, `referals`.`id_user` AS `user`, `referals`.`id_referal` AS `referal` FROM `shop_pays` LEFT JOIN `referals` ON `referals`.`id_referal` = `shop_pays`.`id_author` OR `referals`.`id_referal` = `shop_pays`.`id_user` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '1' AND `out_time` = '0' AND `referals`.`active` = '1'");
  
  if (is_array($referals)) {
    $arrayResult = prepare_ref($referals, 'id');
    send_ref($referals);
  }

  $wmr = $sql -> fetch("SELECT SUM(wmr) AS wmr FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '1' AND `out_time` = '0'");
  $out = round($wmr['wmr'] - ($wmr['wmr'] / 100 * $system['pct_pays']), 2);
  $sql -> update("UPDATE `shop_pays` SET `pays` = '1', `out_time` = '$time', `out_wmr` = '1', `ok` = '3' WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '1' AND `out_time` = '0'");
  $sql -> update("UPDATE `users` SET `wmr` = `wmr` + '$out' WHERE `id` = '$ank[id]' LIMIT 1");
  $ank['wmr'] = $ank['wmr'] + $out;
}
/*
if ($sql -> selectCount("SELECT COUNT(*) FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 259200) ."'") > 0) {
  $wmr = $sql -> fetch("SELECT SUM(wmr) AS wmr FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 259200) ."'");
  $out = round($wmr['wmr'] - ($wmr['wmr'] / 100 * $system['pct_pays']), 2);
  $sql -> update("UPDATE `shop_pays` SET `pays` = '1', `out_time` = '$time', `out_wmr` = '1', `ok` = '3' WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 259200) ."'");
  $sql -> update("UPDATE `users` SET `wmr` = `wmr` + '$out' WHERE `id` = '$ank[id]' LIMIT 1");
  $ank['wmr'] = $ank['wmr'] + $out;
}
*/
/*Зачисление денег для Юзера и VIP */
if($ank['rating']>=0 && $ank['rating']<=50){
if ($sql -> selectCount("SELECT COUNT(*) FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 259200) ."' AND `out_wmr` != '2'") > 0) {

  /**
  * Отчисление реферальских
  */
  $referals = $sql->select("SELECT `shop_pays`.`wmr`, `shop_pays`.`id`, `referals`.`id_user` AS `user`, `referals`.`id_referal` AS `referal` FROM `shop_pays` LEFT JOIN `referals` ON `referals`.`id_referal` = `shop_pays`.`id_author` OR `referals`.`id_referal` = `shop_pays`.`id_user` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 259200) ."' AND `referals`.`active` = '1'");
  
  if (is_array($referals)) {
    $arrayResult = prepare_ref($referals, 'id');
    send_ref($referals);
  }

  $wmr = $sql -> fetch("SELECT SUM(wmr) AS wmr FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 259200) ."'");
  $out = round($wmr['wmr'] - ($wmr['wmr'] / 100 * $system['pct_pays']), 2);
  $sql -> update("UPDATE `shop_pays` SET `pays` = '1', `out_time` = '$time', `out_wmr` = '1', `ok` = '3' WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 259200) ."'");
  $sql -> update("UPDATE `users` SET `wmr` = `wmr` + '$out' WHERE `id` = '$ank[id]' LIMIT 1");
  $ank['wmr'] = $ank['wmr'] + $out;
}}
/*Зачисления денег для PRO*/
if($ank['rating']>=51 && $ank['rating']<=100){
if ($sql -> selectCount("SELECT COUNT(*) FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 172800) ."' AND `out_wmr` != '2'") > 0) {
  
    /**
  * Отчисление реферальских
  */
  $referals = $sql->select("SELECT `shop_pays`.`wmr`, `shop_pays`.`id`, `referals`.`id_user` AS `user`, `referals`.`id_referal` AS `referal` FROM `shop_pays` LEFT JOIN `referals` ON `referals`.`id_referal` = `shop_pays`.`id_author` OR `referals`.`id_referal` = `shop_pays`.`id_user` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 172800) ."' AND `referals`.`active` = '1'");
  
  if (is_array($referals)) {
    $arrayResult = prepare_ref($referals, 'id');
    send_ref($referals);
  }
  
  $wmr = $sql -> fetch("SELECT SUM(wmr) AS wmr FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 172800) ."'");
  $out = round($wmr['wmr'] - ($wmr['wmr'] / 100 * $system['pct_pays']), 2);
  $sql -> update("UPDATE `shop_pays` SET `pays` = '1', `out_time` = '$time', `out_wmr` = '1', `ok` = '3' WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 172800) ."'");
  $sql -> update("UPDATE `users` SET `wmr` = `wmr` + '$out' WHERE `id` = '$ank[id]' LIMIT 1");
  $ank['wmr'] = $ank['wmr'] + $out;
}}
/*Зачисления денег для MASTERA*/
if($ank['rating']>=101 && $ank['rating']<=99999999999){
if ($sql -> selectCount("SELECT COUNT(*) FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 86400) ."' AND `out_wmr` != '2'") > 0) {
  
  /**
  * Отчисление реферальских
  */
  $referals = $sql->select("SELECT `shop_pays`.`wmr`, `shop_pays`.`id`, `referals`.`id_user` AS `user`, `referals`.`id_referal` AS `referal` FROM `shop_pays` LEFT JOIN `referals` ON `referals`.`id_referal` = `shop_pays`.`id_author` OR `referals`.`id_referal` = `shop_pays`.`id_user` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 86400) ."' AND `referals`.`active` = '1'");
  
  if (is_array($referals)) {
    $arrayResult = prepare_ref($referals, 'id');
    send_ref($referals);
  }

  $wmr = $sql -> fetch("SELECT SUM(wmr) AS wmr FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 86400) ."'");
  $out = round($wmr['wmr'] - ($wmr['wmr'] / 100 * $system['pct_pays']), 2);
  $sql -> update("UPDATE `shop_pays` SET `pays` = '1', `out_time` = '$time', `out_wmr` = '1', `ok` = '3' WHERE `id_author` = '$ank[id]' AND `pays` = '1' AND `ok` = '0' AND `out_time` = '0' AND `time_pays` < '". ($time - 86400) ."'");
  $sql -> update("UPDATE `users` SET `wmr` = `wmr` + '$out' WHERE `id` = '$ank[id]' LIMIT 1");
  $ank['wmr'] = $ank['wmr'] + $out;
}}
/*Конец Кода зачисления денег*/
  
$system['title'] = __('Касса') . ' ' . ($ank['id'] != $user['id'] ? login($ank['id']) : '');
require SYS . 'header.php';

$k_post = $sql -> selectCount("SELECT COUNT(*) FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1'");

if ($k_post == 0) {
  ?>
  <div class="alert" style="margin: 2px;"><?= __('У вас еще не было продаж')?></div>
  <?
} else {
  $k_page = k_page($k_post, $system['page_str']);
  $page = page($k_page);
  $start =  $system['page_str'] * $page -  $system['page_str'];

  $array = $sql -> select("SELECT * FROM `shop_pays` WHERE `id_author` = '$ank[id]' AND `pays` = '1' ORDER BY `time_pays` DESC LIMIT $start, $system[page_str]");

  foreach ($array AS $post) {
    $goods = $sql -> fetch("SELECT * FROM `shop_goods` WHERE `id` = '$post[id_goods]' LIMIT 1");
    $num++;
    ?>
    <div class="<?= ($num % 2 ? "nav1" : "nav2")?>">
      <i class="icon-shopping-cart"></i> <a href="/goods/<?= $post['id_goods']?>"><?= text($post['name'])?></a><br />
      <?= __('Продажа')?>: <?= vremja($post['time_pays'])?><br />
      <?= __('Цена')?>: <?= $post['wmr']?> ₽<br />
      <?= __('К выплате')?>: <span style="color: green; font-weight: bold;"><?= round($post['wmr'] - ($post['wmr'] / 100 * $system['pct_pays']), 2)?> ₽</span><br />
      <?= __('Комиссия')?>: <?= round($post['wmr'] / 100 * $system['pct_pays'], 2)?> ₽<br />
      <?= __('Состояние')?>: 
      <?
      if ($post['out_wmr'] == 0) {
        ?><span style="color: blue;"><?= __('Временно не доступны к выводу')?></span><?
      } elseif ($post['out_wmr'] == 1) {
        ?><span style="color: green;"><?= __('Перечислены на личный счет')?></span><br /><?= __('Завершена')?>: <?= vremja($post['out_time'])?><?
      } elseif ($post['out_wmr'] == 2) {
        ?><span style="color: red;"><?= __('Временно заблокированы')?></span><?
      }
      ?>
      <br />
      <?= __('Покупатель')?>: <?= login($post['id_user'], 1)?><br />
      <? if ($post['wmid'] != 0) { ?>
      WMID: <a href="http://passport.webmoney.ru/asp/certview.asp?wmid=<?= $post['wmid']?>"><?= $post['wmid']?></a><br />
      <? } ?>
      <? if ($level == 4 && $post['out_wmr'] != 1) { ?>
        &raquo; <a href="/?func=user.cash&amp;id=<?= $ank['id']?>&amp;pays=<?= $post['id']?>&amp;page=<?= $page?>&amp;act=1"><?= __('Вывести продавцу')?></a><br />
        &raquo; <a href="/?func=user.cash&amp;id=<?= $ank['id']?>&amp;pays=<?= $post['id']?>&amp;page=<?= $page?>&amp;act=2"><?= __('Вернуть покупателю')?></a><br />
      <? } ?>
    </div>
    <?
  }

  if ($k_page > 1) { 
    str('?func=' . $func . '&amp;id=' . $ank['id'] . '&amp;', $k_page, $page);
  }  
}
//$ank['wmr'] = 10;
$cash = $sql -> fetch("SELECT SUM(wmr) AS wmr FROM `shop_pays` WHERE `id_author` = '" . $ank['id'] . "' AND `pays` = '1' AND (`out_wmr` = '0' OR `out_wmr` = '2')");
?>
<div class="nav2">
<?= __('Средств в системе')?>: <?= round($cash['wmr'] - ($cash['wmr'] / 100 * $system['pct_pays']), 2)?> ₽<br />
<?= __('Личный счет')?>: <?= round($ank['wmr'], 2)?> ₽<br />
<? if ($system['min_out_money'] > $ank['wmr'] || $ank['wmr'] == 0) { ?>
  <?= __('Недостаточное количество средств для вывода')?>
<? } else
	if ($ank['purse'] && $ank['wmid']) { 

?>
  
  <form action="/?func=<?= $func?>&amp;id=<?= $ank['id']?>&amp;vivod" method="POST">
  <?= __('Введите сумму для вывода')?>.<br />
  <?= __('Она не должна превышать суммы на вашем счете и быть не менее')?> <?= round($system['min_out_money'], 2)?> wmr.<br />
  <?= __('Сумма доступная для снятия')?>: <span class="on"><?= round($ank['wmr'], 2)?> wmr</span><br />
  <input type="text" name="wmr" value="<?= round($ank['wmr'], 2)?>" /><br />
  <input type="submit" value="<?= __('Вывести')?>" class="btn" /> &raquo; <b><?= $ank['purse']?></b> (min: <?= $system['min_out_money']?> wmr)<br />
  </form>
   
 
  <style>
  .newbottom{
    font-weight: 700;
    color: #f7eded;
    background-color: #4a8bbf;
    border-radius: 4px;
    padding: 8px;
  }
  </style> 

	 <br/>
	  <a class="newbottom" href="/?func=output.cash">Вывод средств</a>
	 <br/> <br/>

  </div> <div class="nav2">
  <!--
  <div class="nav2">
  Доступен вывод средств на карту Сбербанка РФ через <a href="/?func=support">Тех.поддержку</a><br />
  Коммисия за вывод на карту Сбербанка составляет 2%<br />
  Минимальная сумма вывода на карту составляет 100 wmr
  -->
<? } else { ?>
  <?= __('Заполните WMID и WMR кошелек')?>
<? } ?>
</div>  
