<?php

/*
* @package BANANA WARS
* @copyright: (c) 2017 G.P. aka Mvcshka (mvcshka@yandex.ru)
* @license: GNU General Public License version 2; see LICENSE.txt
* @files: /process/vivod.php
*
*/


session_start();
header('Content-type: application/json');
Header("Content-Type: text/html;charset=UTF-8");
if($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) { exit();}
include($_SERVER['DOCUMENT_ROOT'].'/lib/connect.php');
include($_SERVER['DOCUMENT_ROOT'].'/lib/func.php');
include($_SERVER['DOCUMENT_ROOT'].'/lib/CofigFarm.php');
include($_SERVER['DOCUMENT_ROOT'].'/lib/cpayeer.php');

if(isset($_POST['cash']))
{
	$var = clean($_POST['cash']);
	$summa = validefloat($var);
	
	if($summa !== false)
	{
		$MoneyUser = GetUser("MoneyOut", $_SESSION['id']);
		$MoneyUserEnter = GetUser("MoneyEnter", $_SESSION['id']);
		if($MoneyUserEnter >= 0)
		{
			if($summa >= 1)
			{
				if(GetUser("Purse", $_SESSION['id']) != '')
				{
					if(($summa * 100) <= $MoneyUser)
					{
						$accountNumber = $PurseAPIPayeer; 
						$apiId = $idAPIPayeer;
						$apiKey = $SecretKeyAPIPayeer;
						$payeer = new CPayeer($accountNumber, $apiId, $apiKey);
						if ($payeer->isAuth())
						{
							$arTransfer = $payeer->transfer(array(
								'curIn' => 'RUB',
								'sum' => $summa,
								'curOut' => 'RUB',
								'to' => GetUser("Purse", $_SESSION['id']),
								'comment' => 'Выплата с '.$_SERVER['HTTP_HOST'],
								
							));
							if (empty($arTransfer['errors']))
							{
								$q = $mysql->prepare("UPDATE db_users SET MoneyOut = MoneyOut - ?, MoneyVivod = MoneyVivod + ? WHERE Uid = ?");
								$q->execute(array(($summa * 100), $summa, $_SESSION['id']));
								$w = $mysql->prepare("INSERT INTO db_vivod SET Login = ?, UserId = ?, DateAdd = ?, SummaRub = ?, SummaGold = ?, `Purse` = ?, Status = ?");
								$w->execute(array($_SESSION['login'], $_SESSION['id'], time(), $summa, intval($summa * 100), GetUser("Purse", $_SESSION['id']), '1'));
								
								
								$tmp = 'Вывод средств: '.$summa.' руб. 
								<img src="/images/icons/money_dark.jpg"/><span class="title fs14">- '.intval($summa * 100).'</span>';
								$ggq = $mysql->prepare("INSERT INTO db_log SET UserId = ?, DateAdd = ?, `Text` = ?, MoneyIn = ?, MoneyOut = ?");
								$ggq->execute(array($_SESSION['id'], time(), $tmp, GetUser("MoneyIn", $_SESSION['id']), GetUser("MoneyOut", $_SESSION['id'])));
								
								
								echo json_encode($result = array("error" => "Выплачено!", "fillForm .button" => "Вывести")); exit;
							}
							else
							{
								echo json_encode($result = array("error" => "Не удалось выплатить", "fillForm .button" => "Вывести")); exit;	
							}
						}
						else
						{
							echo json_encode($result = array("error" => "Ошибка платежной системы! Попробуйте позже!", "fillForm .button" => "Вывести")); exit;
						}
					}
					else
					{
						echo json_encode($result = array("error" => "Не достаточно средств на балансе", "fillForm .button" => "Вывести")); exit;
					}
				}
				else
				{
					echo json_encode($result = array("error" => "Укажите кошелек в профиле", "fillForm .button" => "Вывести")); exit;
				}
			}
			else
			{
				echo json_encode($result = array("error" => "Минимум для выплаты 1 руб.", "fillForm .button" => "Вывести")); exit;
			}
		}
		else
		{
			echo json_encode($result = array("error" => "Для активации выплат необходимо пополнить свой счёт на 10 руб.", "fillForm .button" => "Вывести")); exit;
		}
	}
	else
	{
		echo json_encode($result = array("error" => "Не верная сумма", "fillForm .button" => "Вывести")); exit;
	}
}
?>