<?php
include "cfg.php";
include "ini.php";

$cid	= cfgSET('cfgPEsid');
$m_key	= cfgSET('cfgPEkey');

if(isset($_POST["m_operation_id"]) && isset($_POST["m_sign"])) {

	$arHash = array($_POST['m_operation_id'],
			$_POST['m_operation_ps'],
			$_POST['m_operation_date'],
			$_POST['m_operation_pay_date'],
			$_POST['m_shop'],
			$_POST['m_orderid'],
			$_POST['m_amount'],
			$_POST['m_curr'],
			$_POST['m_desc'],
			$_POST['m_status'],
			$m_key);

	$sign_hash = strtoupper(hash('sha256', implode(":", $arHash)));

	if($_POST["m_sign"] == $sign_hash && $_POST['m_status'] == "success") {
		$depo=$_POST['m_amount'];
		$user = $_POST['m_orderid'];
		$sum = $depo;
			$get_info	= mysql_query("SELECT * FROM users WHERE id = ".intval($_POST['m_orderid'])."  LIMIT 1");
			$row		= mysql_fetch_array($get_info);

			$date = date("d.m.Y");

			
				$lastdate = time();
				if(cfgSET('datestart') <= time()) {
				$nextdate = $lastdate + 3600 ;}else{
					$nextdate = cfgSET('datestart') + 3600;
				}
				$sql = "INSERT INTO `deposits` (username, user_id, date, plan, sum, paysys, lastdate, nextdate)
									VALUES ('".$row['login']."', '".intval($_POST['m_orderid'])."', ".time().", '1', ".$depo.", 'Payeer USD', ".$lastdate.", ".$nextdate.")";
				mysql_query($sql);
				
    			
			//реферальные начисления////
	$get_user = mysql_query( 'SELECT * FROM users WHERE id = \'' . $user . '\' LIMIT 1' );
	$row = mysql_fetch_array( $get_user );
	$uref = $row['ref'];
		// Начисляем нашим "любимым" рефералам
			if($uref) {

				// Подсчитываем кол-во уровней
				$countlvl = mysql_num_rows(mysql_query("SELECT * FROM reflevels"));

				if($countlvl) {
					$i		= 0;
					$uid	= $row['id'];;
					$query	= "SELECT * FROM reflevels ORDER BY id ASC";
					$result	= mysql_query($query);
					while($row = mysql_fetch_array($result)) {
						if($i < $countlvl) {
							$lvlperc = $row['sum'];		// Процент уровня
							$ps		 = sprintf("%01.2f", $sum / 100 * $lvlperc); // Сумма рефских

							if($uref) {

								

								mysql_query('UPDATE users SET pm_balance = pm_balance + '.$ps.', reftop = reftop + '.$ps.' WHERE id = '.$uref.' LIMIT 1');

								mysql_query('UPDATE users SET ref_money = ref_money + '.$ps.' WHERE id = '.$uid.' LIMIT 1');
								
								// Получаем данные следующего пользователя

								$get_ref	= mysql_query("SELECT id, ref FROM users WHERE id = ".intval($uref)." LIMIT 1");
								$rowref		= mysql_fetch_array($get_ref);
								$uref		= $rowref['ref'];
								$uid		= $rowref['id'];

							}

						}
						$i++;
					}
				}

			}
			// Закончили с рефералами
			
			
		echo $_POST['m_orderid']."|success";
		exit();

	} else {
		echo $_POST['m_orderid']."|error";
	}
}
?>