<?php
header('Content-type: text/html; charset=UTF-8');

if (file_exists("./external.php")) {
    include_once('./external.php');
} else {
    die(255);
}

if ( isset($_GET['paygateway']) && !empty($_GET['paygateway']) && isset($urlHost)) {
	$curl = curl_init();
	$paysystem = $_GET['paygateway'];
	curl_setopt($curl, CURLOPT_URL, "{$urlHost}/pay.php?paygateway={$paysystem}");
	curl_setopt($curl, CURLOPT_REFERER, 'https://mikbill.pro');
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);

	if (isset($_SERVER['HTTP_USER_AGENT'])){
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	}

	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_COOKIESESSION, true);
	curl_setopt($curl, CURLOPT_HEADER, 1);

	curl_setopt($curl, CURLOPT_HTTPHEADER, array(
		"X_FORWARDED_FOR:" . getRealIpAddr(),
		"X_FOWARDED_FOR:" . getRealIpAddr()
	));

	$data = getUserDataFromPOST();
	$data['amount'] = 100;
	if (isset($_POST['amount'])) {
          $data['amount'] = round($_POST['amount'], 2);
	} elseif (isset($_GET['amount'])) {
          $data['amount'] = round($_GET['amount'], 2);
        }
	
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

	$response = curl_exec($curl);

	$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
	$body = substr($response, $header_size);
	$errno = curl_errno($curl);

	if ($errno) {
		$body = json_encode(array("error" => $errno));
	}

	curl_close($curl);
	echo $body;
}

function getUserDataFromPOST()
{
    $user = array(
        'fio'   => '',
        'email' => '',
        'phone' => '',
    );

    # UID
    if (isset($_POST['uid'])) { $user['uid'] = intval($_POST['uid']);
    } elseif (isset($_GET['uid'])) { $user['uid'] = intval($_GET['uid']);
    } else { die('User not defined'); }

    # ФИО
    if (isset($_POST['fio'])) { $user['fio'] = $_POST['fio'];
    } elseif (isset($_GET['fio'])) { $user['fio'] = $_GET['fio']; }

    # e-mail
    if (isset($_POST['email'])) { $user['email'] = $_POST['email'];
    } elseif (isset($_GET['email'])) { $user['email'] = $_GET['email']; }

    # phone
    if (isset($_POST['phone'])) { $user['phone'] = $_POST['phone'];
    } elseif (isset($_GET['phone'])) { $user['phone'] = $_GET['phone']; }

    return $user;
}

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){ $ip=$_SERVER['HTTP_CLIENT_IP']; }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];}
    else { $ip=$_SERVER['REMOTE_ADDR']; }
    return $ip;
}

