<?php

header('Content-Type: application/json');
//header( 'Content-Type: text/html; charset=utf-8' ); 
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://35.154.98.204");
header('Access-Control-Allow-Headers');
header('Content-Type: application/json');

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(1);
ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");

date_default_timezone_set('Asia/Kolkata');

require_once('database.php');

$file = fopen("../API_Logs/API_requestcode.txt","a");
$today = date("Y-m-d H:i:s");
$parameter = "-------------------".$today."-----------------------------"."\n";
foreach($_REQUEST as $key=>$value) {
	$parameter = $parameter."$key=>$value"."\n";
}
$parameter = $parameter."-----------------------------------------------"."\n";
fwrite($file, $parameter);
fclose($file);


$_REQUEST['refer_id'] 	 = (int) $_REQUEST['refer_id'];

$validationErr = '';
$result = array();

if(strlen(!$_REQUEST['refer_id']) || $_REQUEST['refer_id'] == '') {
	$validationErr = "Invalid Refer ID!";
} else if(strlen(!$_REQUEST['voucherAmt']) || $_REQUEST['voucherAmt'] == '') {
	$validationErr = "Please enter a voucher amount!";
} 

if($validationErr != '') {
	$result = array();
	$result['status'] = '0';
	$result['message'] = $validationErr;
	print $return = json_encode($result);
	exit;
}

else
{

    $voucher_code    = generateVoucher();
    $voucher_value   = $_REQUEST['voucherAmt'];
    $current_balance = $_REQUEST['voucherAmt'];
	$created_date    = date("Y-m-d H:i:s");
	$issued_by       = $_REQUEST['refer_id'];

	$response = price_rule($voucher_code, $voucher_value);

	if($response)
	{
		$voucher_shopify_id = $response['coupon_id'];
		$voucher_price_rule = $response['price_rule_id'];

		if(addVoucher($voucher_shopify_id, $voucher_price_rule, $voucher_code, $voucher_value, $current_balance, $created_date, $issued_by, 'BBT',true))
		{
			$result['success'] 	    = true;
			$result['message'] 	    = 'Voucher code has been succesfully generated!';
			$result['voucher_code'] = $voucher_code;
			$result['amount']       = $voucher_value;
		}

		else
		{
			$result['success'] 	= false;
			$result['message'] 	= 'Voucher code request failed!';
		}
	}

	else
	{
		$result['success'] 	= false;
		$result['message'] 	= 'Voucher code request failed!';
	}
    
	$dbh = null;

}

	function generateVoucher()
	{
			
			$length         = 12;
			$useLetters     = true;
			$useNumbers     = true;
			$useMixedCase	= false;

			$uppercase    = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'];
			$lowercase    = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm'];
			$numbers      = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
			$symbols      = ['`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '\\', '|', '/', '[', ']', '{', '}', '"', "'", ';', ':', '<', '>', ',', '.', '?'];

			$characters   = [];
			$coupon = '';

			if ($useLetters) {
				if ($useMixedCase) {
					$characters = array_merge($characters, $lowercase, $uppercase);
				} else {
					$characters = array_merge($characters, $uppercase);
				}
			}

			if ($useNumbers) {
				$characters = array_merge($characters, $numbers);
			}

			for ($i = 0; $i < $length; $i++) {
					$coupon .= $characters[mt_rand(0, count($characters) - 1)];
			}

			$coupon  = substr_replace($coupon, "-",4,0);
			$coupon  = substr_replace($coupon, "-",9,0);
		   
			if(verifyVoucher($coupon))
				generateVoucher();

			else
				return $coupon;

	}




	function verifyVoucher($voucher_code)
	{
		$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'");
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		if($result['voucher_code'] == NULL)
			return 0;

		else
			return 1;
		
		

	}



	function addVoucher($voucher_shopify_id, $voucher_price_rule, $voucher_code, $voucher_value, $current_balance, $created_date, $issued_by, $source, $active)
	{
		$conn = new Database;
		$db = $conn->getConnection();
	    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		try
		{
			$stmt = $db->prepare("INSERT INTO my_voucher(voucher_shopify_id, voucher_price_rule, voucher_code, voucher_value, current_balance, created_date, issued_by, source, active, no_usage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		    $stmt->execute(array($voucher_shopify_id, $voucher_price_rule, $voucher_code, $voucher_value,$current_balance, $created_date, $issued_by, $source, $active, 0));

			//if(price_rule($voucher_code, $voucher_value))
			return true;
	    }

		catch(PDOException $e)
		{
			return false;
		}

	} 


	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") );
			$priceRuleData['price_rule']['prerequisite_subtotal_range']['greater_than_or_equal_to'] = $discountValue * -2.00;


			$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);
				
				//close cURL resource
				curl_close($ch);

				if(isset($discountResult->discount_code->code)) {
					$response['coupon_code'] = $discountResult->discount_code->code;
					$response['coupon_id'] = $discountResult->discount_code->id;
					$response['price_rule_id'] = $discountResult->discount_code->price_rule_id;
					$response['msgtype'] = 'success';
					return $response;
				}

				else
					return false;



			}


	}




 echo json_encode($result);


?>





















