<?php
//ini_set('display_errors', '1');
//error_reporting(E_ALL);

require_once 'eway-rapid-php-master/include_eway.php';

$client_key = '4T7y1vuKPkdhRYUQdH6msueW9hqV2wpcwnSk0Qwxkvwf7TjQn40qymPW7IJb66gUC1w1505cDMkj9IR82juQEnIp4/8nd0nDhwYDSDoqROtNBWmkqtqYmF6F4qVGMUq3HpJrY3y2kdSljCFfWzWc7LIEn4G5XY2IZAPgAO5+mhwvYrricmqwLhqzV4FBUII5AwTvJZl4awrdul4vLWkS73vJuW/XrXHseGK/nqB3oSRluZ1jKp2qDgVTwrXYEbx4rwwS42X2w0C9tLKywxf27WD2CCK8ftSeQBimVqFI0r6VuRXFVaOn6SQTOD9V/TsCfPk5Zh6/PWcfapyVKS+l1w==';

$apiKey = '44DD7APNUxR8/4sDLhEVT11OS00fmBo4Haxj4ZGJGHvtLBP0rC/ayqNhbVu9tEJrjlJPJm';
$apiPassword = 'y2b7QMpd';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Booking Submission</title>

    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="assets/picker/default.css"  crossorigin="anonymous">
    <link rel="stylesheet" href="assets/picker/date.theme.css"  crossorigin="anonymous">

    <link rel="stylesheet" href="assets/picker/default.time.css"  crossorigin="anonymous">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        #map {
            height:300px;
        }
        body{
            background-color: #d9d9d9;
        }

    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12 text-center">
        <?php
        $phone= $_POST['phone'];
        $dbhost = "localhost";
	    $dbuser = "perthdes_inquiri";
	    $dbpass = "@G&{)0*&Ts^V";
	    $dbname = "perthdes_inquiries";
	    $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
	    $qcon=mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

$query1 = "SELECT token FROM inquiries WHERE inquiry_mobile='".$phone."' ORDER BY token DESC LIMIT 0,1";
        $result = mysqli_query($conn, $query1);
        $row = mysqli_fetch_assoc($result);
        $tokencheck = $row['token'];
$success1 = $conn->query($query1);
 
	    if (!$success) {
    		$updatetoken = 0;
    		}
if( $tokencheck != ""){

    $tokencustomerid = $tokencheck;
    $updatetoken = 1;
}else{
    
    $updatetoken = 0;
    
}        
        
        
        $errormessage = '';

	$price= 1;
	

	if ($price < 1) {
		$errormessage.= "Invalid address.<br>\n";
		$error = true;
	}

	
	
		
	// Check if email has been entered and is valid
	// if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
	//	$errormessage.= "Please enter a valid email address<br>\n";
	//	$error = true;
	//}

	$apiEndpoint = \Eway\Rapid\Client::MODE_PRODUCTION; // Use \Eway\Rapid\Client::MODE_PRODUCTION when you go live
	$client = \Eway\Rapid::createClient($apiKey, $apiPassword, $apiEndpoint);

//create customer
$firstname = trim($_POST['First_Name']);
$lastname = trim($_POST['Last_Name']);
$fullname = "$firstname $lastname";

if($updatetoken == 0) {

$customer = [
    'Title' => 'Mr.',
    'FirstName' => $firstname,
    'LastName' => $lastname,
    'Country' => 'au',
    'Email' => trim($_POST['email']),
    'CardDetails' => [
        'Name' => $fullname,
        'Number' => $_POST['EWAY_CARDNUMBER'],
        'ExpiryMonth' => $_POST['EWAY_CARDEXPIRYMONTH'],
        'ExpiryYear' => $_POST['EWAY_CARDEXPIRYYEAR'],
        'CVN' => $_POST['EWAY_CARDCVN']
    ]
];

	/*echo '<pre>';
	print_r($customer);
	echo '</pre>';
	exit;*/
$response = $client->createCustomer(\Eway\Rapid\Enum\ApiMethod::DIRECT, $customer);
$tokencustomerid = $response->Customer->TokenCustomerID;
}

if($updatetoken == 1) {
$customer = [
    'Email' => trim($_POST['email']),
    'TokenCustomerID' => $tokencustomerid,
    'CardDetails' => [
        'Name' => $fullname,
        'Number' => $_POST['EWAY_CARDNUMBER'],
        'ExpiryMonth' => $_POST['EWAY_CARDEXPIRYMONTH'],
        'ExpiryYear' => $_POST['EWAY_CARDEXPIRYYEAR'],
        'CVN' => $_POST['EWAY_CARDCVN']
    ]
];

	/*echo '<pre>';
	print_r($customer);
	echo '</pre>';
	exit;*/
$response = $client->updateCustomer(\Eway\Rapid\Enum\ApiMethod::DIRECT, $customer);

}

	$transaction = [
    	'Customer' => [
                'Reference' => $_POST['hidden_ref'],
        	'CardDetails' => [
           	 	'Name' => $fullname,
            	 	'Number' => $_POST['EWAY_CARDNUMBER'],
            	 	'ExpiryMonth' => $_POST['EWAY_CARDEXPIRYMONTH'],
            	 	'ExpiryYear' => $_POST['EWAY_CARDEXPIRYYEAR'],
            	 	'CVN' => $_POST['EWAY_CARDCVN']
        	]
    	],
    	'Payment' => [
        	'TotalAmount' => $price,
    	],
    	'TransactionType' => \Eway\Rapid\Enum\TransactionType::PURCHASE,
    	'Capture' => false,
	];
	

	$response = $client->createTransaction(\Eway\Rapid\Enum\ApiMethod::DIRECT, $transaction);

	if (isset($response->TransactionStatus) && $response->TransactionStatus) {
    		$transactionid = $response->TransactionID;
    		$AuthorisationCode = $response->AuthorisationCode;
    		//$tokencustomerid = $response->Customer->TokenCustomerID;
	} 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";
    		}
	}

	

        if(!$error)
        {
            $email= $_POST['email'];
            $fullnameencode = $_POST['nameencode'];
            $pickup= $_POST['pickup'];
            $pickupencode = $_POST['pickupencode'];
            $dropoff= $_POST['dropoff'];
            $dropoffencode= $_POST['dropoffencode'];
            
            date_default_timezone_set("Australia/Perth");
            $date=$_POST['date'];
             $date24 = date("Y-m-d", strtotime($date));
            $time=$_POST['time'];
             $time24 = date("G:i", strtotime($time));
	    $timeUTC = date("c", strtotime("$date24 $time24"));
            
            
            $intphone = $_POST['intphone'];
	    $lat1= $_POST['lat1_value'];
	    $lng1= $_POST['lng1_value'];
	    $lat2= $_POST['lat2_value'];
	    $lng2= $_POST['lng2_value'];            
            $price= $_POST['onewayPrice'];
            $reference = $_POST['hidden_ref'];

$longUrl = "https://www.bookings.perthdesignateddrivers.com.au/payment/?token=$tokencustomerid&ref=$reference&amount=$price&name=$fullnameencode&pickup=$pickupencode&dropoff=$dropoffencode&type=DD"; 
$postData = array('longUrl' => $longUrl);
$jsonData = json_encode($postData);

$curlObj = curl_init();

curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyCq_JZBDbrE5qma5SgF06M2dVAqbiZBZ-o');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

$response = curl_exec($curlObj);

// Change the response json string to object
$json = json_decode($response);

curl_close($curlObj);

$shortLink = get_object_vars($json);
$paymentlink = $shortLink['id'];



$curlObj = curl_init();

curl_setopt($curlObj, CURLOPT_URL, 'https://api.fleeteng.com.au/v2/graph/role/jobs?access_token=9olkJkrIcttN8Zlh1lgAch70KFC_nJiIpUiCeaBMswbs');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, '[{"name": "DD ' . $fullname . '","contact": {"name": "' . $name . '","phone": "' . $intphone . '","email": "' . $email . '"},"tasks": [{"zone": {"name": "Pick Up","address": "' . $pickup . '","coords": {"lat": ' . $lat1 . ',"lon": ' . $lng1 . '},"radius": 100}},{"zone": {"name": "Destination","address": "' . $dropoff . '","coords": {"lat": ' . $lat2 . ',"lon": ' . $lng2 . '},"radius": 100}}],"attr": [{ "key": "deliverBy", "value": "' . $timeUTC . '" },{ "key": "Payment Link", "value": "' . $paymentlink . '" }]}]');

// ,


$response = curl_exec($curlObj);

$json = json_decode($response, true);



curl_close($curlObj);


$spatulalink = $json['items'][0]['tracking'];
$spatulaid = $json['items'][0]['id'];	    
	    
	    

            
            echo "<h3>Your booking has been successfully processed</h3>";
            echo "<h3>You will receive an SMS confirmation from the dispatch team within 30 mins (unless you have submitted after hours)</h3><br><h4>When your driver is en route you will receive an SMS with a tracking link and driver contact details. If you do not receive this SMS atleast 10 mins before your booking time please contact us on 1300466365</h4>";
            echo "<h5><table style='margin-left: auto; margin-right: auto;'>
            <tr><td style = 'text-align: left; padding: 5px;'>Name </td><td style = 'text-align: left; padding: 5px;'>$fullname</td></tr>
            <tr><td style = 'text-align: left; padding: 5px;'>Phone </td><td style = 'text-align: left; padding: 5px;'>$phone</td></tr>
            <tr><td style = 'text-align: left; padding: 5px;'>Email </td><td style = 'text-align: left; padding: 5px;'>$email</td></tr>
            <tr><td style = 'text-align: left; padding: 5px;'>Pick Up </td><td style = 'text-align: left; padding: 5px;'>$pickup</td></tr>
            <tr><td style = 'text-align: left; padding: 5px;'>Drop Off </td><td style = 'text-align: left; padding: 5px;'>$dropoff</td></tr>
            <tr><td style = 'text-align: left; padding: 5px;'>Date/Time </td><td style = 'text-align: left; padding: 5px;'>$date $time</td></tr>
            <tr><td style = 'text-align: left; padding: 5px;'>Quoted </td><td style = 'text-align: left; padding: 5px;'>$price</td></tr></table></h5>";
            
            
            
            $smsmessage = $_POST['smsmessage'];
            
	    $nameq = mysqli_real_escape_string($qcon, $fullname);
	    $pickupq = mysqli_real_escape_string($qcon, $pickup);
	    $dropoffq = mysqli_real_escape_string($qcon, $dropoff);

	    $query   = "INSERT into inquiries (inquiry_name, inquiry_mobile, inquiry_dropoff, inquiry_email, token, inquiry_created) VALUES ('" . $nameq . "','" . $phone . "','" . $dropoffq . "','" . $email . "','" . $tokencustomerid . "','" . date('Y-m-d H:i:s') . "') ON DUPLICATE KEY UPDATE inquiry_name='" . $nameq . "', inquiry_dropoff='" . $dropoffq . "', inquiry_email='" . $email . "', token='" . $tokencustomerid . "'";
	    $success = $conn->query($query);
 
	    if (!$success) {
    		die("Couldn't enter data: ".$conn->error);
    		}
    		
    	    $query   = "INSERT into jobs (id, reference, job_name, job_phone, job_email, job_pickup, job_dropoff, job_date, job_time, job_quote, date_added, spat_ref, spat_link) VALUES (NULL,'" . $reference . "','" . $nameq . "','" . $phone . "','" . $email . "','" . $pickupq . "','" . $dropoffq . "','" . $date . "','" . $time . "','" . $price . "','" . date('Y-m-d H:i:s') . "','" . $spatulaid . "','" . $spatulalink . "')";
	    $success = $conn->query($query);
 
	    if (!$success) {
    		die("Couldn't enter data: ".$conn->error);
    		}	
            $message= "Type DD<br>
 Date $date $time24<br>
 Transaction ID $transactionid        <br>
 Token Customer ID $tokencustomerid        <br>
 Name $fullname <br>
 Phone $phone <br>
 Pick Up $pickup<br>
 TO <br>
 Drop Off $dropoff <br>
 Quoted $price <br>
Credit Card Authorised <br>
Lat1 $lat1 <br>
Long1 $lng1 <br>
Lat2 $lat2 <br>
Long2 $lng2 <br>
Email $email <br>
Reference $reference<br>
SMS $smsmessage<br>
Namecode $fullnameencode <br>
Pickupcode $pickupencode <br>
Dropoffcode $dropoffencode";
$message_sql = "Type: DD <br>
Ref: $spatulaid <br> ";

send_mail('adh0zyak@robot.zapier.com','pdd@perthdesignateddrivers.com.au','New Order From'.$email ,$message_sql);

            send_mail('booking@perthdesignateddrivers.com.au','spatula@perthdesignateddrivers.com.au','New Order From
            '.$email ,$message); 
            // send_mail('sherifmesallam@gmail.com','admin@perthdesignateddrivers.com.au','New Order From '.$email ,$message);
        }
        else
        {
        
            
            
            
            $message= "Type DD<br>
 Date $date $time24<br>
 Transaction ID $transactionid        <br>
 Token Customer ID $tokencustomerid        <br>
 Name $name <br>
 Phone $phone <br>
 Pick Up $pickup<br>
 TO <br>
 Drop Off $dropoff <br>
 Quoted $price <br>
Credit Card Authorisation Failed <br>
Lat1 $lat1 <br>
Long1 $lng1 <br>
Lat2 $lat2 <br>
Long2 $lng2 <br>
Email $email <br>
Reference $reference";

            echo "<h3>Transaction has been declined</h3><br>\n";
            echo $errormessage."<br>\n";
            echo "<h4><a href='https://bookings.perthdesignateddrivers.com.au/eway/'> Refresh </a></h4>";
            send_mail('booking@perthdesignateddrivers.com.au','nospatula@perthdesignateddrivers.com.au','New Order [Failed Auth] From
            '.$email ,$message);
             
        }
        ?>
        </div>
    </div>
</div>
</body>
</html>

<?php
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);
}
?>