<?php

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


	class ProductPurchase
	{
		private $conn;
    	private $conn2;
		public  $memberID;
		public  $customerID;
		public  $productID;
		public  $productName;
		public  $productPrice;
		public  $productPV;
		public  $paidByDeposit;
		public  $paidByCash;
		public  $paidByBBT;
		public  $address;
		public  $totalPaid;
		public  $deliveryType;
		public  $cmbStore;
		public  $variantID;
		public  $quantity;
		public  $orderDetails;
		

		function __Construct()
		{
			$dbconnect = new Database();
			$this->conn = $dbconnect->getConnection();
			$this->conn2 = $dbconnect->getConnection2();
			
		}



		function verifyMemberID()
		{

   		  try{
				$stmt  = $this->conn->prepare("select * from my_registration where refer_id='$this->memberID'");
				$stmt->execute();
				$result = $stmt->fetch(PDO::FETCH_ASSOC);
				
				if($result)
			    {
				   $this->customerID = $result['customer_id'];
				   return true;
				}

				else
					return false;
			
			  }catch(Exception $err){

				return false;

			 } 
		 }


		 function verifyProductDetails()
		 {
			
			try{
				$stmt  = $this->conn->prepare("select * from my_product where id='$this->variantID'");
				$stmt->execute();
				$result = $stmt->fetch(PDO::FETCH_ASSOC);
				
				if($result)
				{
					//if($result['price'] <= ($this->paidByDeposit + $this->paidByCash + $this->paidByBBT))
					if($result['price'])
					{
					   $this->productName  = $result['name'];
					   $this->productPrice = $result['price'];
					   $this->productPV    = $result['pricevalue'];
					   //$this->totalPaid    = $this->paidByDeposit + $this->paidByCash + $this->paidByBBT;
					   $this->totalPaid   = $result['price'];
           	 		   return true;
					}

					else
						return false;
				
				}
				else
					return false;
			
			  }catch(Exception $err){

				return false;

			 } 

		   }

           function makePurchase()
		    {

				 try{



					if($this->variantID > 1 && $this->variantID <= 13) 
						{
							$stmt  = $this->conn->prepare("INSERT INTO my_member_package(name, refer_id, date_entered, customer_id, deleted, product_id, product_price, total_PV, paid_by_online, order_id, online_TransactionID, paid_by_voucher, paid_by_deposit, paid_by_cash, paid_by_BBT, total_tax, total_paid, user_add, payment_mode, payment_status, upload_volume) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
							$test = $stmt->execute(array($this->productName, $this->memberID, date("Y-m-d H:i:s"), $this->customerID, '0', $this->variantID, $this->productPrice, $this->productPV, '0', md5(time()), '0', '0', 0, 0, 0, '0', $this->totalPaid, '0', '3', '1', '0'));
							
							
						}


					  if($this->shopifyPurchase())
					  { 
						
						/*$stmt  = $this->conn->prepare("INSERT INTO my_member_package(name, refer_id, date_entered, customer_id, deleted, product_id, product_price, total_PV, paid_by_online, order_id, online_TransactionID, paid_by_voucher, paid_by_deposit, paid_by_cash, paid_by_BBT, total_tax, total_paid, user_add, payment_mode, payment_status, upload_volume) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

						$stmt->execute(array($this->productName, $this->memberID, date("Y-m-d H:i:s"), $this->customerID, '0', $this->variantID, $this->productPrice, $this->productPV, '0', md5(time()), '0', '0', $this->paidByDeposit, $this->paidByCash, $this->paidByBBT, '0', $this->totalPaid, '0', '3', '1', '0'));*/

						return true;
					  }

					 else
					 {

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

					 }
			
				  }catch(Exception $err){
					  echo $err->getMessage();
					  return false;
				  } 


			}


			function shopifyPurchase()
			{

				$data = array();
				$order = array();


				$line_items = array();
				$line_items[0]['variant_id'] = $this->variantID;
				$line_items[0]['quantity'] = 1;

				$customer = array();
				$customer['id'] = $this->customerID;

				$transactions = array();
				$transactions[0]['kind']   = "Bank Deposit";
				$transactions[0]['status'] = "success";
				$transactions[0]['amount'] = $this->totalPaid;

				$order['line_items']   = $line_items;
				$order['customer']     = $customer;
				$order['transactions'] = $transactions;
				$order['financial_status'] = 'authorized';

				$data['order'] = $order;


				//echo json_encode($data);
                $this->orderDetails = array();

				$apiURL = "https://b2836f581daab99987d3b7c5e1eac1eb:4a15503729dadc8232100ca19c57d05a@marvel-mii.myshopify.com//admin/orders.json";
				$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($data));
				curl_setopt($session, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
				curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);

				$result = curl_exec($session);
				//echo $result;

				//echo $result;

				$details = json_decode($result, true);
				$this->orderDetails = $details['order'];
				curl_close($session);

				$isStore = 0;
				$outletId = '';
				$finalOutletId = '';

				/*foreach($this->orderDetails['note_attributes'] as $attributes) {
					if($attributes['name'] == 'delOption' && $attributes['value'] == 'Store') {
						$isStore = 1;				
					} else if($attributes['name'] == 'storeSelected') {
						$outletId = $attributes['value'];
					}
				}*/
				//echo $this->orderDetails['order_number'];


				if($this->deliveryType==1)
					$isStore = 1;				
				else
				{
					$isStore = 2;				
					$outletId = $this->cmbStore;
				}

		
				if($isStore > 0 && $outletId != '') {
					$finalOutletId = $outletId;
				} else {
					$pincode = $this->orderDetails['customer']['default_address']['zip'];
					if(!empty($pincode)) {

						$stmt  = $this->conn2->prepare("SELECT outlet_id FROM franchise_postcodes WHERE postcode = '$pincode' LIMIT 1");
				        $stmt->execute();
				        $result = $stmt->fetch(PDO::FETCH_ASSOC);
				
						if(!empty($result['outlet_id'])) {
							$finalOutletId = $result['outlet_id'];
						}

						else
							$finalOutletId = $outletId;


					}
				}


				if($finalOutletId != '') {
				$salesOrder = array();
				$orderItems = array();
				$rowNo = 1;
				$totalQuantity = 0;


				foreach($this->orderDetails['line_items'] as $item) {
					$orderItems[] = array('rowNo'=>$rowNo,
						'itemId'=>$item['sku'],
						'itemName'=>$item['title'],
						'itemReferenceCode'=>$item['variant_id'],
						'salePrice'=>$item['price'],
						'quantity'=>$item['quantity'],
						'itemAmount'=>$item['price'],
						'taxPercentage'=>$item['tax_lines'][0]['rate']*100,);

					$totalQuantity += $item['quantity'];    
					$rowNo++;
				}


				$phone = '';
				if(!empty($this->orderDetails['customer']['default_address']['phone'])) {
					$phone = $this->orderDetails['customer']['default_address']['phone'];
				} else if(!empty($this->orderDetails['customer']['phone'])) {
					$phone = $this->orderDetails['customer']['phone'];
				} else {
					$phone = '1234567890';
				}


				$customer = $this->orderDetails['customer'];
				$orderNo = $this->orderDetails['order_number'];

				//echo $orderNo;



				$salesOrder['salesOrder'] = array("onlineReferenceNo"=>$this->orderDetails['order_number'],
							'shippingId'=>$this->orderDetails['order_number'],
							'shippingName'=>$this->orderDetails['customer']['default_address']['name'],
							'shippingAddress1'=>$this->orderDetails['customer']['default_address']['address1'],
							'shippingCountry'=>$this->orderDetails['customer']['default_address']['country'],
							'shippingPincode'=>$this->orderDetails['customer']['default_address']['zip'],
							'shippingMobile'=>$phone,
							'shippingEmail'=>$this->orderDetails['email'],
							'shipmentItems'=>count($this->orderDetails['line_items']),
							'totalTaxAmount'=>$this->orderDetails['total_tax'],
							'totalDiscountAmount'=>$this->orderDetails['total_discounts'],
							'totalAmount'=>$this->orderDetails['total_line_items_price'],
							'totalQuantity'=>$totalQuantity,
							'orderItems'=>$orderItems,
							'outletId'=>$finalOutletId,
							'customerName'=>"$customer[first_name] $customer[last_name]",
							'customerPhone'=>$phone,
							'customerMobile'=>$phone,
							'customerEmail'=>$this->orderDetails['customer']['email']);

				$salesJson = json_encode($salesOrder);




				$curl = curl_init();

				curl_setopt_array($curl, array(
				  CURLOPT_URL => "http://mybooster.true-pos.com/TruePOS/api/v1/salesOrders?mode=new",
				  CURLOPT_RETURNTRANSFER => true,
				  CURLOPT_ENCODING => "",
				  CURLOPT_MAXREDIRS => 10,
				  CURLOPT_TIMEOUT => 30,
				  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				  CURLOPT_CUSTOMREQUEST => "POST",
				  CURLOPT_POSTFIELDS => $salesJson,
				  CURLOPT_HTTPHEADER => array(
					"Accept: application/json",
					"Content-Type: application/json",
					"Postman-Token: 586ee71f-4c9d-47af-a176-07d95e44fe3f",
					"X-Auth-Token: 59B2D9AB5F23F0B583158882F1B2E09B63B98B494B541C44504FE65F9190781F5A9E95755166E523",
					"cache-control: no-cache"
				  ),
				));

				$response = curl_exec($curl);
				$err = curl_error($curl);
				curl_close($curl);
				return true;


			}


   }

	}


	$result = array();

	if(!isset($_REQUEST['memberID']) || $_REQUEST['memberID'] == '') {
		$validationErr = "Please enter a Member ID!";
	}else if(!isset($_REQUEST['customerID']) || $_REQUEST['customerID'] == '') {
		$validationErr = "Please enter a customer id!";
	}else if(!isset($_REQUEST['cmbProduct']) || $_REQUEST['cmbProduct'] == '') {
		$validationErr = "Please select a product to purchase!";
	}/*else if(!isset($_REQUEST['paidByDeposit']) || $_REQUEST['paidByDeposit'] == '') {
		$validationErr = "Please enter an amount paid by deposit!";
	}else if(!isset($_REQUEST['paidByCash']) || $_REQUEST['paidByCash'] == '') {
		$validationErr = "Please enter an amount paid by cash!";
	}else if(!isset($_REQUEST['paidByBBT']) || $_REQUEST['paidByBBT'] == '') {
		$validationErr = "Please enter an amount paid by BBT!";
	}*/else if(!isset($_REQUEST['address']) || $_REQUEST['address'] == '') {
		$validationErr = "Shipping Address Missing!";
	}



	if($validationErr != '') {

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

	} 

	
	
	
	
	$product				= new ProductPurchase();
	$product->memberID		= $_REQUEST['memberID'];
	$product->productID		= $_REQUEST['cmbProduct'];
	//$product->paidByDeposit = $_REQUEST['paidByDeposit'];
	//$product->paidByCash	= $_REQUEST['paidByCash'];
	//$product->paidByBBT		= $_REQUEST['paidByBBT'];
	$product->address	    = htmlentities($_REQUEST['address']);
	$product->variantID	    = $_REQUEST['cmbProduct'];
	$product->deliveryType  = $_REQUEST['deliveryType'];
    $product->quantity      = 1;
	$product->cmbStore      = $_REQUEST['cmbStore'];
	

	if($product->verifyMemberID())
	{
		if($product->verifyProductDetails())
		{
			 if($product->makePurchase())
			 {
				 $result['success'] = true;
		         $result['message'] = "Member Package bought Successfully!";
			 }

			 else
			 {
				 $result['success'] = false;
		         $result['message'] = "Your request failed! Please try after sometime!";
			 }


		}

		else
		{
			$result['success'] = false;
		    $result['message'] = "Improper Product Details. Purchase cannot be processed!";

    	}

	}

	else
	{
		$result['success'] = false;
		$result['message'] = "Member Id doesn't exist!";
	}
 


	echo json_encode($result);


?>

