<?php
  header("Expires: 0");
  header("Last-Modified: " . date("D, d M Y H:i:s e"));
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");
?>
<?php
  echo "<h1>CHECK THE TIME: " . date("D, d M Y H:i:s e") . "</h1>";
?>
<?php
    #==========================================================================#
    # CONSTANTS FOR CONFIGURATION                                              #
    #==========================================================================#
	define("DATABASE_NAME"  , "sewing_so");
	define("MYSQL_USERNAME" , "sewing_so");
	define("MYSQL_PASSWORD" , "Gr33n3y3Y#rk!p##");
	
/****************************************************************************************
GMI Order Processing 2016 Application Integration KEYS
*****************************************************************************************
    define("APP_ID"         , "defd4fdl2r7uhwx8lp2k00d7t7szdljj");
    define("SHARED_SECRET"  , "hJ1av2CgcEO4y8BFFYUv2w");
    define("REFRESH_TOKEN"  , "WWxsfV7u1pnx_Y95XbTTI5ULyjQw2slA0EoVv6R1vDo");
****************************************************************************************/

/****************************************************************************************
GMI Order Processing 2020 Application Integration KEYS
*****************************************************************************************
    define("APP_ID"         , "zz5ymx8lgwzm3rirqfg78bzmzji8w7qn");
    define("SHARED_SECRET"  , "frbk0CJyWk-VpDqoISDvcg");
    define("REFRESH_TOKEN"  , "UNuSqY31Z55cN2gNjLi0SsIuiBMc624jR6R-ZbkkRa0");
    define("ACCESS_TOKEN"   , "fz_CpFIGBMrA4Bxh-WmO8pR6iw8U9bhucIFJHmKsrA0-35348");
****************************************************************************************/

/****************************************************************************************
CA Get Orders Application Integration KEYS
****************************************************************************************/
#	define("CA_API_ENDPOINT",       "ciphertest-api.channeladvisor.com"               );
	define("CA_API_ENDPOINT",       "api.channeladvisor.com"                 		  );

    define("APP_ID"         , "9tybjzkwh1o51xn47ujsnp2qii0nk8hw");
    define("SHARED_SECRET"  , "5UUWE4vXckGLkig-u4EY9g");
    define("REFRESH_TOKEN"  , "rvRdhrqQkO87prp8upr2pcBEAF51gip1LCONRa3-dbQ");
    define("ACCESS_TOKEN"   , "hw24EemIvbF3f2JXBQGX-dhA-KbBT3OL9zqSqEyzT1Q-38102"); # This token expires 11/25/2020 10:59:21
/***************************************************************************************/


    define("ACCOUNT_NAME"   , "General Merchandise International Limited - UK");
    #==========================================================================#

    #==========================================================================#
    # FUNCTIONS FOR CHANNEL ADVISOR API CALLS                                  #
    #==========================================================================#
    function ca_REST                   ($url,$application_id,$shared_secret,$fields=false) { 
        $encoded_secret=base64_encode($application_id.':'.$shared_secret);
        $headers = [
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: Basic '.$encoded_secret
        ];
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,trim($url));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_POST,count($fields));
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($fields));
        curl_setopt($ch,CURLOPT_TIMEOUT,5);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($ch,CURLOPT_HTTPGET,false);
        curl_setopt($ch,CURLOPT_HEADER,false);
        curl_setopt($ch,CURLINFO_HEADER_OUT,true);
        curl_setopt($ch,CURLOPT_VERBOSE,true);
        curl_setopt($ch,CURLOPT_STDERR,$verbose=fopen('php://temp','rw+'));
        $result=curl_exec($ch);
        $error=curl_error($ch);
        curl_close($ch);
        if ($error) { var_dump($error); return false; }
        return $result;
    }
    function ca_api_CALL               ($url,$options) { 
        return json_decode(
            file_get_contents(
                $url,
                false,
                stream_context_create($options)
            )
        );
    }
    function ca_api_GET                ($url,$access_token) { 
        return ca_api_CALL(
            $url,
            array(
              'http' => array(
                'method'=>'GET',
                'header'=>"Authorization: bearer ".$access_token."\r\n"
                )
            )
        );
    }
    function ca_api_POST               ($url,$data,$access_token) { 
        return ca_api_CALL(
            $url,
            array(
                'http' => array(
                    'method' =>'POST',
                    'content'=>json_encode($data),
                    'header' =>"Authorization: bearer ".$access_token."\r\n".
                               "Content-Type: application/json\r\n".
                               "Accept: application/json\r\n"
                )
            )
        );
    }
    function ca_api_get_token          ($application_id,$shared_secret,$refresh_token) { 
        $fields = [
            'grant_type'    => 'refresh_token',
            'refresh_token' => $refresh_token 
        ];
        $url="https://".CA_API_ENDPOINT."/oauth2/token";
        $access_token=ca_REST($url,$application_id,$shared_secret,$fields);
        if($access_token===false) return false;
        return json_decode($access_token,true)["access_token"];
    }
    function ca_api_get_profile_id     ($account_name,$access_token) { 
        $url="https://".CA_API_ENDPOINT."/v1/Profiles";
        $result=ca_api_GET($url,$access_token);
/*
?><pre><?php
print_r($result);
?></pre><?php
exit();
*/		
        foreach($result->value AS $profile) { 
            if($profile->AccountName==$account_name)
                return $profile->ID;
        }
        return null;
    }
    function ca_api_get_cleared_orders ($access_token,  $not_managed_by,  $payed_after_date,  $payed_before_date,  $flag_id,  $profile_id) {
        
		$payment_status    = "PaymentStatus eq 'Cleared'";
		$not_managed_by    = $not_managed_by    ? " and DistributionCenterTypeRollup ne '" . $not_managed_by . "'" : ""; // SellerManaged | ExternallyManaged | Mixed
		$payed_after_date  = $payed_after_date  ? " and PaymentDateUtc ge  " . $payed_after_date  . ""  : "";
		$payed_before_date = $payed_before_date ? " and PaymentDateUtc le  " . $payed_before_date . ""  : "";
		$flag_id           = $flag_id           ? " and FlagID eq  " . $flag_id . ""  : "";
        $profile_id        = $profile_id        ? " and ProfileID eq  " . $profile_id . ""  : "";

        $url="https://".CA_API_ENDPOINT."/v1/Orders"."?\$filter=".urlencode($payment_status.$not_managed_by.$payed_after_date.$payed_before_date.$flag_id.$profile_id)."&\$expand=".urlencode("Items(\$expand=FulfillmentItems,Promotions,Adjustments,BundleComponents),Fulfillments(\$expand=Items),Adjustments,CustomFields")."&\$orderby=".urlencode("PaymentDateUtc asc");

##########################
/*
echo "<p>".$url."</p>";
exit();
*/
##########################

        while($url!=null && $url!="") {
            if(!($result = ca_api_GET($url,$access_token)) || !is_array($result->value)) break;
			
			
			/*
			Bodge because CA doesnt report UK FBA Shipping including the Shipping TAX
			*/
			if(DistributionCenterTypeRollup=="ExternallyManaged" && SiteName=="Amazon UK") {
				$result->value->TotalShippingPrice+=$result->value->TotalShippingTaxPrice;
			}

			
            $orders      = (is_array($orders) ? array_merge($orders,$result->value) : $result->value);
            $url         = get_object_vars($result)['@odata.nextLink'];
        }

##########################
/*
?><pre><?php
print_r($orders);
?><pre><?php
exit();
*/
##########################

        return $orders;
    }
    function save_ca_orders            ($mysqli,$orders) {


        foreach($orders AS $order) {
			/*?><pre><?php print_r($order); ?></pre><?php*/		
			$PaymentDateUtc = explode(".",$order->PaymentDateUtc);	if(is_array($PaymentDateUtc)) $order->PaymentDateUtc=$PaymentDateUtc[0];
			$PaymentDateUtc = explode("Z",$order->PaymentDateUtc);	if(is_array($PaymentDateUtc)) $order->PaymentDateUtc=$PaymentDateUtc[0];
			$sql = "INSERT INTO __ca_orders SET ID='".addslashes($order->ID)."', DistributionCenterTypeRollup='".addslashes($order->DistributionCenterTypeRollup)."', OrderTags='".addslashes($order->OrderTags)."', FlagID='".addslashes($order->FlagID)."', FlagDescription='".addslashes($order->FlagDescription)."', CheckoutStatus='".addslashes($order->CheckoutStatus)."', PaymentStatus='".addslashes($order->PaymentStatus)."', ShippingStatus='".addslashes($order->ShippingStatus)."', PaymentDateUtc='".addslashes($order->PaymentDateUtc)."', SiteName='".addslashes($order->SiteName)."', SiteOrderID='".addslashes($order->SiteOrderID)."', SecondarySiteOrderID='".addslashes($order->SecondarySiteOrderID)."', PaymentMethod='".addslashes($order->PaymentMethod)."', SpecialInstructions='".addslashes($order->SpecialInstructions)."', TotalTaxPrice='".addslashes($order->TotalTaxPrice)."', TotalShippingPrice='".addslashes($order->TotalShippingPrice)."', TotalShippingTaxPrice='".addslashes($order->TotalShippingTaxPrice)."', TotalInsurancePrice='".addslashes($order->TotalInsurancePrice)."', AdditionalCostOrDiscount='".addslashes($order->AdditionalCostOrDiscount)."', TotalPrice='".addslashes($order->TotalPrice)."', BuyerUserId='".addslashes($order->BuyerUserId)."', BuyerEmailAddress='".addslashes($order->BuyerEmailAddress)."', BillingTitle='".addslashes($order->BillingTitle)."', BillingFirstName='".addslashes($order->BillingFirstName)."', BillingLastName='".addslashes($order->BillingLastName)."', BillingSuffix='".addslashes($order->BillingSuffix)."', BillingCompanyJobTitle='".addslashes($order->BillingCompanyJobTitle)."', BillingCompanyName='".addslashes($order->BillingCompanyName)."', BillingAddressLine1='".addslashes($order->BillingAddressLine1)."', BillingAddressLine2='".addslashes($order->BillingAddressLine2)."', BillingCity='".addslashes($order->BillingCity)."', BillingStateOrProvinceName='".addslashes($order->BillingStateOrProvinceName)."', BillingPostalCode='".addslashes($order->BillingPostalCode)."', BillingCountry='".addslashes($order->BillingCountry)."', BillingDaytimePhone='".addslashes($order->BillingDaytimePhone)."', BillingEveningPhone='".addslashes($order->BillingEveningPhone)."', ShippingTitle='".addslashes($order->ShippingTitle)."', ShippingFirstName='".addslashes($order->ShippingFirstName)."', ShippingLastName='".addslashes($order->ShippingLastName)."', ShippingSuffix='".addslashes($order->ShippingSuffix)."', ShippingCompanyJobTitle='".addslashes($order->ShippingCompanyJobTitle)."', ShippingCompanyName='".addslashes($order->ShippingCompanyName)."', ShippingAddressLine1='".addslashes($order->ShippingAddressLine1)."', ShippingAddressLine2='".addslashes($order->ShippingAddressLine2)."', ShippingCity='".addslashes($order->ShippingCity)."', ShippingStateOrProvinceName='".addslashes($order->ShippingStateOrProvinceName)."', ShippingPostalCode='".addslashes($order->ShippingPostalCode)."', ShippingCountry='".addslashes($order->ShippingCountry)."', ShippingDaytimePhone='".addslashes($order->ShippingDaytimePhone)."', ShippingEveningPhone='".addslashes($order->ShippingEveningPhone)."', PrivateNotes='".addslashes($order->PrivateNotes)."'";
			/*$insert_order_result = $mysqli->query($sql);*/
			?><pre style="color:<?=($mysqli->error?"red":"black")?>"><?php print_r($sql); ?></pre><?php

            foreach($order->Items AS $item) {
                $sql = "INSERT INTO __ca_order_items SET ID = '".addslashes($item->ID)."', OrderID = '".addslashes($item->OrderID)."', Sku = '".addslashes($item->Sku)."', Title = '".addslashes($item->Title)."', Quantity = '".addslashes($item->Quantity)."', UnitPrice = '".addslashes($item->UnitPrice)."', GiftPrice = '".addslashes($item->GiftPrice)."', GiftTaxPrice = '".addslashes($item->GiftTaxPrice)."', ShippingPrice = '".addslashes($item->ShippingPrice)."', ShippingTaxPrice = '".addslashes($item->ShippingTaxPrice)."', TaxPrice = '".addslashes($item->TaxPrice)."'";
				/*$insert_order_item_result = $mysqli->query($sql);*/
				?><pre style="color:<?=($mysqli->error?"red":"black")?>"><?php print_r($sql); ?></pre><?php

                foreach($item->FulfillmentItems AS $fulfillmentitem) { 
                    $sql = "INSERT INTO __ca_order_item_fulfillmentitems SET ID = '".addslashes($fulfillmentitem->ID)."', OrderID = '".addslashes($fulfillmentitem->OrderID)."', FulfillmentID = '".addslashes($fulfillmentitem->FulfillmentID)."', OrderItemID = '".addslashes($fulfillmentitem->OrderItemID)."', Quantity = '".addslashes($fulfillmentitem->Quantity)."'";
					/*$insert_order_item_result = $mysqli->query($sql);*/
					?><pre style="color:<?=($mysqli->error?"red":"black")?>"><?php print_r($sql); ?></pre><?php
                } 
            }
            foreach($order->Fulfillments AS $fulfillment) {
                $sql = "INSERT INTO __ca_order_fulfillments SET ID = '".addslashes($fulfillment->ID)."', OrderID = '".addslashes($fulfillment->OrderID)."', DistributionCenterID = '".addslashes($fulfillment->DistributionCenterID)."', ShippingClass = '".addslashes($fulfillment->ShippingClass)."'";
				/*$insert_order_item_result = $mysqli->query($sql);*/
				?><pre style="color:<?=($mysqli->error?"red":"black")?>"><?php print_r($sql); ?></pre><?php
            }

continue;

        }
    }
    #==========================================================================#

    #==========================================================================#
    # CONNECT TO DATABASE                                                      #
    #==========================================================================#
	$mysqli = new mysqli('localhost', MYSQL_USERNAME, MYSQL_PASSWORD, DATABASE_NAME);
	if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }
    #==========================================================================#

    #==========================================================================#
    # CHANNEL ADVISOR API SETUP                                                #
    #==========================================================================#
#	$access_token = ACCESS_TOKEN;
    $access_token = ca_api_get_token      (APP_ID,SHARED_SECRET,REFRESH_TOKEN);

    $profile_id   = ca_api_get_profile_id (ACCOUNT_NAME,$access_token);
    #==========================================================================#

    #==========================================================================#
    # RETRIEVE ORDERS FROM CA API & SAVE TO DATABASE                           #
    #==========================================================================#
/*
save_ca_orders ($mysqli,($orders=ca_api_get_cleared_orders( $access_token,  "",  "2019-03-01",  "2019-03-11",  "",  ca_api_get_profile_id ("GMI Limited NZ",$access_token)))); 
exit();
*/
/*
save_ca_orders ($mysqli,($orders=ca_api_get_cleared_orders( $access_token,  "",  "2020-06-14",  "2020-06-15", "",  "")));
exit();
*/
/*
save_ca_orders ($mysqli,($orders=ca_api_get_cleared_orders( $access_token,  "",  "2020-06-01",  "2020-06-27", "",  ca_api_get_profile_id ("GMI Limited NL",$access_token))));
exit();
*/

save_ca_orders ($mysqli,($orders=ca_api_get_cleared_orders( $access_token,  "",   "2022-10-21",  "2022-10-23",            "",  "")));
exit();


save_ca_orders ($mysqli,($orders=ca_api_get_cleared_orders( $access_token,  "",   date("Y-m-d",strtotime('yesterday')),  "",            "",  "")));
exit();
    #==========================================================================#
?>
