<?php
	
	
	require_once('database.php');
	require_once('API_main_class.php');
	date_default_timezone_set('Asia/Kolkata');

	
	ini_set("log_errors", 1);
	ini_set("error_log", "php-error.log");

	$data = file_get_contents('php://input');


	$file = fopen("../API_logs/API_purchase.txt","a");
	
	$today = date("Y-m-d H:i:s");
	$parameter = "-------------------".$today."----------------------------"."\n";
    //$paramater .= $data;
	$parameter .= $parameter."-----------------------------------------------"."\n";
	//print "<br>".$parameter;*/
	fwrite($file, $data);
    fwrite($file, $parameter);
	fclose($file);


    $data = json_decode($data);
 

	$customer_id = $data->customer->id;

	$id = $data->line_items[0]->variant_id;
	
	$product_id = $data->line_items[0]->product_id;

	$product_price = $data->total_line_items_price;

	$paid_by_online = $data->total_price - $data->total_discounts;

	$online_TransactionID = $data->checkout_id;

	$paid_by_voucher = $data->total_discounts;
	
	$total_tax = $data->total_tax;

	$total_paid = $data->total_price + $data->total_discounts;

	$voucher_code = $data->discount_codes[0]->code;


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

	$db->beginTransaction();

	$refer_id = getReferID($db, $customer_id);

    if(updateVoucher($db, $voucher_code, $paid_by_voucher, $refer_id, $customer_id))
	{

		$productDetails = getPV($db, $id, $product_id);
		$totalPV = $productDetails['pricevalue'];
		$title = $productDetails['title'];
		
		if(updateMemberPackage($db, $title, $refer_id, $customer_id, $product_id, $product_price, $totalPV, $paid_by_online, $online_TransactionID, $paid_by_voucher, $voucher_code, $total_tax,  $total_paid))
			$db->commit();

		else
			$db->rollBack();

  	
	}


	else
	{

		exit;

	}



    function getReferID($db, $customer_id)
	{
		$stmt = $db->prepare("SELECT refer_id from my_registration where customer_id='$customer_id' && deleted='0'");
		$stmt->execute();
	    $result = $stmt->fetch(PDO::FETCH_ASSOC);
		if($result!=NULL)
			return $result['refer_id'];

	}
	
	
	function updateVoucher($db, $voucher_code, $paid_by_voucher, $refer_id, $customer_id)
	{
		try{

			$date_entered = date("Y-m-d H:i:s");
			$voucher_price_rule = 0;
			$voucher_shopify_id = 0;

			$stmt = $db->prepare("SELECT voucher_shopify_id,  voucher_price_rule, current_balance, no_usage 
			from my_voucher where voucher_code='$voucher_code' && current_balance>='$paid_by_voucher' && active='1'");

			$stmt2 = $db->prepare("INSERT INTO  my_voucher_transaction(id, voucher_code, refer_id, customer_id, mode, initial_balance, amount, final_balance, date_entered, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

			$stmt3 = $db->prepare("UPDATE my_voucher SET current_balance=?, active=?, no_usage=? WHERE voucher_code=?");

			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);
		
			if($result['current_balance']!=NULL)
			{
				$applied = $result['no_usage'];
				$voucher_price_rule =  $result['voucher_price_rule'];
			    $voucher_shopify_id =  $result['voucher_shopify_id'];

				$balance = 0;

				if($stmt2->execute(array(NULL, $voucher_code, $refer_id, $customer_id, '0', $result['current_balance'], $paid_by_voucher, $result['current_balance']-$paid_by_voucher, $date_entered, 'Product Purchase')))
				{
					$balance = $result['current_balance'] - $paid_by_voucher;

					if($balance > 0)
						$active = 1;
					else
						$active = 0;

					if($stmt3->execute(array($balance, $active, $applied++, $voucher_code)))
					{
					    updatePriceRule($voucher_price_rule, $balance, $applied);
						return true;
					}

					else
						return false;

				}
				
				
				else
					return false;
			}

			else
				return false;
		}

		catch(PDOException $err)
		{
			echo $err->getMessage();
		}

	}



	function getPV($db, $id, $product_id)
	{

		$stmt = $db->prepare("select pricevalue, title from my_product where id='$id' && product_id = '$product_id' && status='1'");
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$db = null;
		return $result;
	}


	function updateMemberPackage($db, $title, $refer_id, $customer_id, $product_id, $product_price, $total_PV, $paid_by_online, $online_TransactionID, $paid_by_voucher, $voucher_code, $total_tax,  $total_paid)
	{
		try{

			$date_entered = date("Y-m-d H:i:s");


			/*$stmt = $db->prepare("INSERT INTO my_member_package(name, refer_id, date_entered, date_modified, modified_user_id, created_by, description, deleted, assigned_user_id, package_id, package_name, package_price, total_PV, paymentmode1, paymentmodetype1, paymentmode2, paymentmodetype2, user_add, cash_status, reference) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)");
		
			$stmt->execute(array($productName, $voucher_code, $email, $mode, $initial_balance, $amount, $final_balance, $date_entered, $description));*/

   
			$stmt = $db->prepare("INSERT INTO my_member_package(name, refer_id, date_entered, date_modified, customer_id, deleted,  product_id,  product_price, total_PV, paid_by_online, online_TransactionID, paid_by_voucher, voucher_code, total_tax, total_paid, user_add, cash_status, reference, payment_status) VALUES('$title', '$refer_id', '$date_entered', NULL, '$customer_id', '0', '$product_id',  '$product_price', '$total_PV', '$paid_by_online', '$online_TransactionID', '$paid_by_voucher', '$voucher_code', '$total_tax',  '$total_paid', '1', '0', '0','1')");

			if($stmt->execute())
				return true;

			else
				return false;
		}


		catch(PDOException $err)
		{
			echo $err->getMessage();
		}

	}

	
	function updatePriceRule($voucher_price_rule, $balance, $no_usage)
	{

	    $apiURL = "https://b2836f581daab99987d3b7c5e1eac1eb:4a15503729dadc8232100ca19c57d05a@marvel-mii.myshopify.com/admin/price_rules/".$voucher_price_rule.".json";

		$discountData = array();
		$discountData['price_rule']['id'] = $voucher_price_rule;
		$discountData['price_rule']['value_type'] = 'fixed_amount';
		$discountData['price_rule']['value'] = $balance;
		$discountData['price_rule']['customer_selection'] = 'all';
		//$discountData['price_rule']['prerequisite_subtotal_range']['greater_than_or_equal_to'] = $balance * -3.33;

		$session = curl_init($apiURL);
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($session, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
		curl_setopt($session, CURLOPT_POSTFIELDS, json_encode($discountData));
		curl_setopt($session, CURLOPT_CUSTOMREQUEST, "PUT");
		curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
		curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);

		$result = curl_exec($session);
		$response = json_decode($result);
		curl_close($session);
	
	}


 ?>