<?php
//$data = '{"id":889848660083,"email":"sunderkamboj0143@gmail.com","closed_at":null,"created_at":"2018-11-16T20:03:28+05:30","updated_at":"2018-11-16T20:03:28+05:30","number":61,"note":"","token":"388edcd6b0df2610b004322cee8d6246","gateway":"razorpay_all_cards_netbanking_wallets_","test":false,"total_price":"21293.10","subtotal_price":"18045.00","total_weight":0,"total_tax":"3248.10","taxes_included":false,"currency":"INR","financial_status":"paid","confirmed":true,"total_discounts":"17955.00","total_line_items_price":"36000.00","cart_token":"","buyer_accepts_marketing":true,"name":"#1061","referring_site":"","landing_site":"\/","cancelled_at":null,"cancel_reason":null,"total_price_usd":"296.13","checkout_token":"8f34131a455773ac33664ffe428592a0","reference":null,"user_id":null,"location_id":null,"source_identifier":null,"source_url":null,"processed_at":"2018-11-16T20:03:28+05:30","device_id":null,"phone":null,"customer_locale":"en","app_id":580111,"browser_ip":null,"landing_site_ref":null,"order_number":1062,"discount_applications":[{"type":"discount_code","value":"17955.0","value_type":"fixed_amount","allocation_method":"across","target_selection":"all","target_type":"line_item","code":"55F2-2RDT-V51X"}],"discount_codes":[{"code":"55F2-2RDT-V51X","amount":"17955.00","type":"fixed_amount"}],"note_attributes":[{"name":"delOption","value":"Store"},{"name":"storeSelected","value":"225"}],"payment_gateway_names":["razorpay_all_cards_netbanking_wallets_"],"processing_method":"offsite","checkout_id":5121622212723,"source_name":"web","fulfillment_status":null,"tax_lines":[{"price":"3248.10","rate":0.18,"title":"IGST"}],"tags":"","contact_email":"sunderkamboj0143@gmail.com","order_status_url":"https:\/\/mybooster.biz\/5128749171\/orders\/388edcd6b0df2610b004322cee8d6246\/authenticate?key=93cebe345a058bb23b837b6ad10a321d","total_tip_received":"0.0","line_items":[{"id":2021221793907,"variant_id":16902657310835,"title":"Hydrogen Water Generator Bottle (HI-TA 13) (PV : 15000 )","quantity":1,"price":"36000.00","sku":"46","variant_title":"","vendor":"Mybooster","fulfillment_service":"manual","product_id":1711548170355,"requires_shipping":true,"taxable":true,"gift_card":false,"name":"Hydrogen Water Generator Bottle (HI-TA 13) (PV : 15000 )","variant_inventory_management":"shopify","properties":[{"name":"Leg","value":"Left"},{"name":"_ZapietId","value":"eebb072860dc9c18cada673a178192f7"}],"product_exists":true,"fulfillable_quantity":1,"grams":0,"total_discount":"0.00","fulfillment_status":null,"discount_allocations":[{"amount":"17955.00","discount_application_index":0}],"tax_lines":[{"title":"IGST","price":"3248.10","rate":0.18}],"origin_location":{"id":727820599411,"country_code":"IN","province_code":"MH","name":"Mybooster","address1":"64, Rajni, Shivaji Housing Society,","address2":"Off Senapati Bapat Raod","city":"Pune","zip":"411016"}}],"shipping_lines":[{"id":619363991667,"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":"Sushma","address1":"1412, sec 9","phone":null,"city":"Karnal","zip":"132001","province":"Haryana","country":"India","last_name":"Devi","address2":"","company":null,"latitude":29.6386837,"longitude":77.0794705,"name":"Sushma Devi","country_code":"IN","province_code":"HR"},"shipping_address":{"first_name":"Sushma","address1":"1412, sec 9","phone":null,"city":"Karnal","zip":"132001","province":"Haryana","country":"India","last_name":"Devi","address2":"","company":null,"latitude":29.6386837,"longitude":77.0794705,"name":"Sushma Devi","country_code":"IN","province_code":"HR"},"fulfillments":[],"client_details":{"browser_ip":"157.36.129.32","accept_language":"en-US,en;q=0.9","user_agent":"Mozilla\/5.0 (Linux; Android 7.1.2; vivo 1718 Build\/N2G47H) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/62.0.3202.84 Mobile Safari\/537.36","session_hash":"c154770a320150526a7c74267965ef62","browser_width":360,"browser_height":598},"refunds":[],"customer":{"id":1151716819059,"email":"sunderkamboj0143@gmail.com","accepts_marketing":true,"created_at":"2018-11-01T06:31:38+05:30","updated_at":"2018-11-16T20:03:28+05:30","first_name":"Sushma","last_name":"Devi","orders_count":1,"state":"enabled","total_spent":"21293.10","last_order_id":889848660083,"note":null,"verified_email":true,"multipass_identifier":null,"tax_exempt":false,"phone":"+919416209900","tags":"","last_order_name":"#1061","default_address":{"id":1322302111859,"customer_id":1151716819059,"first_name":"Sushma","last_name":"Devi","company":null,"address1":"1412, sec 9","address2":"","city":"Karnal","province":"Haryana","country":"India","zip":"132001","phone":null,"name":"Sushma Devi","province_code":"HR","country_code":"IN","country_name":"India","default":true}}}';

$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 = '';


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 != '') {
$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'=>225,
            '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);
?>