<?php
//This script will fetch the xml files from DispatchTrack and save them to the server

require_once("dt_sql_config.php"); // database connection config.
$urlToPost = "https://fam.dispatchtrack.com/orders/api/export.xml?code=fam&api_key=7ezkktmf1pzmvos9";
  
//get or set a date range to fetch
$sql = "SELECT MAX(lastdate) as lastdate FROM dispatch.dateTracker";
$result = mysqli_query($db1, $sql);
$row = mysqli_fetch_assoc($result);
if( $row['lastdate'] !== NULL ){
    $begin = new DateTime($row['lastdate']);
}else{
    $begin = new DateTime('2012-09-01'); // this should only be needed for the first run.
}
$varB = clone $begin; //create secondary variable so we don't change the value with the date-add we're about to do.
// add only 40 days because we have an API call limit per hour.
$end = date_add($varB, date_interval_create_from_date_string('40 days'));
$varE = clone $end;

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

//record the last date we fetched
$recDate = $varE->format('Y-m-d'); //convert to string so we can write it to database
$sql = "INSERT INTO dispatch.dateTracker (`lastdate`) VALUES ('".$recDate."')";
mysqli_query($db1, $sql);

if($recDate <= '2022-03-10'){  //this is the last date we want to fetch in case you have to manually start this script again.
    foreach ($period as $dt) {
        // stringify and urlencode the date to search for
        $dateToSearch = "&date=".urlencode($dt->format("Y-m-d"));
            
        $url = $urlToPost.$dateToSearch;
    
        $xml = file_get_contents($url); // fetch the xml file from DispatchTrack
        file_put_contents("DTHistoryNew/".$dt->format("Y-m-d").".xml", $xml); // xml file is saved.  
    
        //code to fetch images, experimental
        $response = simplexml_load_file("DTHistoryNew/".$dt->format("Y-m-d").".xml"); //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);
                }
            }
        }
    }
}

?>
