<?php

/* Get MatthewsPaint.tools general configuration settings. */
require_once($_SERVER['DOCUMENT_ROOT']."/Configuration.class.php");
$Settings = new Configuration();

/* If validating the input actually came from Shopify, use the "secret" key. */
define('SHOPIFY_APP_SECRET', 'ea6c3b08907e9cf2e6ff7774daa66ea80e0963fb3b7cd3ec0b9983eff991f08c');

/* Read the contents of the input stream. */
$data = '{"id":637638180950,"email":"mcirisheyes@hotmail.com","closed_at":null,"created_at":"2018-11-10T12:23:23-06:00","updated_at":"2018-11-10T12:23:29-06:00","number":634,"note":"Merry Christmas!","token":"31073305bcb3fda28d2237ac773b2b03","gateway":"shopify_payments","test":false,"total_price":"35.00","subtotal_price":"35.00","total_weight":680,"total_tax":"0.00","taxes_included":false,"currency":"USD","financial_status":"paid","confirmed":true,"total_discounts":"0.00","total_line_items_price":"35.00","cart_token":"6175ed8ee02506d72438064d334305e7","buyer_accepts_marketing":true,"name":"#1S1634TEST","referring_site":"http:\/\/www.1shot.com\/One-Shot\/Products.aspx","landing_site":"\/","cancelled_at":null,"cancel_reason":null,"total_price_usd":"35.00","checkout_token":"be037d1058489c3a993ac311526b64b1","reference":null,"user_id":null,"location_id":null,"source_identifier":null,"source_url":null,"processed_at":"2018-11-10T12:23:23-06:00","device_id":null,"phone":null,"customer_locale":"en","app_id":580111,"browser_ip":"174.227.15.195","landing_site_ref":null,"order_number":1634,"discount_applications":[],"discount_codes":[],"note_attributes":[],"payment_gateway_names":["shopify_payments"],"processing_method":"direct","checkout_id":7141221335126,"source_name":"web","fulfillment_status":null,"tax_lines":[],"tags":"","contact_email":"mcirisheyes@hotmail.com","order_status_url":"https:\/\/1shotstore.com\/9863424\/orders\/31073305bcb3fda28d2237ac773b2b03\/authenticate?key=b3e08ae31a933cfde716adcf9f058c9e","total_tip_received":"0.0","line_items":[{"id":1543710605398,"variant_id":16406152644,"title":"1 Shot Mug and Black \"Old Skool\" Tee Package","quantity":1,"price":"35.00","sku":"MUGTEE01-L","variant_title":"Large","vendor":"Official 1 Shot Merchandise Store, by GS Marketing Group","fulfillment_service":"gs-marketing-group","product_id":4518292932,"requires_shipping":true,"taxable":true,"gift_card":false,"name":"1 Shot Mug and Black \"Old Skool\" Tee Package - Large","variant_inventory_management":null,"properties":[],"product_exists":true,"fulfillable_quantity":1,"grams":680,"total_discount":"0.00","fulfillment_status":null,"discount_allocations":[],"tax_lines":[],"origin_location":{"id":3681782276,"country_code":"US","province_code":"WI","name":"Official 1 Shot Merchandise Store, by GS Marketing Group","address1":"5900 77th Street","address2":"","city":"Kenosha","zip":"53142-4110"}}],"shipping_lines":[{"id":537552322646,"title":"Shipping Included (Free)","price":"0.00","code":"Shipping Included (Free)","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":"Mary","address1":"1350 75th ave ne","phone":"","city":"Fridley","zip":"55432","province":"Minnesota","country":"United States","last_name":"Campbell","address2":"","company":"","latitude":45.1038904,"longitude":-93.23697759999999,"name":"Mary Campbell","country_code":"US","province_code":"MN"},"shipping_address":{"first_name":"Mary ","address1":"2008 Polaris ","phone":"(612) 644-9396","city":"North St Paul","zip":"55109","province":"Minnesota","country":"United States","last_name":"Campbell","address2":"","company":"","latitude":45.0155505,"longitude":-93.0435224,"name":"Mary  Campbell","country_code":"US","province_code":"MN"},"fulfillments":[],"client_details":{"browser_ip":"174.227.15.195","accept_language":"en-US,en;q=0.9","user_agent":"Mozilla\/5.0 (Linux; Android 8.0.0; VS996) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.80 Mobile Safari\/537.36","session_hash":null,"browser_width":720,"browser_height":280},"refunds":[],"payment_details":{"credit_card_bin":"557634","avs_result_code":"Y","cvv_result_code":"M","credit_card_number":"•••• •••• •••• 6045","credit_card_company":"Mastercard"},"customer":{"id":849460363350,"email":"mcirisheyes@hotmail.com","accepts_marketing":true,"created_at":"2018-11-10T12:19:04-06:00","updated_at":"2018-11-10T12:23:23-06:00","first_name":"Mary","last_name":"Campbell","orders_count":1,"state":"disabled","total_spent":"35.00","last_order_id":637638180950,"note":null,"verified_email":true,"multipass_identifier":null,"tax_exempt":false,"phone":null,"tags":"","last_order_name":"#1S1634","default_address":{"id":965179310166,"customer_id":849460363350,"first_name":"Mary ","last_name":"Campbell","company":"","address1":"2008 Polaris ","address2":"","city":"North St Paul","province":"Minnesota","country":"United States","zip":"55109","phone":"(612) 644-9396","name":"Mary  Campbell","province_code":"MN","country_code":"US","country_name":"United States","default":true}}}';

try {
	
	if (is_string($data)) {
		
		/* Create a PHP object from JSON. */
		$Order = json_decode(utf8_encode($data), FALSE);
		
		/* Calculate derived values like the Shopify fee. */
		if ((1*$Order->{'total_price'}) > 0) {
			$fee = round(0.029*$Order->{'total_price'}, 2, PHP_ROUND_HALF_UP) + 0.30; // 2.9% of Total Sale + $0.30
		}
		
		/* Calculate shipping upcharge as sum of "shipping_lines" ietms. */
		$upcharge = 0;
		foreach($Order->{'shipping_lines'} as $Line) {
			$upcharge += $Line->{'price'};
		}
		
		/* Format a message for publishing to a dedicated Slack channel. */
		$payload = '{"channel": "#1shotstore", "username": "shopifybot", "text": "<http://1shotstore.com/admin/orders/{{id}}|New Order {{name}}>: ${{total_price}}\n>>>Contact: {{customer_name}}, {{customer_email}}\nShip to: {{recipient_name}}, {{ship_city}} {{ship_state}}, {{ship_country}}{{note}}", "icon_url": "https://cdn.shopify.com/shopify-marketing_assets/static/shopify-favicon.png"}';
		$payload = str_replace(
			array('{{id}}', '{{name}}', '{{total_price}}', '{{customer_name}}', '{{customer_email}}', '{{recipient_name}}', '{{ship_city}}', '{{ship_state}}', '{{ship_country}}', '{{note}}'),
			array($Order->{'id'}, trim($Order->{'name'}), $Order->{'total_price'}, trim(preg_replace("/\s{2,}/", " ", $Order->{'billing_address'}->{'name'})), $Order->{'contact_email'}, trim(preg_replace("/\s{2,}/", " ", $Order->{'shipping_address'}->{'name'})), trim(preg_replace("/\s{2,}/", " ", $Order->{'shipping_address'}->{'city'})), trim($Order->{'shipping_address'}->{'province_code'}), trim($Order->{'shipping_address'}->{'country'}), (empty($Order->{'note'}) ? "" : "\nNote: ".trim($Order->{'note'}))),
			$payload);
		
		/* Connect to Slack and push the message. */
		$Socket = curl_init();
		
		curl_setopt($Socket, CURLOPT_URL, "https://hooks.slack.com/services/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");
		curl_setopt($Socket, CURLOPT_POST, TRUE);
		curl_setopt($Socket, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($Socket, CURLOPT_POSTFIELDS, $payload);
		$response = curl_exec($Socket);
		curl_close($Socket);
		
		unset($Socket);
        
        $entry = '{"payload": ' . $payload . ', "status": "' . $response . '"}' . "\n";
		
		file_put_contents($_SERVER['DOCUMENT_ROOT'].'/shopify/slack.log', $entry, FILE_APPEND);
		
	}
	
} catch (PDOException $Oops) {
	//exit($Oops->getMessage());
} catch (Exception $Oops) {
	//exit($Oops->getMessage());
}

?>