<?php
require("lib/config.php");
require_once('braintree/braintree_init.php');
require_once 'braintree/lib/Braintree.php';
// =============== New customer user api ===================================
$data  = $_REQUEST;
$referal = false;
error_log(json_encode($data, true));
//echo "<pre>";
	//print_r($data);
//echo "<pre>";
$sql = "SELECT id FROM customers where email = '".$_REQUEST['email']."'";
$result = $conn->query($sql);

$headers = 'From: '.$_REQUEST["email"] . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    
$promo_code = "";
if(isset($_REQUEST['no_fam'])) {
 $no_pax = $_REQUEST['no_fam'];
 }
if(isset($_REQUEST['no_pax'])) {
$no_pax = $_REQUEST['no_pax'];
}
   
if ($result->num_rows > 0) 
 {
	$Res["mail"] = $_REQUEST["email"];
	$Res["message"] = "User already exist with this mail id";
	$Res["customer_status"] = "already exist";
	$Res["status"] = "error";
	
 }
 else 
 {
  if($_REQUEST['user_agree']=="1")
  {
  if(isset($_REQUEST['promo_code']) && $_REQUEST['promo_code'] != "") {
  	if(substr($_REQUEST['promo_code'], 0, 2) === "RF"){
  		$sql = "SELECT * FROM referrals where code = '".$_REQUEST['promo_code']."'";
	$result = $conn->query($sql);
	if ($result->num_rows > 0) {
		$promo_code = $_REQUEST['promo_code'];
		$promo_details = $result->fetch_assoc();
		$continue = 1;
		$referal = true;
		
		} else {
		error_log($conn->error);
		$continue = 0;
		$promo_code = "";
		
  	}
  	
  	} else {
  
  
  	$sql = "SELECT code FROM promo_codes where code = '".trim($_REQUEST['promo_code'])."'";
	$result = $conn->query($sql);
	if ($result->num_rows > 0) {
		$promo_code = $_REQUEST['promo_code'];
		$continue = 1;
		} else {
		error_log($conn->error);
		$continue = 0;
		$promo_code = "";
		
  	}
  	}
  
  } else {
  	$continue = 1;
  }
  if($continue == 1) {
  $pass = MD5($_REQUEST["pass"]);
	//$fullname = $_REQUEST["name"];
	//$name_split = explode(" ",$fullname);
	$fname = trim($_REQUEST["fname"]);
	$lname = trim($_REQUEST["lname"]);
	$fullname  = $conn->real_escape_string($fname." ".$lname);
	
	
	$response = Braintree_Customer::create([
	        'firstName' => 'Mike',
            'lastName' => 'Jones',
            'email' => $_REQUEST["email"],
            'phone' => $_REQUEST["phone"],
            'paymentMethodNonce' => $_REQUEST["nonce"]
	    
	    
	    ]);
	    
	    if ($response->success) {
            $bt_cust_id = $response->customer->id;
            $token = $response->customer->paymentMethods[0]->token;
        } else {
    
            foreach($response->errors->deepAll() AS $error) {
                error_log($error->code . ": " . $error->message);
        }
}
	
	
	
  
  if($token != "")
	{
	
	if($fname!="" && $lname!="")
	{
		$phone = str_replace(" ", "", $_REQUEST["phone"]);
			$sql = "INSERT INTO `customers` (`id`, `name`, `mobile`, `email`,`password`, `firebase_token`, `promo_code`, `promo_used`, `is_delete`, `created`, `modified`) VALUES (NULL, '".$fullname."', '".$phone."', '".$_REQUEST["email"]."', '".$pass."', '', '".$promo_code."', '1', '0',NOW() , NOW() )";
			if ($conn->query($sql) === TRUE) 
			{
				$cid = $conn->insert_id;
				if($conn->insert_id)
				{
				    if(isset($_REQUEST["googleID"]) && $_REQUEST["googleID"] != "") {
				        
				        $sql = "SELECT * FROM `google_id` WHERE `google_id` = '".$_REQUEST["googleID"]."'";
    					$insert = $conn->query($sql);
    					
    					if($insert->num_row > 0) {
    					    
    					    $sql = "DELETE FROM `customers` WHERE `id` = ".$cid;
    					    
    					    $insert = $conn->query($sql);
    					    
    					    $Res["status"] = "error";
    					    $Res["message"] = "Google ID already attached to an account";
    					    
    					    die(json_encode(new ArrayObject($Res)));
    					    
    					} else {
				        
				        
				        $sql = "INSERT INTO `google_id` (`id`, `cid`, `google_id`, `date_created`) VALUES (NULL, '".$cid."', '".$_REQUEST["googleID"]."', NOW())";
    					$insert = $conn->query($sql);
    					if(!$insert) {error_log("google add error ".$conn->error);}
				        
    					}
				        
				        
				        
				    } else if(isset($_REQUEST["facebookID"]) && $_REQUEST["facebookID"] != "") {
				        
				        
				        $sql = "SELECT * FROM `facebook_id` WHERE `facebook_id` = '".$_REQUEST["facebookID"]."'";
    					$insert = $conn->query($sql);
    					
    					if($insert->num_row > 0) {
    					    
    					    $sql = "DELETE FROM `customers` WHERE `id` = ".$cid;
    					    
    					    $insert = $conn->query($sql);
    					    
    					    $Res["status"] = "error";
    					    $Res["message"] = "Google ID already attached to an account";
    					    
    					    die(json_encode(new ArrayObject($Res)));
    					    
    					} else {
				        
				        $sql = "INSERT INTO `facebook_id` (`id`, `cid`, `facebook_id`, `date_created`) VALUES (NULL, '".$cid."', '".$_REQUEST["facebookID"]."', NOW())";
    					$insert = $conn->query($sql);
    					if(!$insert) {error_log("facebook add error ".$conn->error);}
				        
				        
    					}
				        
				        
				    }
				    
				    
					//$expmonth = $_REQUEST["expmonth"];
					//$expyear = $_REQUEST["expyear"];
					if($referal) {
					$sql = "INSERT INTO `referral_use` (`id`, `referer_id`, `refered_id`, `code`, `value`, `reference`, `date_used`) VALUES (NULL, '".$promo_details['customer_id']."', '".$cid."', '".$promo_code."', '".$promo_details['value']."', '', NULL)";
					$insert = $conn->query($sql);
					if(!$insert) {error_log($conn->error);}
					
					$sql = "SELECT * FROM `referal_claim` WHERE `code` = '".$promo_code."'";
					$result = $conn->query($sql);
						if($result->num_rows > 0) {
						$claims = $result->fetch_assoc();
						$current_claims = $claims['referrals_generated'];
						$new_claims = $current_claims + 1;
						error_log("Number of claims: ".$new_claims);
						$sql = "UPDATE `referal_claim` SET `referrals_generated` = ".$new_claims.", `date_last_generated` = NOW() WHERE `code` = '".$promo_code."'";
						$update = $conn->query($sql);
						if(!$update) {error_log($conn->error);}
						
						
						} else {
						
						$sql = "INSERT INTO `referal_claim` (`id`, `customer_id`, `code`, `referrals_generated`, `date_last_generated`, `referrals_claimed`, `reference_claimed`, `date_last_claimed`, `value`) VALUES (NULL, '".$promo_details['customer_id']."',  '".$promo_code."', '1', NOW(), '0', '', NULL, '10')";
						$insert = $conn->query($sql);
						if(!$insert) {error_log($conn->error);}
						}
					
					}
					
					
					$address = $pickup = $conn->real_escape_string($_REQUEST['address']);
					$addr_lat = $_REQUEST["addr_la"];
					$addr_long = $_REQUEST["addr_long"];
					$sql_detail = "INSERT INTO `customer_details` (`id`, `cid`, `address`, `addr_lat`, `addr_long`) VALUES (NULL, '".$cid."', '".$address."', '".$addr_lat."','".$_REQUEST['addr_long']."')";
					if ($conn->query($sql_detail) === TRUE) 
					{
						//$Res["customer_detail_id"] = $conn->insert_id;
						//$Res["customer_detail_status"] = "OK";
						$success[] = "Ok" ;
					}
					else
					{
						//$Res["customer_detail_status"] = "Error";
						error_log($conn->error);
					
						$error[] = "Error";
						
					}
					
						
							$sql_token = "INSERT INTO `customer_tokens` (`id`, `cid`, `bt_cust_id`,`access_token_value`, `status`, `created`, `modified`) VALUES (NULL, '".$cid."', '".$bt_cust_id."', '".$token ."', '".$_REQUEST['user_agree']."', NOW(), NULL)";
							$cid = $conn->insert_id;
							if ($conn->query($sql_token) === TRUE) 
							{
								//$Res["customer_token_id"] = $conn->insert_id;
								//$Res["customer_token_status"] = "OK";
								$success[] = "Ok" ;
							}
							else
							{
								error_log($conn->error);
								//$Res["customer_token_status"] = "Error";
								$error[] = "Error";
							}
						}
						} else {
						error_log($conn->error);
						}
					} else
			{
				$Res["message"] = "First and Last Name required";
				$Res["customer_status"] = "name error";
				$Res["status"] = "name error";
			}
		
				$success = sizeof($success);
				$error = sizeof($error);
				if($success==2)
				{
					$Res["message"] = "New Customer is created successfully";
					$Res["customer_status"] = "OK";
					$Res["status"] = "OK";
					
					
					
					
					$curlObj = curl_init();
	curl_setopt($curlObj, CURLOPT_URL, 'https://hooks.slack.com/services/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');
	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, '{"text": "New Customer '.$fullname.' created '.$promo_code.'"}');

	$response = curl_exec($curlObj);

	curl_close($curlObj);
	

	
	$url = "https://hooks.zapier.com/hooks/catch/1952188/z1cs79/";
    			$curlObj = curl_init();

			curl_setopt($curlObj, CURLOPT_URL, "$url");
			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_HTTPHEADER, array('Accept: application/json'));		
			curl_setopt($curlObj, CURLOPT_POST, 1);
			curl_setopt($curlObj, CURLOPT_POSTFIELDS, '[{"cid": "'.$cid.'"}]');



			//$response = curl_exec($curlObj);

			curl_close($curlObj);
					
					
				}
				if($error>0)
				{
					$Res["message"] = "User data not accurate";
					$Res["customer_status"] = "error";
					$Res["status"] = "error";
				}
				
				
				
			} else {
					$Res["message"] = "Credit Card details invalid or incorrect";
					$Res["customer_status"] = "error";
					$Res["status"] = "error";
				}
 			
 
 	} else {
 		$Res["message"] = "Invalid Promo Code";
		$Res["customer_status"] = "promo error";
		$Res["status"] = "promo error";
 
 	}
 }
  else
  {
	 $Res["message"] = "Please accept the user agreement";
	 $Res["customer_status"] = "agreement error";
  }
  
  
}
echo json_encode(new ArrayObject($Res)); 
//echo "<pre>";
//print_r($Res);
//print_r($response);
//echo "</pre>";
$conn->close();
// =============== New customer user api End Here ==========================


?>