<?php
require_once('dbconnect.php');

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

$myfile = file_put_contents('data.txt', $data.PHP_EOL , FILE_APPEND | LOCK_EX);
$orderDetails = json_decode($data,true);
respondOK();

function respondOK($text = null) {
	// check if fastcgi_finish_request is callable
	if(is_callable('fastcgi_finish_request')) {
		if($text !== null) {
		echo $text;
		}
		/*
		 * http://stackoverflow.com/a/38918192
		 * This works in Nginx but the next approach not
		 */
		session_write_close();
		fastcgi_finish_request();

		return;
	}

	ignore_user_abort(true);

	ob_start();

	if($text !== null) {
		echo $text;
	}

	$serverProtocol = filter_input(INPUT_SERVER, 'SERVER_PROTOCOL', FILTER_SANITIZE_STRING);
	header($serverProtocol . ' 200 OK');
	// Disable compression (in case content length is compressed).
	header('Content-Encoding: none');
	header('Content-Length: ' . ob_get_length());

	// Close the connection.
	header('Connection: close');

	ob_end_flush();
	ob_flush();
	flush();
}

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

foreach($orderDetails['note_attributes'] as $attributes) {
	if($attributes['name'] == 'delOption' && $attributes['value'] == 'Store') {
		$isStore = 1;				
	} else if($attributes['name'] == 'storeSelected') {
		$outletId = $attributes['value'];
	}
}

if($isStore > 0 && $outletId != '') {
	$finalOutletId = $outletId;
} else {
	$pincode = $orderDetails['shipping_address']['zip'];
	if(!empty($pincode)) {
		$sql = "SELECT outlet_id FROM franchise_postcodes WHERE postcode = '$pincode' LIMIT 1";
		$result = $conn->query($sql);
		$result = $result->fetch_array();
		
		if(!empty($result['outlet_id'])) {
			$finalOutletId = $result['outlet_id'];
		}
	}
}


if($finalOutletId != '') {
$salesOrder = array();

$orderItems = array();
$rowNo = 1;
$totalQuantity = 0; 
foreach($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($orderDetails['shipping_address']['phone'])) {
    $phone = $orderDetails['shipping_address']['phone'];
} else if(!empty($orderDetails['customer']['phone'])) {
    $phone = $orderDetails['customer']['phone'];
} else {
    $phone = '1234567890';
}

$customer = $orderDetails['customer'];
$orderNo = $orderDetails['order_number'];

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

if ($err) {
  $message = "cURL Error #:" . $err;
} else {
  $responseArray = json_decode($response,true);
  if($responseArray['result']['status'] == 'success') {
      $message = 'Success - '.$responseArray['result']['id'];
  } else {
      $message = 'Error - '.$responseArray['error']['desc'];
  }
}
} else {
    $message = 'Not a store order';
}

$myfile = file_put_contents('data.txt', $message.PHP_EOL , FILE_APPEND | LOCK_EX);

$lineBreak = '=======================================================================================';
$myfile = file_put_contents('data.txt', $lineBreak.PHP_EOL , FILE_APPEND | LOCK_EX);
?>