<?php

require_once 'common.php';
//
$start_time = microtime(true); // time in Microseconds
//
$invoices_to_be_updated = array();
$all_inv_data = array();
$fastpax_invoices = array();
$aramex_invoices = array();
$msg = "<br/>=====================================================================================> Start: " . date('Y-m-d H:i:s') . "<br/>";
//
$query_invoices = $db->query_execute('select inv.Invoice_ID_Auto,
                                             shipping.pick_up_date,
                                             shipping.drop_off_date,
                                             shipping.shipping_status_id,
                                             shipping.api_shipping_id,
                                             shipping.api_other_response,
                                             shipping_company.shipping_company_id,
                                             shipping_company.api_folder,
                                             shipping_company.token,
                                             shipping_company.api_version
                                      from tbl_invoices inv
                                    inner join tbl_invoice_shipping shipping on shipping.Invoice_ID_Auto = inv.Invoice_ID_Auto
                                    inner join tbl_shipping_company shipping_company on shipping_company.shipping_company_id = inv.shipping_company_id
                                      where shipping.shipping_status_id  is not null
                                      and shipping.shipping_status_id not in (1,4,5,6,8)
                                      and shipping.api_shipping_id is not null
                                      and shipping_company.api_folder In ("fastpax","aramex") limit 150
                                      ');
while ($invoice_row = $db->query_fetch($query_invoices)) {
    $all_inv_data[$invoice_row['Invoice_ID_Auto']] = ['shipping_status_id' => $invoice_row['shipping_status_id']];
    //
    if ($invoice_row['api_folder'] == 'fastpax') {
        $fastpax_invoices[] = $invoice_row;
    } else {
        $aramex_invoices[$invoice_row['api_shipping_id']] = $invoice_row['Invoice_ID_Auto'];
    }
}
//
$msg .= "<br/>Finish Main Query & Loop " . (microtime(true) - $start_time) . " Sec.";
//for fastpax
if (!empty($fastpax_invoices)) {
    foreach ($fastpax_invoices as $invoice_row) {
        $api_version = !empty($invoice_row['api_version']) ? $invoice_row['api_version'] : 'v1';
        $current_token = $invoice_row['token'];
        $order_track_link = SERVER_FASTPAX_URL . $api_version . '/order/track';
        $post_data = ['DBNumber' => $invoice_row['api_shipping_id']];
        $order_track = send_post($order_track_link, $post_data, $current_token);
        $response_order_track = json_decode($order_track);
        if ($response_order_track->Status == 1) {
            $other_response = 'Phase: ' . $response_order_track->Data->Phase . ', Status: ' . $response_order_track->Data->Status;
            $current_response_phase = $response_order_track->Data->Phase;
            $current_response_status = $response_order_track->Data->Status;
            $current_status = $invoice_row['shipping_status_id'];
            if ($current_response_status == 'PLACE ORDER' || $current_response_status == 'WAITING FOR PICK UP')
                $current_status = 2;
            else if ($current_response_status == 'DELIVERED')
                $current_status = 6;
            else if ($current_response_status == 'PICKED UP & FIRST CALL')
                $current_status = 3;
            else if ($current_response_status == 'CLOSED')
                $current_status = 4;
            else if ($current_response_status == 'RETURN')
                $current_status = 5;
            else if ($current_response_status == 'PAYMENT TRANSFER')
                $current_status = 7;
            $invoices_to_be_updated[$invoice_row['Invoice_ID_Auto']] = ['other_response' => $other_response,
                'current_status' => $current_status];
        }else {
            $other_response = $response_order_track->ErrorMessage;
            $current_status = $response_order_track->ErrorMessage == 'Not found' ? 8 : '';
            $invoices_to_be_updated[$invoice_row['Invoice_ID_Auto']] = ['other_response' => $other_response,
                'current_status' => $current_status];
        }
    }
}
$msg .= "<br/>Finish Fastpax [" . count($fastpax_invoices) . " Invoices] Time: " . (microtime(true) - $start_time) . " Sec.";

//for aramex
if (!empty($aramex_invoices)) {
    $soapClient = new SoapClient(SITE_LINK . 'shipping_api/tracking.wsdl');
    $shipping_company_query = $db->query_execute('select * from tbl_shipping_company where api_folder = "aramex" ');
    $shipping_company_data = $db->query_fetch($shipping_company_query);
    $shipping_account_data = json_decode($shipping_company_data['note'], true);
    //
    $invoice_ids_array = array_keys($aramex_invoices);
    $params = array(
        'ClientInfo' => array(
            'AccountCountryCode' => 'LB',
            'AccountEntity' => $shipping_account_data['AccountEntity'],
            'AccountNumber' => $shipping_account_data['AccountNumber'],
            'AccountPin' => $shipping_account_data['AccountPin'],
            'UserName' => $shipping_company_data['user_name'],
            'Password' => $shipping_company_data['password'],
            'Version' => $shipping_company_data['api_version']
        ),
        'Transaction' => array(
            'Reference1' => '001',
        ),
        'Shipments' => $invoice_ids_array
    );
    try {
        $auth_call = $soapClient->TrackShipments($params);
        if (!$auth_call->HasErrors) {
            if (count($invoice_ids_array) == 1) {
                $last_track_result = $auth_call->TrackingResults->KeyValueOfstringArrayOfTrackingResultmFAkxlpY->Value->TrackingResult;
                if (is_object($last_track_result)) {
                    $track_result = set_track_data($last_track_result);
                } else {
                    $track_result = set_track_data($last_track_result[0]);
                }
                $current_key = $auth_call->TrackingResults->KeyValueOfstringArrayOfTrackingResultmFAkxlpY->Key;
                $invoices_to_be_updated[$aramex_invoices[$current_key]] = $track_result;
            } else {
                $shippments_data = $auth_call->TrackingResults->KeyValueOfstringArrayOfTrackingResultmFAkxlpY;
                foreach ($shippments_data as $current_shippment) {
                    $last_track_result = $current_shippment->Value->TrackingResult;
                    $current_key = $current_shippment->Key;
                    //  print_r($last_track_result);
                    if (is_object($last_track_result)) {
                        $track_result = set_track_data($last_track_result);
                    } else {
                        $track_result = set_track_data($last_track_result[0]);
                    }
                    $invoices_to_be_updated[$aramex_invoices[$current_key]] = $track_result;
                }
            }
        }
    } catch (SoapFault $fault) {
        $msg .= "<br/>Aramex API Error: " . print_r($fault->faultstring, true);
    }
}
$msg .= "<br/>Finish Aramex [" . count($aramex_invoices) . " Invoices] Time: " . (microtime(true) - $start_time) . " Sec.";
//update invoices status in db.
$updtd_inv = 0;
foreach ($invoices_to_be_updated as $key => $value) {
    if ($all_inv_data[$key]['shipping_status_id'] == $value['current_status'])
        continue;
    $updtd_inv++;
    if ($value['current_status'] == 3 || $value['current_status'] == 6) {
        $invoice = new Invoice;
        $invoice->generate_ship_trans($key, $value['current_status']);
    }
    $current_date = date('Y-m-d');
    $updated_invoices = $db->query_execute('update tbl_invoice_shipping 
         set shipping_status_id = ?,api_other_response = ?,date_last_status=? where Invoice_ID_Auto = ? ', [&$value['current_status'], &$value['other_response'], $current_date, &$key]);
    $db->query_execute('update tbl_invoices set shipping_status_id = ? where Invoice_ID_Auto = ? ', [&$value['current_status'], &$key]);
}
$msg .= "<br/>All Invoices: " . count($invoices_to_be_updated) . ", Updated Invoices: {$updtd_inv}";
$msg .= "<br/>Done, Total Time: " . (microtime(true) - $start_time) . " Sec.";
$msg .= "<br/>=====================================================================================> End: " . date('Y-m-d H:i:s') . "<br/><br/>";
echo "<pre>" . $msg;

//
$tmp_shpng_log = tmp_dir_path . 'shipping_log/';
if (!is_dir($tmp_shpng_log))
    mkdir($tmp_shpng_log);
if (!empty($invoices_to_be_updated))
    file_put_contents($tmp_shpng_log . date('Y-m-d') . '.html', $msg, FILE_APPEND);
//since maybe new files like from seconds or minutes created & used for now,..
//we need it to at least keep today file ex: 86400 to delete all filed before 24 hour [2592000=>30 days]
$old_time = time() - 2592000;
$dir_elements = scandir($tmp_shpng_log, 0);
if (is_array($dir_elements)) {
    foreach ($dir_elements as $element) {
        if ($element != '.' && $element != '..') {
            $full_element = $tmp_shpng_log . DIRECTORY_SEPARATOR . $element;
            if (is_writable($full_element) && filemtime($full_element) < $old_time)
                unlink($full_element);
        }
    }
}
