<?php
require_once("../../config/connect.php");
require_once("../../config/sIT_global_db_functions.php");



$timestamp = time();
$datum = date("d.m.Y - H:i", $timestamp);

echo "____________________ 658 Orders _____________________<br>";

echo "____________________ Start Zeit _____________________<br>";
echo $datum;
echo "____________________ ENDE Start Zeit _____________________<br>";



$orders_count = get_table_api_shopify_url2("orders/count.json?tag=any&status=refund");
var_dump($orders_count);

$orders = get_table_api_shopify_url2("orders.json?created_at_max=2023-07-31&tag=filiale&status=any&limit=5");
//$orders = get_table_api_shopify_url("orders.json?tag=filiale&status=any&limit=10","orders");
//var_dump($orders);

$url = FILIALSYSTEM_URL_ZENTRALSYSTEM;
foreach ($orders['orders'] as $order) {

        $strorderurl = "orders/" . $order['id'] . ".json";
        $strurl = $url . $strorderurl;
        echo "URL: ".$strurl."<br>";
        echo "Order Name: ".$order['name']. ", Order ID: ".$order['id']. ", Tag: ". $order['tags'].", Note: ".$order['note']."<br><br>";
        //var_dump($order);
        
        
      // delete_table_api_shopify_url($strurl);
}

$timestamp2 = time();
$datum2 = date("d.m.Y - H:i", $timestamp2);

echo "____________________ End Zeit _____________________<br>";
echo $datum2;
echo "____________________ ENDE End Zeit _____________________<br>";


function delete_table_api_shopify_url($url)
{
        $token = FILIALSYSTEM_TOKEN;
        ini_set('max_execution_time', -1);
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt( $ch, CURLOPT_POST, 1 ); 
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json",
                "X-Shopify-Access-Token: $token"
        ));

        $response = curl_exec($ch);
        if ($response === false) echo 'Curl-Fehler: ' . curl_error($ch);
        //$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        curl_close($ch);

        echo "<pre>";
        print_r($response);
        echo "</pre>";
}

function get_table_api_shopify_url2($strurl)
{
        try {
                $url = FILIALSYSTEM_URL_ZENTRALSYSTEM;
                $token = FILIALSYSTEM_TOKEN;

                $url .= $strurl;

                $ch = curl_init();

                echo $url . "<br>";
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                //curl_setopt( $ch, CURLOPT_POST, 1 );
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                curl_setopt($ch, CURLOPT_HEADER, TRUE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                $header = [
                        "Content-Type:application/json",
                        "X-Shopify-Access-Token:$token"
                ];
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                $response = curl_exec($ch);
                if ($response === false) echo 'Curl-Fehler: ' . curl_error($ch);
                $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
                curl_close($ch);
                $header = substr($response, 0, $header_size);
                $body = substr($response, $header_size);
                //echo "-->";
                //var_dump(json_decode($body, true));
                //echo "<--";


                return json_decode($body, true);
        } catch (Exception $e) {
                echo 'Exception abgefangen: ',  $e->getMessage(), "<br>";
        }
}
function get_object_shopify($parsedResponse, $object_shopify)
{
        switch ($object_shopify) {
                case "products":
                        $result = $parsedResponse['products'];
                        break;
                case "collects":
                        $result = $parsedResponse['collects'];
                        break;
                case "collection":
                        $result = $parsedResponse['collection'];
                        break;
                case "variants":
                        $result = $parsedResponse['variants'];
                        break;
                case "metafields":
                        $result = $parsedResponse['metafields'];
                        break;
                case "order":
                        $result = $parsedResponse['order'];
                        break;
                case "orders":
                        $result = $parsedResponse['orders'];
                        break;
                case "fulfillment_orders":
                        $result = $parsedResponse['fulfillment_orders'];
                        break;
                case "fulfillment":
                        $result = $parsedResponse['fulfillment'];
                        break;


                default:
                        $result =  $parsedResponse;
        }

        return $result;
}



function get_table_api_shopify_url($strurl, $object_shopify = null)
{



        $token = FILIALSYSTEM_TOKEN;
        $url = FILIALSYSTEM_URL_ZENTRALSYSTEM;
        $nextPage = NULL;
        $url .= $strurl;
        $curl = curl_init();
        echo "<br>" . $url . "<br>";
        // set result limit and Basic auth

        curl_setopt_array(
                $curl,
                array(
                        CURLOPT_URL => $url,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => "",
                        CURLOPT_CUSTOMREQUEST => "GET",
                        CURLOPT_SSL_VERIFYHOST => 0,
                        CURLOPT_SSL_VERIFYPEER => 0,
                        CURLOPT_HTTPHEADER => array(
                                "Content-Type: application/json",
                                "X-Shopify-Access-Token: $token"
                        )
                )
        );

        // call back function to parse Headers and get Next Page Link
        curl_setopt(
                $curl,
                CURLOPT_HEADERFUNCTION,
                function ($curl, $header) use (&$nextPage) {
                        $len = strlen($header);
                        $header = explode(':', $header, 2);

                        if (count($header) < 2) // ignore invalid headers
                                return $len;

                        if (trim($header[0]) === "Link" && strpos($header[1], 'next') !== false) {
                                $links = explode(',', $header[1], 2);

                                $link = count($links) === 2 ? $links[1] : $links[0];
                                if (preg_match('/<(.*?)>/', $link, $match) === 1) $nextPage = $match[1];
                        }

                        return $len;
                }
        );

        // First request
        $response = curl_exec($curl);

        if (curl_errno($curl)) {
                $error_msg = curl_error($curl);
                print_r($error_msg);
        }
        $parsedResponse = json_decode($response, true);

        $result = null;

        if (!is_null($object_shopify))
                $result = get_object_shopify($parsedResponse, $object_shopify);


        // generate new requests till next page is available

        while ($nextPage !== NULL) {
                curl_setopt($curl, CURLOPT_URL, $nextPage);

                $result = get_object_shopify($parsedResponse, $object_shopify);

                //$parsedResponse->$object_shopify = [];
                $nextPage = NULL;

                $response = curl_exec($curl);
                $parsedResponse = json_decode($response, true);

                if (curl_errno($curl)) {
                        $error_msg = curl_error($curl);
                } else {

                        $result = get_object_shopify($parsedResponse, $object_shopify);

                        //$result = array_merge($result, $parsedResponse->$object_shopify);
                        sleep(2);
                }
        };

        curl_close($curl);

        return  $result;
}
