<?php

// online to offline
include 'autoload.smart.php';
//
$online_url = SMARTDINER_SYNC_URL;
$current_url = SITE_LINK;
if (empty($online_url))
    die("No Online Sync. URL!");
//
$db = DBConnectorFactory::loadDriver();

//we use this not file_get_contents directly as some servers/hosting not allow, it return
//failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request | it need header send
function my_get_contents($url, $post_arr = null) {
    $header_arr = array(
        'Content-type: application/x-www-form-urlencoded',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng',
        'Accept-Language: en-US,en;q=0.9,ar;q=0.8',
        'Cache-Control: max-age=0',
        'Connection: keep-alive',
        'Host: ' . parse_url($url, PHP_URL_HOST),
        'Upgrade-Insecure-Requests: 1',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    );
    $postdata = '';
    if (!empty($post_arr))
        $postdata = http_build_query($post_arr);
    //
    $opts = array('http' =>
        array(
            'method' => (empty($postdata) ? 'GET' : 'POST'),
            'header' => implode("\r\n", $header_arr),
            'content' => $postdata
        )
    );
    //
    $context = stream_context_create($opts);
    return file_get_contents($url, false, $context);
    //
//    $ch = curl_init();
//    curl_setopt($ch, CURLOPT_URL, $url);
//    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//    if (!empty($postdata)) {
//        curl_setopt($ch, CURLOPT_POST, 1);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
//    }
//    curl_setopt($ch, CURLOPT_HTTPHEADER, $header_arr);
//    $contents = curl_exec($ch);
//    curl_close($ch);
//    return $contents;
}

//
$file = my_get_contents($online_url . "/public/last-file/" . SMARTDINER_BRANCH_ID);
$image_name_date = my_get_contents($online_url . "/public/last-image-file/" . SMARTDINER_BRANCH_ID);

$time = date("Y-m-d-H-i");
$prev_min = date("Y-m-d-H-i", strtotime('-2 minutes'));

$query_string = '';
$image_string = '';
$zip_file_name = 'img-' . microtime(true) . '.zip';
$zip = new ZipArchive();
$last_file = '';
$last_image_file = '';

$dir = scandir(dirBase . "uploads/logs");

foreach ($dir as $file_name) {
    $current_file = dirBase . "uploads/logs/" . $file_name;
    if (is_file($current_file) && substr($file_name, 0, 4) == 'log#' && substr($file_name, 0, 1) != '.') {
        $file_date = explode('#', $file_name)[1];
        if ($file_date > $file && $file_date < $prev_min) {
            $query_string .=file_get_contents($current_file);
            $last_file = $file_date;    //max($last_file, $file_date);
        } else if ($file_date <= $file) {
            rename($current_file, dirBase . "uploads/logs/done/" . $file_name);
        }
    }
//    if (is_file($current_file) && substr($file_name, 0,4) == 'img#' && substr($file_name, 0,1) != '.') {
//        $file_date = explode('#', $file_name)[1];
//        if ($file_date > $image_name_date && $file_date < $prev_min) {
//            $image_array = explode("\n",file_get_contents($current_file));
//            //            for($i=0; $i<count($image_array)-1;$i++){
//            //                $current_image_path=  explode("Ӂ",$image_array[$i])[0];
//            //                $image_path_new = explode("/",$current_image_path);
//            //                $new_image_name = end($image_path_new);
//            //                if ($zip->open($zip_file_name,ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
//            //                    $zip->addFile($current_url.$current_image_path, $new_image_name);
//            //                }
//            //                $zip->close();
//            //            }
//            //            $movedReturn = $db->moveZipFiles($zip_file_name,$current_url);
//            //            if($movedReturn){
//            //                $last_image_file = $file_date;  
//            //                //                unlink($zip_file_name);
//            //            }
//        }
//    }
}
if (!empty($last_file) || !empty($last_image_file)) {
    $post_arr = array(
        'query' => $query_string,
        'last_file' => $last_file,
        'branch_id' => SMARTDINER_BRANCH_ID,
        'zip_file_name' => $zip_file_name,
        'last_image_file' => $last_image_file
    );
    $postdata = http_build_query($post_arr);
    $opts = array('http' =>
        array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
    //
//    $context = stream_context_create($opts);
//    $result = file_get_contents($online_url . '/public/sync-log', false, $context);
    $result = my_get_contents($online_url . '/public/sync-log', $post_arr);
}
