<?php
//http://10.1.1.41/DT_Fetch/checkZeros.php
// This script checks the Zeros folder for files that are 0 bytes in size, and then re-fetches them from DispatchTrack.  
// This was necessary because sometimes the xml files were not written completely, and they end up being 0 bytes in size, but probably isn't necessary.
// It will also insert the filename into the filesTracker table in the database, so that the file will not be re-fetched again.


require_once("dt_sql_config.php"); // database connection config.
$urlToPost = "https://fam.dispatchtrack.com/orders/api/export.xml?code=fam&api_key=7ezkktmf1pzmvos9";

$fileArr = preg_grep('/^([^.])/',scandir('Zeros')); //load filenames into array, filter out anything starting with a dot
$calls = 0; //accumulator for api calls so we don't go over 40

foreach ($fileArr as $file) {
    if(filesize('Zeros/'.$file) == 0){
        //if( $calls < 40 ){
            //get the remote xml file again, write it locally, and increment the api call counter
            $dateToSearch = "&date=".urlencode(substr($file,0,10));
            $url = $urlToPost.$dateToSearch;
            echo 'Fetching: '.$url."<br>";
    
            $xml = file_get_contents($url); // fetch the xml file from DispatchTrack
            if(!empty($xml)){
                file_put_contents("DTHistoryNew/".$file, $xml); // xml file is saved.

                //code to fetch images
                $response = simplexml_load_file("DTHistoryNew/".$file); //create simplexml object so we can parse it
                foreach ($response->service_order as $soInfo) {
                    if($soInfo->images['count'] > 0){
                        $order_number = $soInfo['order_number'];
                        foreach ($soInfo->images->image as $image) {
                            $imageURL = $image['src'];
                            $imageName = $image['name'];
                            $img = file_get_contents($imageURL);
                            file_put_contents("DTImages/".$order_number."_".$imageName.".jpg", $img);
                        }
                    }
                }
                $sql = "INSERT INTO dispatch.filesTracker (`filename`) VALUES ('".$file."')";
                mysqli_query($db1, $sql);
            }else{
                echo 'Error: xml variable was empty!<br>';
            }
            $calls++;
        //}
    }
}
echo 'Calls variable was incremented '.$calls.' times.';

?>
