<?php
	
	require_once('database.php');
	require_once('API_main_class.php');
	
	ini_set("log_errors", 1);
	ini_set("error_log", "php-error.log");
	date_default_timezone_set('Asia/Kolkata');


	$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";
	fwrite($file, $parameter);
	fwrite($file, $data);
	$parameter = $parameter."-----------------------------------------------"."\n";
    fwrite($file, $parameter);
	fclose($file);

	/*$data = '{"id":823684137075,"email":"odedarapravin@gmail.com","closed_at":null,"created_at":"2018-10-17T18:01:00+05:30","updated_at":"2018-10-17T18:01:01+05:30","number":44,"note":null,"token":"1abfa02f155896d484f9becebaf64bc3","gateway":"Bank Deposit","test":false,"total_price":"44049.40","subtotal_price":"37330.00","total_weight":0,"total_tax":"6719.40","taxes_included":false,"currency":"INR","financial_status":"pending","confirmed":true,"total_discounts":"6750.00","total_line_items_price":"44080.00","cart_token":"0417ec56a9905f814668e66dca97d2d1","buyer_accepts_marketing":true,"name":"#1044","referring_site":"","landing_site":"\/","cancelled_at":null,"cancel_reason":null,"total_price_usd":"599.55","checkout_token":"692214b084c50a52d16ed53576669474","reference":null,"user_id":null,"location_id":null,"source_identifier":null,"source_url":null,"processed_at":"2018-10-17T18:01:00+05:30","device_id":null,"phone":null,"customer_locale":"en","app_id":580111,"browser_ip":null,"landing_site_ref":null,"order_number":1044,"discount_applications":[{"type":"discount_code","value":"6750.0","value_type":"fixed_amount","allocation_method":"across","target_selection":"all","target_type":"line_item","code":"FKPN-GUOS-H258"}],"discount_codes":[{"code":"FKPN-GUOS-H258","amount":"6750.00","type":"fixed_amount"}],"note_attributes":[{"name":"Checkout-Method","value":"shipping"}],"payment_gateway_names":["Bank Deposit"],"processing_method":"manual","checkout_id":4933023137907,"source_name":"web","fulfillment_status":null,"tax_lines":[{"price":"6719.40","rate":0.18,"title":"CGST"}],"tags":"","contact_email":"odedarapravin@gmail.com","order_status_url":"https:\/\/mybooster.biz\/5128749171\/orders\/1abfa02f155896d484f9becebaf64bc3\/authenticate?key=5c75458078ee193125322f5504f75527","total_tip_received":"0.0","line_items":[{"id":1784285888627,"variant_id":16021188083827,"title":"Nutravita Purebiotic - Probiotic Pearls (180 count) (PV : 2900)","quantity":9,"price":"4750.00","sku":"","variant_title":"Purchase","vendor":"MyBooster","fulfillment_service":"manual","product_id":1035187454067,"requires_shipping":true,"taxable":true,"gift_card":false,"name":"Nutravita Purebiotic - Probiotic Pearls (180 count) (PV : 2900) - Purchase","variant_inventory_management":null,"properties":[{"name":"Leg","value":"Left"}],"product_exists":true,"fulfillable_quantity":9,"grams":0,"total_discount":"0.00","fulfillment_status":null,"discount_allocations":[{"amount":"6546.34","discount_application_index":0}],"tax_lines":[{"title":"CGST","price":"6516.66","rate":0.18}],"origin_location":{"id":511965790323,"country_code":"IN","province_code":"MH","name":"Mybooster","address1":"Chembur","address2":"","city":"Mumbai","zip":"400071"}},{"id":1784285921395,"variant_id":16020691615859,"title":"Quick Change DC-5M Water Filter Cartridge (DC RO-1121) (PV : 400)","quantity":2,"price":"1330.00","sku":"","variant_title":"Repurchase","vendor":"MyBooster","fulfillment_service":"manual","product_id":1418687742067,"requires_shipping":true,"taxable":true,"gift_card":false,"name":"Quick Change DC-5M Water Filter Cartridge (DC RO-1121) (PV : 400) - Repurchase","variant_inventory_management":null,"properties":[{"name":"_ZapietId","value":"0417ec56a9905f814668e66dca97d2d1"}],"product_exists":true,"fulfillable_quantity":1,"grams":0,"total_discount":"0.00","fulfillment_status":null,"discount_allocations":[{"amount":"203.66","discount_application_index":0}],"tax_lines":[{"title":"CGST","price":"202.74","rate":0.18}],"origin_location":{"id":511965790323,"country_code":"IN","province_code":"MH","name":"Mybooster","address1":"Chembur","address2":"","city":"Mumbai","zip":"400071"}}],"shipping_lines":[{"id":578284945523,"title":"Domestic","price":"0.00","code":"Domestic","source":"shopify","phone":null,"requested_fulfillment_service_id":null,"delivery_category":null,"carrier_identifier":null,"discounted_price":"0.00","discount_allocations":[],"tax_lines":[]}],"billing_address":{"first_name":"Vinay ","address1":"Thane","phone":null,"city":"Mumbai","zip":"400091","province":"Maharashtra","country":"India","last_name":"Sharma","address2":"Jhghjghjg","company":null,"latitude":19.2340372,"longitude":72.8399487,"name":"Vinay  Sharma","country_code":"IN","province_code":"MH"},"shipping_address":{"first_name":"Vinay ","address1":"Thane","phone":null,"city":"Mumbai","zip":"400091","province":"Maharashtra","country":"India","last_name":"Sharma","address2":"Jhghjghjg","company":null,"latitude":19.2340372,"longitude":72.8399487,"name":"Vinay  Sharma","country_code":"IN","province_code":"MH"},"fulfillments":[],"client_details":{"browser_ip":"110.227.193.174","accept_language":"en-us","user_agent":"Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit\/605.1.15 (KHTML, like Gecko) Version\/11.1 Safari\/605.1.15","session_hash":"31a4384bf2ddb75c4ee4330c99868010","browser_width":1440,"browser_height":839},"refunds":[],"customer":{"id":724573487219,"email":"odedarapravin@gmail.com","accepts_marketing":true,"created_at":"2018-07-03T10:59:09+05:30","updated_at":"2018-10-17T18:01:01+05:30","first_name":"Vinay","last_name":"Sharma","orders_count":15,"state":"enabled","total_spent":"25457.23","last_order_id":823684137075,"note":null,"verified_email":true,"multipass_identifier":null,"tax_exempt":false,"phone":"+918169961671","tags":"","last_order_name":"#1044","default_address":{"id":1242193395827,"customer_id":724573487219,"first_name":"Vinay ","last_name":"Sharma","company":null,"address1":"Thane","address2":"Jhghjghjg","city":"Mumbai","province":"Maharashtra","country":"India","zip":"400091","phone":null,"name":"Vinay  Sharma","province_code":"MH","country_code":"IN","country_name":"India","default":true}}}';*/

																																								$data = json_decode($data);
	$customer_id = $data->customer->id;
	$product_info = $data->line_items;
	$online_TransactionID = $data->checkout_id;
	$order_id = $data->order_number;
	$payment_mode = 1;
	$payment_status = 1;
	$no_of_items = count($data->line_items);
	$total_quantity = 0;
	$order_type=1;
	$total_price = $data->total_line_items_price;
	$subtotal_price = $data->subtotal_price;
	$total_tax = $data->total_tax;
	$total_amount = $data->total_price;
	$status = 0;

    /*if(!empty($data->source_name))
	{
		if($data->source_name=='web')
			$user_add = 1;

		else
			exit;

	}*/
	

	foreach($data->line_items as $row)
	{
		$total_quantity += $row->quantity;
	}


	if($data->financial_status != "paid")
	{
		$payment_mode   = 2;
		$payment_status = 0;
	}

	$insertcount = 0;

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

	$db->beginTransaction();

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

	if(!empty($data->discount_codes))
	{
		$voucher_code = $data->discount_codes[0]->code;
		$paid_by_voucher = $data->discount_codes[0]->amount;
		//$result = updateVoucher($db, $voucher_code, $paid_by_voucher, $refer_id, $customer_id);
		$result = true;

		if(!$result)
			exit;


	}

    addOrder($db, $customer_id, $order_id, 	$order_type, $refer_id, $no_of_items, $total_quantity, $total_price, $voucher_code, $paid_by_voucher, $subtotal_price, $total_tax, $total_amount, $status);
	
	function addOrder($db, $customer_id, $order_id, $order_type, $refer_id, $no_of_items, $total_quantity, $total_price, $voucher_code, $paid_by_voucher, $subtotal_price, $total_tax, $total_amount, $status)
	{
		try{

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

			$stmt = $db->prepare("INSERT INTO my_order(id, order_type, refer_id, customer_id, date_entered, no_of_items, total_quantity, total_price, discount_code, discount_amount, subtotal_price, total_tax, total_amount,  deleted, status) VALUES('$order_id', '$order_type', '$refer_id', '$customer_id', '$date_entered', '$no_of_items', '$total_quantity', '$total_price', '$voucher_code', '$paid_by_voucher', '$subtotal_price', '$total_tax', '$total_amount', '0', '$status')");

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

			else
				return false;
		}


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

		exit;


	}


   	foreach($product_info as $row)
		{
			$id = $row->variant_id;
			$product_id = $row->product_id;
			$product_price = $row->price;
			$voucher_code = '';
			$paid_by_voucher = 0;
			$total_tax = 0;
			$quantity = $row->quantity;
			if($row->variant_title == 'Purchase')
				$variant = 0;
			else
				$variant = 1;
			
			if(!empty($row->discount_allocations))
			{
				//$voucher_code = $data->discount_codes[0]->code;
				$paid_by_voucher = $row->discount_allocations[0]->amount;

			}
		
			if(!empty($row->tax_lines))
			{
				$total_tax = $row->tax_lines[0]->price;
			}

			$productDetails = getPV($db, $id, $product_id);
			$pv = $productDetails['pricevalue'];
			$totalPV = $productDetails['pricevalue'] * $quantity;
			$title   = $productDetails['title'];
			$paid_by_online = ($product_price * $quantity) - $paid_by_voucher;
			$total_paid  = ($product_price * $quantity) + $total_tax;
			
			if(updateMemberPackage($db, $title, $refer_id, $customer_id, $product_id, $product_price, $quantity, $pv, $totalPV, $paid_by_online, $order_id, $online_TransactionID, $paid_by_voucher, $voucher_code, $total_tax,  $total_paid, $user_add, $payment_mode, $payment_status, $variant))
				$insertcount++;

		}
	


	if($insertcount == count($data->line_items))
		$db->commit();

	else
		$db->rollBack();


	


    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)))
					{
						if($active)
							updatePriceRule($voucher_price_rule, $balance, $applied);

						return true;
					}

					else
						return false;

				}
				
				
				else
					return false;
			}

			else
				return false;
		}

		catch(PDOException $err)
		{
			return false;

		}

	}




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

		$stmt = $db->prepare("select pricevalue, title from my_product where 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, $quantity, $pv, $total_PV, $paid_by_online, $order_id, $online_TransactionID, $paid_by_voucher, $voucher_code, $total_tax,  $total_paid, $user_add, $payment_mode, $payment_status, $repurchase)
	{
		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, customer_id, deleted,  product_id,  product_price, qty, pv, total_PV, paid_by_online, order_id, online_TransactionID, paid_by_voucher, voucher_code, total_tax, total_paid, user_add, payment_mode, payment_status, upload_volume, repurchase) VALUES('$title', '$refer_id', '$date_entered', '$date_entered', '$customer_id', '0', '$product_id',  '$product_price', '$quantity', '$pv', '$total_PV', '$paid_by_online', '$order_id', '$online_TransactionID', '$paid_by_voucher', '$voucher_code', '$total_tax',  '$total_paid', '$user_add', '$payment_mode', '$payment_status', '0', $repurchase)");

			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);
	
	}


 ?>