<?php
/**
 * Stripe - Payment Gateway integration example
 * ==============================================================================
 * 
 * @version v1.0: stripe_pay_demo.php 2016/09/29
 * @copyright Copyright (c) 2016, http://www.ilovephp.net
 * @author Sagar Deshmukh <sagarsdeshmukh91@gmail.com>
 * You are free to use, distribute, and modify this software
 * ==============================================================================
 *
 */

// Stripe library
require 'stripe/Stripe.php';

include_once($_SERVER['DOCUMENT_ROOT'].'/request/react-includes/configuration.php');
global $auth_authorization, $authorization,$familyone_site_url,$authzero_domain, $db_conn;


header('Access-Control-Allow-Origin: *');

global $stripe_credentials;
$params = $stripe_credentials;

if ($params['testmode'] == "on") {
	Stripe::setApiKey($params['private_test_key']);
	$pubkey = $params['public_test_key'];
} else {
	Stripe::setApiKey($params['private_live_key']);
	$pubkey = $params['public_live_key'];
}
$request_data = json_decode(file_get_contents('php://input'), true);

if($request_data['action']=='make_payment'){
	
	$user_id = base64_decode($request_data['user_id']);
	$product_id = $request_data['product_id'];
	$upgraded = $request_data['upgraded'];
	$shipping_address = $request_data['shipping_address'];
	$billing_address = $request_data['billing_address'];
	
	$shipping_address_data = json_decode($shipping_address);
	$shipping_name = $shipping_address_data->shipping_name;
	$shipping_addressLine1 = $shipping_address_data->addressLine1;
	$shipping_city = $shipping_address_data->city;
	$shipping_addressLine2 = $shipping_address_data->addressLine2;
	$shipping_state = $shipping_address_data->shipping_state;
	$shipping_zipcode = $shipping_address_data->zipcode;
	$shipping_country = $shipping_address_data->country;
	
	$get_product_sql = "SELECT * FROM `product_info` WHERE `product_id`= '$product_id'";
	$query = mysqli_query($db_conn, $get_product_sql);
	$product_detail = mysqli_fetch_array($query, MYSQLI_ASSOC);
	
	$redeem_for = $request_data['claim_for'];
	$eligible_for_offer = 0 ;
	$current_date = date('Y-m-d H:m:s');
	if($redeem_for){
		$check_redeem_id_sql = "SELECT * FROM `prize_claim` WHERE id = $redeem_for AND `end_prize_accept_date` >= '$current_date' AND `claim_status` = 'pending'";	
		$check_redeem_id_query = mysqli_query($db_conn, $check_redeem_id_sql);
		$redeem_data = mysqli_fetch_array($check_redeem_id_query, MYSQLI_ASSOC);
		if($redeem_data['user_id'] == $request_data['user_id']){
			$eligible_for_offer = 1;
		}
	}
	
	$price = $product_detail['product_price'];
	$shipping_price = $product_detail['shipping_price'];
	$upgrade_price = $product_detail['upgraded'];
	$expedited_price = $product_detail['expedited'];
	$tax = $product_detail['tax'];
	
	if($eligible_for_offer){
			$total_price = $shipping_price+$tax;
	}else{
		if($upgraded){
			$total_price = $price + $shipping_price + $upgrade_price + $expedited_price+$tax;
		}else{
			$total_price = $price + $shipping_price +$tax;
		}
	}
	
	$payment_for = $product_detail['product_name'];
	$stripeToken = $request_data['stripeToken'];
	$stripe_customer_id = $request_data['customer_id'];
	$stripe_card_id = $request_data['card_id'];
	
	$amount_cents = $total_price*100; 

	$sql = "SELECT * FROM `payment_log` WHERE 1 ORDER BY `payment_id` DESC";
	$query = mysqli_query($db_conn, $sql);
	$query_result33 = mysqli_fetch_array($query, MYSQLI_ASSOC);
	$order_id = $query_result33['payment_id'] + 1;
	$invoiceid = sprintf("%06d", $order_id);
	//$description = "Order #" . $invoiceid . " - " . $invoiceid;
	$description = $order_id;

	$url = $authzero_domain.'/api/v2/users/'.$user_id;
	$ch=curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$auth_authorization));
	$user_information = curl_exec($ch);
	curl_close($ch);
	$user_information = json_decode($user_information);
	$all_payment_data = array();
	if($user_information->user_metadata->payment_data){
		foreach($user_information->user_metadata->payment_data as $existing_payment_data)	
		$all_payment_data[] = $existing_payment_data;
	}
	
	
	if($stripe_customer_id){
				try {
					$charge = Stripe_Charge::create(array(		 
						  "amount" => $amount_cents,
						  "currency" => "cad",
						  "description" => $description,
						  "card" 	=> $stripe_card_id,
						  "customer" => $stripe_customer_id,
						  "metadata" => array('PRODUCT_NAME' => $payment_for,'PRODUCT_PRICE' => '$'.$price,'SHIP_FEE' => '$'.$shipping_price, 'SHIP_NAME' =>$shipping_name,'SHIP_ADDRESSLINE1'=> $shipping_addressLine1, 'SHIP_ADDRESSLINE2' => $shipping_addressLine2, 'SHIP_CITY' => $shipping_city,'SHIP_STATE'=>$shipping_state, 'SHIP_ZIPCODE' => $shipping_zipcode, 'SHIP_COUNTRY'=>$shipping_country)
						  )			  
					);
			
					if ($charge->card->address_zip_check == "fail") {
						throw new Exception("zip_check_invalid");
					} else if ($charge->card->address_line1_check == "fail") {
						throw new Exception("address_check_invalid");
					} else if ($charge->card->cvc_check == "fail") {
						throw new Exception("cvc_check_invalid");
					}
					// Payment has succeeded, no exceptions were thrown or otherwise caught				
			
					$result = "success";
			
				} catch(Stripe_CardError $e) {			
			
				$error = $e->getMessage();
					$result = "declined";
			
				} catch (Stripe_InvalidRequestError $e) {
					$result = "declined";		  
				} catch (Stripe_AuthenticationError $e) {
					$result = "declined";
				} catch (Stripe_ApiConnectionError $e) {
					$result = "declined";
				} catch (Stripe_Error $e) {
					$result = "declined";
				} catch (Exception $e) {
					if ($e->getMessage() == "zip_check_invalid") {
						$result = "declined";
					} else if ($e->getMessage() == "address_check_invalid") {
						$result = "declined";
					} else if ($e->getMessage() == "cvc_check_invalid") {
						$result = "declined";
					} else {
						$result = "declined";
					}		  
				}
}elseif($stripeToken){
		$customer = Stripe_Customer::create([
		    'source' => $stripeToken,
		    'email' => $user_information->email
		]);
		$customer_id = $customer->id;
		
		try {
					$charge = Stripe_Charge::create(array(		 
						  "amount" => $amount_cents,
						  "currency" => "cad",
						  "description" => $description,
						  "customer" => $customer_id,
						  "metadata" => array('PRODUCT_NAME' => $payment_for,'PRODUCT_PRICE' => '$'.$price,'SHIP_FEE' => '$'.$shipping_price, 'SHIP_NAME' =>$shipping_name,'SHIP_ADDRESSLINE1'=> $shipping_addressLine1, 'SHIP_ADDRESSLINE2' => $shipping_addressLine2, 'SHIP_CITY' => $shipping_city,'SHIP_STATE'=>$shipping_state, 'SHIP_ZIPCODE' => $shipping_zipcode, 'SHIP_COUNTRY'=>$shipping_country)
						  )			  
					);
			
					if ($charge->card->address_zip_check == "fail") {
						throw new Exception("zip_check_invalid");
					} else if ($charge->card->address_line1_check == "fail") {
						throw new Exception("address_check_invalid");
					} else if ($charge->card->cvc_check == "fail") {
						throw new Exception("cvc_check_invalid");
					}
					// Payment has succeeded, no exceptions were thrown or otherwise caught				
			
					$result = "success";
			
				} catch(Stripe_CardError $e) {			
			
				$error = $e->getMessage();
					$result = "declined";
			
				} catch (Stripe_InvalidRequestError $e) {
					$result = "declined";		  
				} catch (Stripe_AuthenticationError $e) {
					$result = "declined";
				} catch (Stripe_ApiConnectionError $e) {
					$result = "declined";
				} catch (Stripe_Error $e) {
					$result = "declined";
				} catch (Exception $e) {
					if ($e->getMessage() == "zip_check_invalid") {
						$result = "declined";
					} else if ($e->getMessage() == "address_check_invalid") {
						$result = "declined";
					} else if ($e->getMessage() == "cvc_check_invalid") {
						$result = "declined";
					} else {
						$result = "declined";
					}		  
				}
}
		if($result == 'success'){
			$charge = $charge->__toArray(true);
			if(!empty($charge['source'])){
					$payment_data = array(
											'card_id' => $charge['source']['id'],
											'exp_month' => $charge['source']['exp_month'],
											'exp_year' => $charge['source']['exp_year'], 
											'last4' => $charge['source']['last4'],
											'customer_id' => $charge['source']['customer'],
											'brand' => $charge['source']['brand']
										 );
					if(!empty($all_payment_data)){
						$existing_flag = 0;
						foreach($all_payment_data as $saved_card){
							if($saved_card->last4 == $charge['source']['last4'])
							{
								$existing_flag = 1;
							}
						}
						if($existing_flag == 0){
							$all_payment_data[] = $payment_data;
						}
					}else{
						$all_payment_data[] = $payment_data;
					}
					
			}
			
			
			include_once($_SERVER['DOCUMENT_ROOT'].'/request/react-includes/request_functions.php');
			include_once($_SERVER['DOCUMENT_ROOT'].'/request/react-includes/mail_functions.php'); 
			
			$user_data['user_id'] = $user_id;
			$user_data['order_id'] = "Order #" . $invoiceid;
			$user_data['transaction_id'] = $transaction_id = $charge['balance_transaction'];
			$user_data['user_email'] =  $user_email =  $charge['receipt_email'];
			$user_data['price'] = $price ;
			$user_data['shipping_price'] = $shipping_price ;
			$user_data['tax'] = $tax ;
			$user_data['total_price'] = $total_price ;
			$user_data['product_name'] = $payment_for ;
			
			$insert_sql = "INSERT INTO `payment_log`(`user_id`, `user_email`, `product_id`, `shipping_charge`, `product_price`, `total_price`, `transaction_id`, `transaction_status`,`product_name`,`billing_address`,`shipping_address`) VALUES ('$user_id','$user_email','$product_id','$shipping_price','$price','$total_price','$transaction_id','completed','$payment_for','$billing_address','$shipping_address')";
			mysqli_query($db_conn, $insert_sql); 
			
			sendOrderConfirmationToUser($user_data);
			//sendOrderConfirmationToAdmin($user_data);
			
			$data_to_update = array(
				'user_metadata' =>array('payment_data'=>$all_payment_data,'products'=>array($payment_for))
			);
			
			$update_url = $authzero_domain.'/api/v2/users/'.$user_id;
			$update_data_string = json_encode($data_to_update);
			$ch=curl_init($update_url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
			curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$auth_authorization));
			curl_setopt($ch, CURLOPT_POSTFIELDS, $update_data_string);
			$update_result = curl_exec($ch);
			curl_close($ch);
			header('Access-Control-Allow-Origin: *');
			echo json_encode(array('payment_status'=>'successful'));
		}else{
			echo json_encode(array('payment_status'=>'failed'));
		}
	
}
?>