<?php
// required headers
require_once('database.php');


date_default_timezone_set('Asia/Kolkata');

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: https://mybooster.biz");
header('Access-Control-Allow-Headers');
header('Content-Type: application/json');
$file = fopen("../API_logs/API_voucher.txt","a");
$today = date("Y-m-d H:i:s");
$parameter = "-------------------".$today."----------------------------"."\n";
//$parameter = $parameter."File Name=>".$_FILES['videofile']['name']."\n";
foreach($_REQUEST as $key=>$value) {
	$parameter = $parameter."$key=>$value"."\n";
}
$parameter = $parameter."-----------------------------------------------"."\n";
//print "<br>".$parameter;
fwrite($file, $parameter);
fclose($file);

$validationErr = "";

if(!isset($_REQUEST['voucher_code'])){
	$validationErr = "Please enter the Voucher Code!";
}

else if(!isset($_REQUEST['memberID'])){
	$validationErr = "Please enter the Member ID!";
}

else if(!isset($_REQUEST['amount'])){
	$validationErr = "Please enter the Transaction Amount!";
}

else if(!isset($_REQUEST['query'])) {
	$validationErr = "Please enter the query type!";
}



else
{

	$memberID = $_REQUEST['memberID'];
	$voucher_code = $_REQUEST['voucher_code'];
	$amount = (float)str_replace("Rs. ", "", $_REQUEST['amount'])*0.5;
	$discountvalue=0;

	if(verifyMemberID($memberID))
	{
		if(verifyCouponCode($voucher_code, $amount))
		{
			
			$initial_balance = getBalance($voucher_code);
			if($initial_balance < $amount)
			{
				$final_balance = 0;
				$discountvalue = $initial_balance;
			}

			else
			{
				$final_balance = $initial_balance - $amount;
				$discountvalue = $amount;
			}

			$description = "Product Purchase";


			if($_REQUEST['query'] == 0)
			{

				$couponcode = $voucher_code . "-" . time();


			
				$data = price_rule($couponcode, $discountvalue);

				if($data)
				{
					$result['success'] = true;
					$result['message'] = "Voucher Code valid!";
					$result['coupon_code'] =  $data;
					$result['balance'] =  $initial_balance;
					$result['discountedRate'] =  $discountvalue; 
				}

				else
				{
					$result['success'] = true;
					$result['message'] = "Transaction is Successful!";
					$result['balance'] =  $initial_balance;
					
				}

			}


			else
			{

				if(processTranscation($voucher_code, $memberID, 0, $initial_balance, $amount, $final_balance, $description))
				{
					$result['success'] = true;
					$result['message'] = "Transaction is Successful!";
					$result['data']['balance'] =  $initial_balance - $amount;
				}

				else
				{
					$result['success'] = false;
					$result['message'] = "Your request cannot be processed at the moment. Please contact our support centre!";

				}
			}
				

		}


		else
		{
			$result['success'] = false;
			$result['message'] = "Invalid Voucher Code for this transaction!";

		}


	}

	else
	{
		$result['success'] = false;
		$result['message']="Invalid Member ID!";

	}

}

if($validationErr != '') {

	$result = array();
	$result['success'] = false;
	$result['message'] = $validationErr;
	print $return = json_encode($result);
	exit;

} 


	function verifyMemberID($referID)
	{
		$conn = new Database;
		$db = $conn->getConnection();
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$stmt = $db->prepare("select refer_id from my_registration where refer_id='$referID'");
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$db = null;

		if($result['refer_id'] != NULL)
			return 1;

		else
			return 0;
		
	}


	function verifyCouponCode($voucher_code, $amount)
	{
		$conn = new Database;
		$db = $conn->getConnection();
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$stmt = $db->prepare("select voucher_code from my_voucher where voucher_code='$voucher_code' && active='1'");
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$db = null;

		if($result['voucher_code'] != NULL)
			return 1;

		else
			return 0;
		
	}

	
	function getBalance($voucher_code)
	{
		$conn = new Database;
		$db = $conn->getConnection();
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$stmt = $db->prepare("select current_balance from my_voucher where voucher_code='$voucher_code'");
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$db = null;

		if($result['current_balance'] != NULL)
			return $result['current_balance'];

		else
			return 0;

	}



	function processTranscation($voucher_code, $refer_id, $mode, $initial_balance, $amount, $final_balance, $description)
	{

		$conn = new Database;
		$db = $conn->getConnection();
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$date_entered = date("Y-m-d H:i:s");

		try
		{
			$db->beginTransaction();

			$stmt = $db->prepare("INSERT INTO my_voucher_transaction(voucher_code, refer_id, mode, initial_balance, amount, final_balance, date_entered, description) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)");
		    $stmt->execute(array($voucher_code, $refer_id, $mode, $initial_balance, $amount, $final_balance, $date_entered, $description));
			
			$stmt2 = $db->prepare("UPDATE my_voucher SET current_balance=? WHERE voucher_code=?");
			$stmt2->execute(array($final_balance, $voucher_code));

			if($amount == $initial_balance)
			{
				$stmt3 = $db->prepare("UPDATE my_voucher SET active=? WHERE voucher_code=?");
				$stmt3->execute(array(0, $voucher_code));
			}

			$db->commit();

			return true;
   		
		}

		catch(PDOException $ex) {
			$db->rollBack();
		}



		$db = null;

	}

			
	function price_rule($couponcode, $discountvalue)
	{

			$response =array();

			$customerCoupon = $couponcode; // This will be unique alpha  numeric no.
			$discountValue = -1 * $discountvalue;//abs($discountvalue); // This will be alway in negative value Eg: -10, -13 ...
			// Calculate Coupon and Discount value based on above value, assign the coupon value to $customerCoupon and discount amount to $discountValue
		

			$priceRuleUrl = 'https://b2836f581daab99987d3b7c5e1eac1eb:4a15503729dadc8232100ca19c57d05a@marvel-mii.myshopify.com/admin/price_rules.json';

			//create a new cURL resource
			$ch = curl_init($priceRuleUrl);

			//setup request to send json via POST
			$priceRuleData = array();
			$priceRuleData['price_rule']['title'] = $customerCoupon;
			$priceRuleData['price_rule']['target_type'] = 'line_item';
			$priceRuleData['price_rule']['target_selection'] = 'all';
			$priceRuleData['price_rule']['allocation_method'] = 'across';
			$priceRuleData['price_rule']['value_type'] = 'fixed_amount';
			$priceRuleData['price_rule']['value'] = $discountValue;
			$priceRuleData['price_rule']['customer_selection'] = 'all';
			$priceRuleData['price_rule']['usage_limit'] = 1;
			$priceRuleData['price_rule']['starts_at'] = date(DATE_ISO8601, strtotime("-2 hours") );


			$payload = json_encode($priceRuleData);
			//attach encoded JSON string to the POST fields
			curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			//set the content type to application/json
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

			//return response instead of outputting
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					
			//execute the POST request
			$priceRuleResponse = curl_exec($ch);
			$priceRuleResult = json_decode($priceRuleResponse);

			//close cURL resource
			curl_close($ch);

			if(isset($priceRuleResult->price_rule->id)){
				$discountUrl = 'https://b2836f581daab99987d3b7c5e1eac1eb:4a15503729dadc8232100ca19c57d05a@marvel-mii.myshopify.com/admin/price_rules/'.$priceRuleResult->price_rule->id.'/discount_codes.json';

				$discountData = array();
				$discountData['discount_code']['code'] = $customerCoupon;

				$ch = curl_init($discountUrl);
				$payload = json_encode($discountData);
				//attach encoded JSON string to the POST fields
				curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				//set the content type to application/json
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

				//return response instead of outputting
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				//execute the POST request
				$discountResult = curl_exec($ch);

				$discountResult = json_decode($discountResult);

				if(isset($discountResult->discount_code->code)) {
					$response['coupon_code'] = $discountResult->discount_code->code;
					$response['msgtype'] = 'success';
				}
				//close cURL resource
				curl_close($ch);

			}


			return $response['coupon_code'];


	}






	print $return = json_encode($result);
	exit;



//echo json_encode($data['data']['voucher_code']);


?>