<?php
require("lib/config.php");
require_once 'vendor/eway/eway-rapid-php/include_eway.php';
$data  = $_REQUEST;
$sql = "SELECT * FROM customers where email = '".$_REQUEST['username']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc()) 
	{
        $customer[] = $row;
		$sql = "SELECT * FROM `customer_details` where `cid` = '".$row["id"]."'"; 
		$result = $conn->query($sql);
		if ($result->num_rows > 0) 
		{
			while($row_details = $result->fetch_assoc()) 
			{
				$cust_detail[] = $row_details;
			}
		}
		$sql = "SELECT * FROM `customer_tokens`  where `cid` = '".$row["id"]."'"; 
		$result = $conn->query($sql);
		if ($result->num_rows > 0) 
		{
			while($row_token = $result->fetch_assoc()) 
			{
				$cust_token[] = $row_token;
			}
		}
		$sql = "SELECT * FROM `booking` where email = '".$_REQUEST['username']."'";
		$result = $conn->query($sql);
		if ($result->num_rows > 0) 
		{
			while($row_booking = $result->fetch_assoc()) 
			{
				$cust_booking[] = $row_booking;
			}
		}
		
    }
}
$name = $customer[0]["name"];
$name_split = explode(" ",$name);
$fname = $name_split[0];
$lname = $name_split[1];
$cus = $customer[0]["name"];
$mob = $customer[0]["mobile"];

		$Res["data"]["id"] = $customer[0]["id"];
		$Res["data"]["name"] = $customer[0]["name"];
		$Res["data"]["mobile"] = $customer[0]["mobile"];
		$Res["data"]["email"] = $customer[0]["email"];
		$Res["data"]["address"] = $cust_detail[0]["address"];
		$Res["data"]["addr_lat"] = $cust_detail[0]["addr_lat"];
		$Res["data"]["addr_long"] = $cust_detail[0]["addr_long"];
		$Res["data"]["pickup_addr"] = $cust_booking[0]["pickup_addr"];
		$Res["data"]["pickup_lat"] = $cust_booking[0]["pickup_lat"];
		$Res["data"]["pickup_long"] = $cust_booking[0]["pickup_long"];
		$Res["data"]["pickoff_addr"] = $cust_booking[0]["pickoff_addr"];
		$Res["data"]["pickoff_lat"] = $cust_booking[0]["pickoff_lat"];
		$Res["data"]["pickoff_long"] = $cust_booking[0]["pickoff_long"];
		$Res["data"]["booking_date"] = $cust_booking[0]["booking_date"];
		$Res["data"]["booking_time"] = $cust_booking[0]["booking_time"];
		$Res["data"]["Access_token"] = $cust_token[0]["access_token_value"];
		$Res["data"]["show_message"] = "Thank you for submitting your booking. Please make sure the above details are correct. 
You will receive confirmation via SMS within 30 mins. 
When the driver is en route you will receive a tracking link via SMS with driver contact details and their ETA.
Please call 1300466365 if you need to make any changes at short notice."; 
	
	$client_key = '4T7y1vuKPkdhRYUQdH6msueW9hqV2wpcwnSk0Qwxkvwf7TjQn40qymPW7IJb66gUC1w1505cDMkj9IR82juQEnIp4/8nd0nDhwYDSDoqROtNBWmkqtqYmF6F4qVGMUq3HpJrY3y2kdSljCFfWzWc7LIEn4G5XY2IZAPgAO5+mhwvYrricmqwLhqzV4FBUII5AwTvJZl4awrdul4vLWkS73vJuW/XrXHseGK/nqB3oSRluZ1jKp2qDgVTwrXYEbx4rwwS42X2w0C9tLKywxf27WD2CCK8ftSeQBimVqFI0r6VuRXFVaOn6SQTOD9V/TsCfPk5Zh6/PWcfapyVKS+l1w==';

	$apiKey = '44DD7APNUxR8/4sDLhEVT11OS00fmBo4Haxj4ZGJGHvtLBP0rC/ayqNhbVu9tEJrjlJPJm';
	$apiPassword = 'y2b7QMpd';
	$apiEndpoint = \Eway\Rapid\Client::MODE_PRODUCTION;
	
	//$apiKey = '60CF3Ce97nRS1Z1Wp5m9kMmzHHEh8Rkuj31QCtVxjPWGYA9FymyqsK0Enm1P6mHJf0THbR';
	//$apiPassword = 'API-P4ss';
	//$apiEndpoint = \Eway\Rapid\Client::MODE_SANDBOX; // Use \Eway\Rapid\Client::MODE_PRODUCTION when you go live
	$client = \Eway\Rapid::createClient($apiKey, $apiPassword, $apiEndpoint);
	$transaction = [
			'Customer' => [
				'TokenCustomerID' =>$cust_token[0]["access_token_value"],
			],
			'Payment' => [
				'TotalAmount' => $_REQUEST["price"],
			],
			'TransactionType' => \Eway\Rapid\Enum\TransactionType::RECURRING,
		];

		$response = $client->createTransaction(\Eway\Rapid\Enum\ApiMethod::DIRECT, $transaction);
		
	if (isset($response->TransactionStatus) && $response->TransactionStatus) 
	{
    		$Res["transaction"]["transactionid"] = $response->TransactionID;
			$TransactionID = $response->TransactionID;
			$Res["transaction"]["AuthorisationCode"] = $response->AuthorisationCode;
			$authorisation_code =  $response->AuthorisationCode;
    		$Res["transaction"]["tokencustomerid"] = $response->Customer->TokenCustomerID;
    		$tokencustomerid = $response->Customer->TokenCustomerID;			
			$sql = "INSERT INTO `perthdes_new_pro_api`.`payments` (`id`, `transaction_id`, `authorisation_code`, `customer_name`, `customer_email`, `amount`, `token_id`, `created`, `modified`) VALUES (NULL, '".$TransactionID."', '".$authorisation_code."', '".$cus."', '".$_REQUEST['username']."', '".$_REQUEST['price']."', '".$tokencustomerid."' , NOW(), NOW())";
			if ($conn->query($sql) === TRUE) 
			{
				$Res['payment']["payment_id"] = $conn->insert_id;
				$Res["message"]["success"] = "payment success" ;

				
				$message = '<div style ="width:725; margin:0 auto;"><p>Hi,</p>
				<p>Thank you for your booking. Please check the details below for your booking, transection and location :</p>

				<p style = "font-weight:bold;";>Details:</p>
				<br>
				<table width="400" style="border:none;">
					<tr>
						<td >Type</td>
						<td>DD</td>
					</tr>
					<tr>
						<td>Date</td>
						<td>'.date('d-M-Y  H:i:s').'</td>
					</tr>
					<tr>
						<td>Transection Id</td>
						<td>'.$TransactionID.'</td>
					</tr>
					<tr>
						<td>Token Customer Id</td>
						<td>'.$tokencustomerid.'</td>
					</tr>
					<tr>
						<td>Name</td>
						<td>'.$cus.'</td>
					</tr>
					<tr>
						<td>Phone</td>
						<td>'.$mob.'</td>
					</tr>
					<tr>
						<td>Pick Up</td>
						<td>'.$cust_booking[0]["pickup_addr"].'</td>
					</tr>
					<tr>
						<td>To Drop</td>
						<td>'.$cust_booking[0]["pickoff_addr"].'</td>
					</tr>
					<tr>
						<td>Credit Card</td>
						<td>'.$cust_detail[0]["card_number"].'</td>
					</tr>
					<tr>
						<td>Pick up Location Dimenstions</td>
						<td>
						Longitude:'.$cust_booking[0]["pickup_long"].'
						latitude:'.$cust_booking[0]["pickup_lat"].'
						</td>
					</tr>
					<tr>
						<td>To drop Of Location Dimentions</td>
						<td>
						Longitude:'.$cust_booking[0]["pickoff_long"].'
						latitude:'.$cust_booking[0]["pickoff_lat"].'
						</td>
					</tr>
					<tr>
						<td>Booking fare</td>
						<td>
						'.$_REQUEST['price'].'
						</td>
					</tr>
				</table>
				</div>';
				$to = $_REQUEST['username'];
				$from = "booking@perthdesignateddrivers.com.au";
				$title = "Booking payment Details";
				send_mail($to, $from, $title, $message);
			}
	} 
	else 
	{
		$error = true;
    	if ($response->getErrors()) 
		{
        	foreach ($response->getErrors() as $error) 
			{
        	    $errormessage.= "Error: $error (".\Eway\Rapid::getMessage($error).")<br>\n";
       	 	}
    	} 
		else 
		{
        	$errormessage.= "Sorry, your payment was declined";
    	}
		
		$Res["message"]["errormessage"] = $errormessage; 
	}
	//echo "<pre>";
	//print_r($Res);
	//print_r($response);
	//echo "</pre>";
	echo json_encode(new ArrayObject($Res)); 
	
	function send_mail($to, $from, $title, $message)
	{
		$headers = "MIME-Version: 1.0 \r\n";
		$headers .= "From: $from \n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-type: text/html;charset=ISO-8859-1 \r\n";
		$headers .= "X-Priority: 3\r\n";
		$headers .= "X-Mailer: smail-PHP " . phpversion() . "\r\n";
		return mail($to, $title, $message, $headers);
	}
?>