<?php

require_once("../include/dbconnect.inc.php");

//$requestURLVotian = "https://apache-3.assecutor.de/test_sb_intern/service/order_request.php";
$requestURLVotian = "https://sb.assecutor.de/service/order_request.php";

if (!function_exists('str_contains')) {
    function str_contains($haystack, $needle) {
        return $needle !== '' && mb_strpos($haystack, $needle) !== false;
    }
}

function getAuthHeaderVotian($data) {

//    NetApp B.V. - Good (EMEA)
//    Philips Healthcare Services EMEA
//    JUNIPER NETWORKS-EMEA GOOD INVENTORY

    $headerMatchData = array(
//        "STS910310" => array(
//            "costcenter" => array(
//                "Stadtbote GmbH",
//                "Ciena",
//                "DELL",
//                "Extreme Networks",
//                "Juniper",
//                "Riverbed",
//                "TeraData",
//                "Unify",
//                "BROCADE",
//                "Ruckus",
//                "Landa",
//            ),
//            "address" => array(
//                "Hertichstraße 10 71229 Leonberg"
//            ),
//            "deliveryType" => ""
//        ),

        //        "STH911740" => array(
//            "costcenter" => array(
//                "Stadtbote GmbH"
//            ),
//            "address" => array(
//                "Hertichstraße 10 71229 Leonberg"
//            ),
//            "deliveryType" => "WFRA5"
//        ),
//
//        "STH911739" => array(
//            "costcenter" => array(
//                "Stadtbote GmbH"
//            ),
//            "address" => array(
//                "Hertichstraße 10 71229 Leonberg"
//            ),
//            "deliveryType" => "WSTR1"
//        ),

        "STF909266" => array(
            "costcenter" => array(
                "Stadtbote GmbH"
            ),
            "address" => array(
                "Gaugrafenstraße 24A,Frankfurt am Main,GERMANY,60489"
            ),
            "deliveryType" => "WFRA5"
        ),

        "STH911738" => array(
            "costcenter" => array(
                "Stadtbote GmbH"
            ),
            "address" => array(
                "Ikarusallee 15,Hannover,GERMANY,30179"
            ),
            "deliveryType" => "WLHA1"
        ),

        "STH911738" => array(
            "costcenter" => array(
                "Stadtbote GmbH"
            ),
            "address" => array(
                "Ikarusallee 15,Hannover,GERMANY,30179"
            ),

            "deliveryType" => "WHAJ1"
        ),

        "STS910311" => array(
            "costcenter" => array(
                "Stadtbote GmbH",
                "Ciena",
                "DELL",
                "Extreme Networks",
                "Juniper",
                "Riverbed",
                "TeraData",
                "Unify",
                "BROCADE",
                "Ruckus",
                "Landa",
            ),
            "address" => array(
                "Hertichstraße 10,Leonberg,GERMANY,71229"
            ),
            "deliveryType" => "WSTR1"
        ),
    );

//    $authArray = array(
//        "STF909270" => array(
//            "customer" => "STF909270",
//            "account" => "STF909270",
//            "password" => "F26145",
//            "session_id" => "acf922154627f6788918f03c42b123cde4da3b7fbbce2345d7772b0674a318d513e11c604eb72f856a0e99eed6b5a7a9649871c97cb15dd0f859974733bd15c9",
//            "costcenter_name" => "Stadtbote/UPS"
//        ),
//        "STS910310" => array(
//            "customer" => "STS910310",
//            "account" => "STS910310",
//            "password" => "test12345a",
//            "session_id" => "558e3aa9f7f9b7049d1fadda292d23a16512bd43d9caa6e02c990b0a82652dca00b3f8fe5afe60e1a467a936c9d58bb7718a9a733adbef7edb0bd1dadb211124",
//            "costcenter_name" => "Stadtbote/UPS"
//        ),
//        "STF909266" => array(
//            "customer" => "STF909266",
//            "account" => "STF909266",
//            "password" => "F80120",
//            "session_id" => "f288f46c5d79de67251ea00e6c7970f6e4da3b7fbbce2345d7772b0674a318d5b3758ba1faf81fdf9253465f6642dfee38853822faf9db66ed087d9e847f267a",
//            "costcenter_name" => "Stadtbote GmbH / UPS"
//        ),
//        "STH911739" => array(
//            "customer" => "STH911739",
//            "account" => "STF909266",
//            "password" => "H85450",
//            "session_id" => "5067ed417ec5779207a81178c50017b4a87ff679a2f3e71d9181a67b7542122c74e6497fd22dd8eafa58e21abe4b371bf72642f12aa2d1a323334db941c0f145",
//            "costcenter_name" => "Stadtbote/UPS"
//        ),
//        "STH911740" => array(
//            "customer" => "STH911740",
//            "account" => "STH911740",
//            "password" => "H63474",
//            "session_id" => "fe709c654eac84d5239d1a12a4f71877a87ff679a2f3e71d9181a67b7542122c618b8800517a6c10f8f27a7c48166ea392433abdf2a5a3badf45c990fc732aff",
//            "costcenter_name" => "Stadtbote/UPS"
//        ),
//        "STS920307" => array(
//            "customer" => "STS920307",
//            "account" => "STS920307",
//            "password" => "S68031",
//            "session_id" => "dc363817786ff182b7bc59565d8645236512bd43d9caa6e02c990b0a82652dca2ab855e70e04711a44aea6555af30f10ab1a2d9401e4ae7fe5acff76e5f10420",
//            "costcenter_name" => "Stadtbote/UPS"
//        ),
//        "STS920308" => array(
//            "customer" => "STS920308",
//            "account" => "STS920308",
//            "password" => "S27196",
//            "session_id" => "f096d3da9f8797e053edd854335413ab6512bd43d9caa6e02c990b0a82652dcaf5bea4fc2cbc9766f98b8d8fd28d597c3485aa0e07dfb703721627b6edf1759e",
//            "costcenter_name" => "Stadtbote/UPS"
//        ),
//        "STS920315" => array(
//            "customer" => "STS920315",
//            "account" => "STS920315",
//            "password" => "S36338",
//            "session_id" => "0a30a980e3540e51eb25423caa79f0cb6512bd43d9caa6e02c990b0a82652dcae0442a7d0949964ee2de23a30ff2c1c3cbd682237d1c378be6413427c69ffba6",
//            "costcenter_name" => "Stadtbote/UPS"
//        ),
//    );

    $authArray = array(
        "STF909266" => array(
            "customer" => "STF909266",
            "account" => "STF909266",
            "password" => "F24718",
            "session_id" => "64063a9bafbf19f37ef32a222116bcf1e4da3b7fbbce2345d7772b0674a318d5b3758ba1faf81fdf9253465f6642dfee38853822faf9db66ed087d9e847f267a",
            "costcenter_name" => "Stadtbote/UPS"
        ),
        "STH911739" => array(
            "customer" => "STH911739",
            "account" => "STH911739",
            "password" => "h1x5304937z",
            "session_id" => "c9ce98a38ebb27ccdb0e5083f2cfcde7a87ff679a2f3e71d9181a67b7542122c74e6497fd22dd8eafa58e21abe4b371bf72642f12aa2d1a323334db941c0f145",
            "costcenter_name" => "Stadtbote/UPS"
        ),
        "STH911740" => array(
            "customer" => "STH911740",
            "account" => "STH911740",
            "password" => "h2x7398573m",
            "session_id" => "e340862bc3c1549012646f7abdc2e155a87ff679a2f3e71d9181a67b7542122c618b8800517a6c10f8f27a7c48166ea392433abdf2a5a3badf45c990fc732aff",
            "costcenter_name" => "Stadtbote GmbH / UPS"
        ),
        "STS910311" => array(
            "customer" => "STS910311",
            "account" => "STS910311",
            "password" => "S94634",
            "session_id" => "94133569fa68cdac680ed55b978ddb396512bd43d9caa6e02c990b0a82652dca333136567a522bd804fcb838f434c6526e17cffb04e96736ea7cd39a1a216b9a",
            "costcenter_name" => "Stadtbote/UPS"
        ),
        "STH911738" => array(
            "customer" => "STH911738",
            "account" => "STH911738",
            "password" => "h8293879x",
            "session_id" => "4164f841b44e3eb8e122b78b0e40af4fa87ff679a2f3e71d9181a67b7542122cd37e5b335b9ff484f872e2ad1a93cac2c5fb336d2edc39d8227d4689833d6709",
            "costcenter_name" => "Stadtbote/UPS"
        ),
        "STS910230" => array(
            "customer" => "STS910230",
            "account" => "STS910230",
            "password" => "s7303829v",
            "session_id" => "07563a3fe3bbe7e3ba84431ad9d055af6512bd43d9caa6e02c990b0a82652dca6134d9f1f712e6359c489750abb4a922d58a34045898e11873b28d087822e709",
            "costcenter_name" => "Stadtbote/UPS"
        )
    );

    $matchPercSum = PHP_INT_MAX;
    $matchingCustomer = "";
    $costcenterArray = explode(" ", $data['costcenter']);
    $costcenterArray = array_map('strtolower', $costcenterArray);

    foreach($headerMatchData as $customer => $matchInfo) {

        $matchCustPercentage = PHP_INT_MAX;
        $matchOriginPercentage = PHP_INT_MAX;
        $matchDestPercentage = PHP_INT_MAX;

        if(strpos($data['branchName'], $matchInfo['deliveryType']) !== false || $data['deliveryType'] == $matchInfo['deliveryType']) {

            $matchingCustomer = $customer;
            break;

        }

        foreach($matchInfo['costcenter'] as $customerIndex => $customerInfo) {

            if(in_array(strtolower($customerInfo), $costcenterArray)) {

                $matchingCustomer = $customer;
                break 2;

            }

//            var_dump();
//            similar_text(strtolower($data['costcenter']), strtolower($customerInfo), $customerPerc);
            $customerPerc = levenshtein(strtolower($customerInfo), strtolower($data['costcenter']));

//
//            echo strtolower($customerInfo) . " - ";
//            echo strtolower($data['costcenter']);
//            echo " - " . levenshtein(strtolower($customerInfo), strtolower($data['costcenter']));
//            echo "<br>";
//            echo "<br>";

            if($customerPerc < $matchCustPercentage) {

                $matchCustPercentage = $customerPerc;

            }

        }

        foreach($matchInfo['address'] as $addressIndex => $addressInfo) {

//            similar_text(strtolower($data['address']), strtolower($addressInfo), $addressPercs);
            $originPerc = levenshtein(strtolower($addressInfo), strtolower($data['origin']));

//            echo strtolower($addressInfo) . " - ";
//            echo strtolower($data['address']);
//            echo " - " . $addressPercs;
//            echo "<br>";
//            echo "<br>";

            if($originPerc < $matchOriginPercentage) {

                $matchOriginPercentage = $originPerc;

            }

//            similar_text(strtolower($data['address']), strtolower($addressInfo), $addressPercs);
            $destionationPerc = levenshtein(strtolower($addressInfo), strtolower($data['destination']));

//            echo strtolower($addressInfo) . " - ";
//            echo strtolower($data['address']);
//            echo " - " . $addressPercs;
//            echo "<br>";
//            echo "<br>";

            if($destionationPerc < $matchDestPercentage) {

                $matchDestPercentage = $destionationPerc;

            }

        }

        $matchPercSumTemp = $matchCustPercentage + $matchOriginPercentage + $matchDestPercentage;

        if($matchPercSumTemp < $matchPercSum) {

            $matchPercSum = $matchPercSumTemp;
            $matchingCustomer = $customer;

        }

    }

    return $authArray[$matchingCustomer];

}

function syncDataWithVotian($postData, $lnOrderGetResponse) {

    global $requestURLVotian;

    $suffix = getSuffix($postData['branchName']);

    if(!$suffix) {

        $suffix = "";

    }

//    $lnOrderGetResponse = json_decode($lnOrderGetResponse, true);

    if($lnOrderGetResponse['status'] == 200 && $lnOrderGetResponse['message'] == "SUCCESS" && count($lnOrderGetResponse['data']) > 0) {

        $availableDummyVehicle = getAvailableDummyVehicle($suffix);

        $dummyVehicle = str_replace($suffix, "", $availableDummyVehicle['gdc_context']);

        $lnOrderGetResponseData = $lnOrderGetResponse['data'][0];

        $blockVehicleDummy = setDummyVehicleStatus($availableDummyVehicle['gdc_obj_id'], 2);

        if($blockVehicleDummy) {

            $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
            fwrite($myfile,"-------".$postData['orderNo']."----------------REClogiNextMileDeliveryAssociateGet-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
            fclose($myfile);

            $vehicleExists = logiNextMileDeliveryAssociateGet($dummyVehicle);

            $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
            fwrite($myfile,"-------".$postData['orderNo']."----------------ANSlogiNextMileDeliveryAssociateGet-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
            fclose($myfile);

            if($vehicleExists[1]['status'] == 200 && $vehicleExists[1]['data']['totalCount'] == 0 && $vehicleExists[1]['data']['otherCount'] == 0 && $vehicleExists[1]['data']['clientBranchId'] == 0) {

                $vehicleDataArray = array(
                    array(
                        "employeeId" => $dummyVehicle,
                        "imei" => $dummyVehicle,
                        "userGroupName" => "Driver Mobile Access",
                        "branchName" => "Stadtbote",
                        "deliveryMediumMasterName" => $availableDummyVehicle['gdc_context'],
                        "userName" => $dummyVehicle,
                        "password" => $dummyVehicle,
                        "capacityInUnits" => 10,
                        "phoneNumber" => $dummyVehicle
                    )
                );

                $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                fwrite($myfile,"-------".$postData['orderNo']."----------------REClogiNextMileDeliveryAssociateCreate-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                fclose($myfile);

                $lnCreateVehicle = logiNextMileDeliveryAssociateCreate($vehicleDataArray);

                $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                fwrite($myfile,"-------".$postData['orderNo']."----------------ANSlogiNextMileDeliveryAssociateCreate-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                fclose($myfile);

                if($lnCreateVehicle[1]['status'] == 201 && $lnCreateVehicle[1]['message'] == "Success" && $lnCreateVehicle[1]['hasError'] == false) {

                    $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                    fwrite($myfile,"-------".$postData['orderNo']."----------------REClogiNextMileOrderAssign-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                    fclose($myfile);

                    $lnAssignOrder = logiNextMileOrderAssign($postData['orderReferenceId'], $dummyVehicle);

                    $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                    fwrite($myfile,"-------".$postData['orderNo']."----------------ANSlogiNextMileOrderAssign-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                    fclose($myfile);

                    if(($lnAssignOrder[1]['status'] == 200 && !$lnAssignOrder[1]['hasError'])) {

                        $orderGetData = array(
                            "orderReferenceId" => $postData['orderReferenceId'],
                            "order_no" => $postData['orderNo'],
                            // "end_date" => $postData['endTimeWindow'],
                            // "start_date" => $postData['startTimeWindow'],
                        );

                        $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                        fwrite($myfile,"-------".$postData['orderNo']."----------------REClogiNextMileOrderGet-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                        fclose($myfile);

                        $lnOrderGetResponse = logiNextMileOrderGet($orderGetData);

                        $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                        fwrite($myfile,"-------".$postData['orderNo']."----------------ANSlogiNextMileOrderGet-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                        fclose($myfile);

                        // if($lnOrderGetResponse['status'] != 200 || $lnOrderGetResponse['message'] != "SUCCESS") {

                        //     error("No order information could be found \n" . json_encode($lnOrderGetResponse));

                        // }

                        $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                        fwrite($myfile,"-------".$postData['orderNo']."----------------REClnStartTrip-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                        fclose($myfile);

                        $lnStartTripResult = lnStartTrip($lnOrderGetResponse[1]['data'][0]['tripReferenceId']);

                        $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                        fwrite($myfile,"-------".$postData['orderNo']."----------------ANSlnStartTrip-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                        fclose($myfile);

                        if(($lnStartTripResult['status'] == 200 && $lnStartTripResult['data'] == true)) {

                            $authData = getAuthHeaderVotian(
                                array(
                                    "costcenter" => $lnOrderGetResponse[1]['data'][0]['clientName'],
                                    "origin"  => $lnOrderGetResponse[1]['data'][0]['origin'],
                                    "destination"  => $lnOrderGetResponse[1]['data'][0]['destination'],
                                    "deliveryType"  => $postData['deliveryType'],
                                    "branchName" => $postData['branchName']
                                )
                            );

                            $votianStations = array();
                            $votianGdc = array();
                            $votianFirstStation = array();
                            $votianSecondStation = array();
                            $votianAuthData = $authData;

                            $pickUpAddress = getAddressFromString($lnOrderGetResponseData['origin']);
                            $deliveryAddress = getAddressFromString($lnOrderGetResponseData['destination']);

                            // $pickUpAddress = explode(",", $lnOrderGetResponseData['origin']);
                            // $deliveryAddress = explode(",", $lnOrderGetResponseData['destionation']);

                            // $pickUpStreetHsno = explode(" ", $pickUpAddress[count($pickUpAddress)-4]);
                            // $pickUpHsno = $pickUpStreetHsno[count($pickUpStreetHsno)-1];
                            // $pickUpStreet = str_replace(" ".$pickUpHsno, "", $pickUpAddress[0]);

                            // $deliveryStreetHsno = explode(" ", $deliveryAddress[count($deliveryAddress)-4]);
                            // $deliveryHsno = $deliveryStreetHsno[count($deliveryStreetHsno)-1];
                            // $deliveryStreet = str_replace(" ".$deliveryHsno, "", $deliveryAddress[0]);

                            $pickUpPerson = explode(",", $lnOrderGetResponseData['deliverAccountName']);

                            $votianFirstStation["company"] = "Stadtbote / " . $lnOrderGetResponseData['clientName'];
                            $votianFirstStation["street"] = $pickUpAddress['street1'];
                            $votianFirstStation["ad_supplement_1"] = $pickUpAddress['street2'];
                            $votianFirstStation["ad_supplement_2"] = $pickUpAddress['street3'];
                            $votianFirstStation["houseno"] = $pickUpAddress['hsno'];
                            $votianFirstStation["zipcode"] = $pickUpAddress['zipcode'];
                            $votianFirstStation["city"] = $pickUpAddress['city'];
                            // $votianFirstStation["special_remark"] = $postData['originAddr'];
                            // $votianFirstStation["person"] = $lnOrderGetResponseData['pickupAccountName'];
                            $votianFirstStation["phone"] = $lnOrderGetResponseData['pickupPhoneNumber'];
                            $votianFirstStation["email"] = $lnOrderGetResponseData['pickupEmail'];
                            $votianFirstStation["gps_lat"] = $lnOrderGetResponseData['originLatitude'];
                            $votianFirstStation["gps_long"] = $lnOrderGetResponseData['originLongitude'];

                            $articles = array();

                            foreach ($lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['shipmentlineitems'] as $key=>$value) {

                                $article = array();

                                $article['description'] = $value['itemName'];
                                $article['quantity'] = $value['itemQuantity'];
                                $article['weight'] = $value['itemWeight'];
                                $article['length'] = $value['itemLength'];
                                $article['height'] = $value['itemHeight'];
                                $article['width'] = $value['itemBreadth'];

                                $articles['article'] = $article;

                            }

                            $articles['total_weight'] = $lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['totalItemsWeight'];
                            $articles['totalItemsVolume'] = $lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['totalItemsVolume'];
                            $articles['total_pieces'] = $lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['noOfUnits'];
                            $votianFirstStation["articles"] = $articles;

                            $destionationCompany = explode(",", $lnOrderGetResponseData['destination']);
                            $destionationCompanyString = "";

                            // if(count($destionationCompany) > 4) {

                                $destionationCompanyString = explode(",", $lnOrderGetResponseData['deliverAccountCode']);

                            // }


                            // if(strpos($lnOrderGetResponseData['deliveryNotes'], 'ALT:') !== false) {

                            //     preg_match('/ALT:\ ([A-Za-zÀ-ÖØ-öø-ÿ\s]*)\ [0-9]*/', $lnOrderGetResponseData['deliveryNotes'], $personSecondStation);
                            //     $personSecondStationString = $personSecondStation[1];

                            // } else {

                                $destinationPersonString = explode(",", $lnOrderGetResponseData['deliverAccountName']);
                                $personSecondStationString = $destinationPersonString[count($destinationPersonString)-1];

                            // }



                            
                            $votianSecondStation["street"] = $deliveryAddress['street1'];
                            $votianSecondStation["ad_supplement_1"] = $deliveryAddress['street2'];
                            $votianSecondStation["ad_supplement_2"] = $deliveryAddress['street3'];
                            $votianSecondStation["houseno"] = $deliveryAddress['hsno'];
                            $votianSecondStation["floorno"] = "";
                            $votianSecondStation["zipcode"] = $deliveryAddress['zipcode'];
                            $votianSecondStation["city"] = $deliveryAddress['city'];
                            $votianSecondStation["special_remark"] = $lnOrderGetResponseData['deliveryNotes'];

                            // SPLUS CHECK order_no: XXX_0

                            if(str_contains($postData['orderNo'], "_0")) {

                                $votianSecondStation["company"] = $lnOrderGetResponseData['deliverAccountName'];

                                $votianSecondStation["person"] = $lnOrderGetResponseData['deliveryNotes'] . " " . $lnOrderGetResponseData['deliverPhoneNumber'];
                                

                            } else {

                                $votianSecondStation["company"] = $destionationCompanyString[0];

                                $votianSecondStation["person"] = $personSecondStationString . " " . $lnOrderGetResponseData['deliverPhoneNumber'];

                            }

                            $votianSecondStation["phone"] = $lnOrderGetResponseData['deliverPhoneNumber'];
                            // $votianSecondStation["phone"] = $lnOrderGetResponseData['customerPhoneNumber'];
                            $votianSecondStation["email"] = $lnOrderGetResponseData['deliverEmail'];
                            $votianSecondStation["gps_lat"] = $lnOrderGetResponseData['destinationLatitude'];
                            $votianSecondStation["gps_long"] = $lnOrderGetResponseData['destinationLongitude'];

                            $votianStations['station'][] = $votianFirstStation;
                            $votianStations['station'][] = $votianSecondStation;

                            $votianGdc['val'][] = $postData['orderNo'];
                            $votianGdc['val'][] = $postData['awbNumber'];
                            $votianGdc['val'][] = $dummyVehicle;
                            $votianGdc['val'][] = $postData['orderReferenceId'];

                            // 2012-02-17 09:30:00
                            // $pickUpStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['pickupEta'] / 1000));
                            // $deliverStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverEta'] / 1000));

                            $pickUpStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['pickupStartTimeWindow'] / 1000));
                            $deliverStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverEndTimeWindow'] / 1000));
                            // $deliverStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverStartTimeWindow'] / 1000));

                            // $eta = "Keine";

                            // if($lnOrderGetResponse[1]['data'][0]['pickupEta']) {

                                // $eta = date("Y-m-d H:i:s", ($lnOrderGetResponse[1]['data'][0]['pickupEta'] / 1000));
                                $eta = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverEndTimeWindow'] / 1000));

                            // }

                            $votianOrderReqData = array(
                                "order" => array(
                                    "auth" => $votianAuthData,
                                    "no" => $lnOrderGetResponseData['awbNumber'],
                                    "ordertime" => $pickUpStartTime,
                                    // "ordertimeUTC" => $postData['startTimeWindow'],
                                    "warningtime" => $deliverStartTime,
                                    // "warningtimeUTC" => $postData['endTimeWindow'],
                                    // "remark" => $postData['shipmentNotes'],
                                    "remark" => ".",
                                    "courier_remark" => ".",
                                    "dispoinfo" => "ETA:" . $eta,
                                    "gdc" => $votianGdc,
                                    "stations" => $votianStations
                                )
                            );

                            $requestResult = executeRESTCall("POST", $requestURLVotian, $votianOrderReqData, "xml");
                            $requestResultXML = simplexml_load_string(array_keys($requestResult[0])[2]);

                            if($requestResultXML->state == "OK") {

                                $successArray = array(
                                    "status" => 201,
                                    "message" => "ORDER SUCCESSFULLY CREATED AND ASSIGNED TO VEHICLE"
                                );

                                $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                                fwrite($myfile,"-----------------------".$postData['orderNo']."---------- SUCCESS---------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
                                fwrite($myfile, array_keys($requestResult[0])[2]);
                                fwrite($myfile, "\n");
                                fwrite($myfile, json_encode($successArray));
                                fwrite($myfile, "\n");
                                fwrite($myfile, "\n");
                                fclose($myfile);

                                return true;

                            } else {

                                setDummyVehicleStatus($availableDummyVehicle['gdc_obj_id'], 0);
                                error("The order could not be created in votian \n" . $requestResultXML->asXML(), $postData['orderNo']);

                            }

                        } else {

                            error("The trip could not be started \n" . json_encode($lnStartTripResult), $postData['orderNo']);

                        }

                    } else {

                        error("The order could not be assigned to the driver \n" . json_encode($lnAssignOrder), $postData['orderNo']);

                    }

                } else {

                    error("Driver could not be created in the LN system \n" . json_encode($lnCreateVehicle[1]), $postData['orderNo']);

                }

            } else if($vehicleExists[1]['status'] == 200 && $vehicleExists[1]['data']['totalCount'] > 0) {

                $lnAssignOrder = logiNextMileOrderAssign($postData['orderReferenceId'], $dummyVehicle);

                if(($lnAssignOrder[1]['status'] == 200 && !$lnAssignOrder[1]['hasError'] && $lnAssignOrder[1]['message'] == "Order(s) Assigned Successfully!")) {

                    $orderGetData = array(
                        "orderReferenceId" => $postData['orderReferenceId'],
                        "order_no" => $postData['orderNo'],
                        // "end_date" => $postData['endTimeWindow'],
                        // "start_date" => $postData['startTimeWindow'],
                    );

                    $lnOrderGetResponse = logiNextMileOrderGet($orderGetData);

                    // if($lnOrderGetResponse['status'] != 200 || $lnOrderGetResponse['message'] != "SUCCESS") {

                    //         error("No order information could be found \n" . json_encode($lnOrderGetResponse));

                    // }

                    $lnStartTripResult = lnStartTrip($lnOrderGetResponse[1]['data'][0]['tripReferenceId']);

                    if($lnStartTripResult['status'] == 200 && $lnStartTripResult['data'] == true) {

                        $authData = getAuthHeaderVotian(
                            array(
                                "costcenter" => $lnOrderGetResponse[1]['data'][0]['clientName'],
                                "origin"  => $lnOrderGetResponse[1]['data'][0]['origin'],
                                "destination"  => $lnOrderGetResponse[1]['data'][0]['destination'],
                                "deliveryType"  => $postData['deliveryType'],
                                "branchName" => $postData['branchName']
                            )
                        );

                        $votianStations = array();
                        $votianGdc = array();
                        $votianFirstStation = array();
                        $votianSecondStation = array();
                        $votianAuthData = $authData;

                        // $pickUpAddress = explode(",", $postData['originAddr']);
                        // $deliveryAddress = explode(",", $postData['destinationAddr']);

                        // $pickUpStreetHsno = explode(" ", $pickUpAddress[0]);
                        // $pickUpHsno = $pickUpStreetHsno[count($pickUpStreetHsno) - 1];
                        // $pickUpStreet = str_replace(" " . $pickUpHsno, "", $pickUpAddress[0]);

                        // $deliveryStreetHsno = explode(" ", $deliveryAddress[0]);
                        // $deliveryHsno = $deliveryStreetHsno[count($deliveryStreetHsno) - 1];
                        // $deliveryStreet = str_replace(" " . $deliveryHsno, "", $deliveryAddress[0]);

                        $pickUpAddress = getAddressFromString($lnOrderGetResponseData['origin']);
                        $deliveryAddress = getAddressFromString($lnOrderGetResponseData['destination']);

                        $pickUpPerson = explode(",", $lnOrderGetResponseData['deliverAccountName']);

                        $votianFirstStation["company"] = "Stadtbote / " . $lnOrderGetResponseData['clientName'];
                        $votianFirstStation["street"] = $pickUpAddress['street1'];
                        $votianFirstStation["ad_supplement_1"] = $pickUpAddress['street2'];
                        $votianFirstStation["ad_supplement_2"] = $pickUpAddress['street3'];
                        $votianFirstStation["houseno"] = $pickUpAddress['hsno'];
                        $votianFirstStation["zipcode"] = $pickUpAddress['zipcode'];
                        $votianFirstStation["city"] = $pickUpAddress['city'];
                        // $votianFirstStation["special_remark"] = $postData['originAddr'];
                        // $votianFirstStation["person"] = $lnOrderGetResponseData['pickupAccountName'];
                        $votianFirstStation["phone"] = "";
                        $votianFirstStation["email"] = $lnOrderGetResponseData['pickupEmail'];
                        $votianFirstStation["gps_lat"] = $lnOrderGetResponseData['originLatitude'];
                        $votianFirstStation["gps_long"] = $lnOrderGetResponseData['originLongitude'];

                        $articles = array();

                        foreach ($lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['shipmentlineitems'] as $key=>$value) {

                            $article = array();

                            $article['description'] = $value['itemName'];
                            $article['quantity'] = $value['itemQuantity'];
                            $article['weight'] = $value['itemWeight'];
                            $article['length'] = $value['itemLength'];
                            $article['height'] = $value['itemHeight'];
                            $article['width'] = $value['itemBreadth'];

                            $articles['article'] = $article;

                        }

                        $articles['total_weight'] = $lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['totalItemsWeight'];
                        $articles['totalItemsVolume'] = $lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['totalItemsVolume'];
                        $articles['total_pieces'] = $lnOrderGetResponse[1]['data'][0]['shipmentCrateMappings'][0]['noOfUnits'];
                        $votianFirstStation["articles"] = $articles;

                        $destionationCompany = explode(",", $lnOrderGetResponseData['destination']);
                        $destionationCompanyString = "";

                        // if(count($destionationCompany) > 4) {

                            $destionationCompanyString = explode(",", $lnOrderGetResponseData['deliverAccountCode']);

                        // }



                        // if(strpos($lnOrderGetResponseData['deliveryNotes'], 'ALT:') !== false) {

                        //     preg_match('/ALT:\ ([A-Za-zÀ-ÖØ-öø-ÿ\s]*)\ [0-9]*/', $lnOrderGetResponseData['deliveryNotes'], $personSecondStation);
                        //     $personSecondStationString = $personSecondStation[1];

                        // } else {

                            $destinationPersonString = explode(",", $lnOrderGetResponseData['deliverAccountName']);
                            $personSecondStationString = $destinationPersonString[count($destinationPersonString)-1];

                        // }
                            
                        $votianSecondStation["street"] = $deliveryAddress['street1'];
                        $votianSecondStation["ad_supplement_1"] = $deliveryAddress['street2'];
                        $votianSecondStation["ad_supplement_2"] = $deliveryAddress['street3'];
                        $votianSecondStation["houseno"] = $deliveryAddress['hsno'];
                        $votianSecondStation["floorno"] = "";
                        $votianSecondStation["zipcode"] = $deliveryAddress['zipcode'];
                        $votianSecondStation["city"] = $deliveryAddress['city'];
                        $votianSecondStation["special_remark"] = $lnOrderGetResponseData['deliveryNotes'];

                        // SPLUS CHECK order_no: XXX_0

                        if(str_contains($postData['orderNo'], "_0")) {

                            $votianSecondStation["company"] = $lnOrderGetResponseData['deliverAccountName'];

                            $votianSecondStation["person"] = $lnOrderGetResponseData['deliveryNotes'] . " " . $lnOrderGetResponseData['deliverPhoneNumber'];
                            

                        } else {

                            $votianSecondStation["company"] = $destionationCompanyString[0];

                            $votianSecondStation["person"] = $personSecondStationString . " " . $lnOrderGetResponseData['deliverPhoneNumber'];

                        }

                        // $votianSecondStation["person"] = $pickUpPerson[count($pickUpPerson)-1];
                        // $votianSecondStation["phone"] = $lnOrderGetResponseData['customerPhoneNumber'];
                        $votianSecondStation["phone"] = $lnOrderGetResponseData['deliverPhoneNumber'];
                        $votianSecondStation["email"] = $lnOrderGetResponseData['deliverEmail'];
                        $votianSecondStation["gps_lat"] = $lnOrderGetResponseData['destinationLatitude'];
                        $votianSecondStation["gps_long"] = $lnOrderGetResponseData['destinationLongitude'];

                        $votianStations['station'][] = $votianFirstStation;
                        $votianStations['station'][] = $votianSecondStation;

                        $votianGdc['val'][] = $postData['orderNo'];
                        $votianGdc['val'][] = $postData['awbNumber'];
                        $votianGdc['val'][] = $dummyVehicle;
                        $votianGdc['val'][] = $postData['orderReferenceId'];

                        // $pickUpStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['pickupEta'] / 1000));
                        // $deliverStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverEta'] / 1000));

                        $pickUpStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['pickupStartTimeWindow'] / 1000));
                        $deliverStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverEndTimeWindow'] / 1000));
                        // $deliverStartTime = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverStartTimeWindow'] / 1000));

                        // $eta = "Keine";

                        // if($lnOrderGetResponse[1]['data'][0]['pickupEta']) {

                        //     $eta = date("Y-m-d H:i:s", ($lnOrderGetResponse[1]['data'][0]['pickupEta'] / 1000));
                        $eta = date("Y-m-d H:i:s", ($lnOrderGetResponseData['deliverEndTimeWindow'] / 1000));

                        // }

                        $votianOrderReqData = array(
                            "order" => array(
                                "auth" => $votianAuthData,
                                "no" => $lnOrderGetResponseData['awbNumber'],
                                "ordertime" => $pickUpStartTime,
                                // "ordertimeUTC" => $postData['startTimeWindow'],
                                "warningtime" => $deliverStartTime,
                                // "warningtimeUTC" => $postData['endTimeWindow'],
                                "remark" => ".",
                                "courier_remark" => ".",
                                "dispoinfo" => "ETA:" . $eta,
                                "gdc" => $votianGdc,
                                "stations" => $votianStations
                            )
                        );

                        $requestResult = executeRESTCall("POST", $requestURLVotian, $votianOrderReqData, "xml");
                        $requestResultXML = simplexml_load_string(array_keys($requestResult[0])[2]);

                        if ($requestResultXML->state == "OK") {

                            $successArray = array(
                                "status" => 201,
                                "message" => "ORDER SUCCESSFULLY CREATED AND ASSIGNED TO VEHICLE"
                            );

                            $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
                            fwrite($myfile,"-----------------------".$postData['orderNo']."---------- SUCCESS-----------". gmdate("Y-m-d\TH:i:s\Z") ."------");
                            fwrite($myfile, array_keys($requestResult[0])[2]);
                            fwrite($myfile, "\n");
                            fwrite($myfile, json_encode($successArray));
                            fwrite($myfile, "\n");
                            fwrite($myfile, "\n");
                            fclose($myfile);

                            return true;

                        } else {

                            setDummyVehicleStatus($availableDummyVehicle['gdc_obj_id'], 0);
                            error("The order could not be created in votian \n" . $requestResultXML->asXML(), $postData['orderNo']);

                        }

                    } else {

                        error("The trip could not be started \n" . json_encode($lnStartTripResult), $postData['orderNo']);

                    }

                } else {

                    error("The order could not be assigned to the driver \n" . json_encode($lnAssignOrder), $postData['orderNo']);

                }

            }

        } else {

            error("Vehicle could not be blocked", $postData['orderNo']);

        }

    } else {

        error("No order information could be found \n" . json_encode($lnOrderGetResponse), $postData['orderNo']);

    }

    return false;

}

function getAvailableDummyVehicle($suffix) {

    global $db;

    // $sql = "SELECT * FROM phoenix.genericdatacontainer WHERE gdc_content = 0 AND gdc_obj_type = 'cr_virtual' AND gdc_gen_fieldname = 'imei' AND gdc_context LIKE '%". $suffix ."'";
    // $result = $db->query($sql);
    // $result = $result->fetch_assoc();
//    $result = $result->fetch_assoc();
    $result = false;

    if(!$result) {

        $createNewVehicleResult = generateVirtualVehicle($suffix);

        if($createNewVehicleResult) {

            $result = $createNewVehicleResult;

        }

    }

    if(setDummyVehicleStatus($result['gdc_obj_id'], 1)) {

        return $result;

    } else {

        error("The vehicle status could not be set");

    }

    $result->free();

}

function generateVirtualVehicle($suffix) {

    global $db, $dblogin, $dbhost, $dbname, $tokenFile;

    // $sql = "SELECT * FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'cr_virtual' AND gdc_gen_fieldname = 'imei' ORDER BY gdc_obj_id DESC LIMIT 0, 1";
    // $result = $db->query($sql);
    // $result = $result->fetch_assoc();
//    $result = $result->fetch_assoc();

    $getVehicleCounter = getVehicleCounter();

    $vehicleCounter = intval(str_replace("STVH", "", str_replace($suffix, "", $getVehicleCounter)))+1;
    $gdc_obj_id = ($getVehicleCounter + 1);

    $insertNewVirtualVehicleSQL = "INSERT INTO phoenix.genericdatacontainer (gdc_obj_type, gdc_obj_id, gdc_gen_fieldname, gdc_content, gdc_context) VALUES ('cr_virtual', '". $gdc_obj_id ."', 'imei', 0, 'STVH". $vehicleCounter . $suffix."')";
    $insertResult = $db->query($insertNewVirtualVehicleSQL);

    $newCreatedVirutalVehicle = array(
        "gdc_obj_type" => "cr_virtual",
        "gdc_obj_id" => $gdc_obj_id,
        "gdc_gen_fieldname" => "imei",
        "gdc_content" => 0,
        "gdc_context" => "STVH".$vehicleCounter.$suffix
    );

    if($insertResult) {

        return $newCreatedVirutalVehicle;

    }

    return false;

}

function getVehicleCounter() {

    global $tokenFile, $db;

    $selectVehicleCounterSQL = "SELECT gdc_content FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'cr_virtual' AND gdc_obj_id = '1' AND gdc_gen_fieldname = 'ups_vehicle_counter'";
    $selectVehicleCounter = $db->query($selectVehicleCounterSQL);
    $selectVehicleCounter = $selectVehicleCounter->fetch_assoc();
    $vehicleCounter = $selectVehicleCounter['gdc_content'];
    $tempCounter = $selectVehicleCounter['gdc_content'] + 1;

    $updateVehicleCounterSQL = "UPDATE phoenix.genericdatacontainer SET gdc_content = '". $tempCounter ."' WHERE gdc_gen_fieldname = 'ups_vehicle_counter' AND gdc_obj_type = 'cr_virtual' AND gdc_obj_id = '1'";
    $updateVehicleCounter = $db->query($updateVehicleCounterSQL);

    return $vehicleCounter;

    // $file = fopen(getAbsoluteSystemPathLN()."/vehicleCounter.txt", 'r');
    // $token = fgets($file);
    // fclose($file);

    // $token = json_decode($token, true);

    // if(!isset($token['vehicleCounter'])) {

    //     $token['vehicleCounter'] = 3000;

    // }

    // $counter = $token['vehicleCounter'];

    // $fileContent = file_get_contents(getAbsoluteSystemPathLN()."/vehicleCounter.txt");
    // $fileNew = fopen(getAbsoluteSystemPathLN()."/vehicleCounter.txt", 'w');

    // $authJson = json_decode($fileContent, true);

    // $authJson['vehicleCounter'] = $token['vehicleCounter']+1;

    // fwrite($fileNew, json_encode($authJson));
    // fclose($fileNew);

    // return $counter;

}

function setDummyVehicleStatus($dummyVehicleId, $status) {

    global $db;

    $sql = "UPDATE phoenix.genericdatacontainer SET gdc_content = '". $status ."' WHERE gdc_obj_id = '". $dummyVehicleId ."' AND gdc_obj_type = 'cr_virtual' AND gdc_gen_fieldname = 'imei'";
    $result = $db->query($sql);

    return $result;

}


function votianGetOrderInfo($orderReferenceId) {

    global $db;

    $selectJbIdSql = "SELECT gdc_obj_id FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_3' AND gdc_content = '". $orderReferenceId ."'";
    $selectJbId = $db->query($selectJbIdSql);
    $selectJbId = $selectJbId->fetch_assoc();
//    $selectJbId = $selectJbId->fetch_assoc();
    $jbId = $selectJbId['gdc_obj_id'];

    $selectOrderNoSql = "SELECT gdc_content FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_0' AND gdc_obj_id = '". $jbId ."'";
    $selectOrderNo = $db->query($selectOrderNoSql);
    $selectOrderNo = $selectOrderNo->fetch_assoc();
//    $selectOrderNo = $selectOrderNo->fetch_assoc();
    $orderNo = $selectOrderNo['gdc_content'];

    $selectOrderTimeWarningUTCSql = "SELECT jb_ordertime, jb_warningtime FROM phoenix.job WHERE jb_id  = '". $jbId ."'";
    $selectOrderTimeWarningUTC = $db->query($selectOrderTimeWarningUTCSql);
    $selectOrderTimeWarningUTC = $selectOrderTimeWarningUTC->fetch_assoc();
//    $selectOrderTimeWarningUTC = $selectOrderTimeWarningUTC->fetch_assoc();
    $orderTimeUTC = gmdate('Y-m-d H:i:s', strtotime($selectOrderTimeWarningUTC['jb_ordertime']));
    $warningTimeUTC = gmdate('Y-m-d H:i:s', strtotime($selectOrderTimeWarningUTC['jb_warningtime']));

    $resultArray = array(
        "orderReferenceId" => $orderReferenceId,
        "order_no" => $orderNo,
        "end_date" => $warningTimeUTC,
        "start_date" => $orderTimeUTC,
    );

    return $resultArray;

}

function votianGetImei($orderReferenceId) {

    global $db;

    $selectJbIdSql = "SELECT gdc_obj_id FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_3' AND gdc_content = '". $orderReferenceId ."'";
    $selectJbId = $db->query($selectJbIdSql);
    $selectJbId = $selectJbId->fetch_assoc();
//    $selectJbId = $selectJbId->fetch_assoc();
    $jbId = $selectJbId['gdc_obj_id'];

    $selectOrderNoSql = "SELECT gdc_content FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_2' AND gdc_obj_id = '". $jbId ."'";
    $selectOrderNo = $db->query($selectOrderNoSql);
    $selectOrderNo = $selectOrderNo->fetch_assoc();
//    $selectOrderNo = $selectOrderNo->fetch_assoc();
    $imei = $selectOrderNo['gdc_content'];

    $branchArray = array(
        "_34575437", "_32214321352135", "_38934897"
    );

    foreach ($branchArray as $key => $value) {

        $imei = str_replace($value, "", $imei);

    }

    return $imei;

}

function haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000) {

    // convert from degrees to radians
    $latFrom = deg2rad($latitudeFrom);
    $lonFrom = deg2rad($longitudeFrom);
    $latTo = deg2rad($latitudeTo);
    $lonTo = deg2rad($longitudeTo);

    $latDelta = $latTo - $latFrom;
    $lonDelta = $lonTo - $lonFrom;

    $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
            cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
    return number_format($angle * $earthRadius, 2, '.', '');

}

function votianCheckFistTrack($imei) {

    global $db;

    $selectJbIdSql = "SELECT gdc_obj_id FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_2' AND gdc_content = '". $imei ."'";
    $selectJbId = $db->query($selectJbIdSql);
    $selectJbId = $selectJbId->fetch_assoc();
//    $selectJbId = $selectJbId->fetch_assoc();
    $jbId = $selectJbId['gdc_obj_id'];

    $selectFristTrackSql = "SELECT gdc_content FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_4' AND gdc_obj_id = '". $jbId ."'";
    $selectFristTrack = $db->query($selectFristTrackSql);
    $selectFristTrack = $selectFristTrack->fetch_assoc();
//    $selectFristTrack = $selectFristTrack->fetch_assoc();
    $firstTrack = $selectFristTrack['gdc_content'];

    return json_decode($firstTrack, true);

}

function votianSaveLastTrack($imei, $lastTrackJson) {

    global $db;

    $lastTrackJson = json_encode($lastTrackJson);

    $selectJbIdSql = "SELECT gdc_obj_id FROM phoenix.genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_2' AND gdc_content = '". $imei ."'";
    $selectJbId = $db->query($selectJbIdSql);
    $selectJbId = $selectJbId->fetch_assoc();
//    $selectJbId = $selectJbId->fetch_assoc();
    $jbId = $selectJbId['gdc_obj_id'];

    if(votianCheckFistTrack($imei)) {

        $updateFristTrackSql = "UPDATE phoenix.genericdatacontainer SET gdc_content = '". $lastTrackJson ."' WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_4' AND gdc_obj_id = '". $jbId ."'";

    } else {

        $updateFristTrackSql = "INSERT INTO phoenix.genericdatacontainer (gdc_obj_type, gdc_obj_id, gdc_gen_fieldname, gdc_content) VALUES ('jb', '". $jbId ."', 'info_4', '". $lastTrackJson ."')";

    }

    $updateFristTrack = $db->query($updateFristTrackSql);

    return $updateFristTrack;

}

function getSuffix($branchName) {

    $branchArray = array(
        "WFRA5_34575437" => "_34575437",
        "WHAJ1_32214321352135" => "_32214321352135",
        "WSTR1_38934897" => "_38934897"
    );

    return $branchArray[$branchName];

}

function getAddressFromString($addressString) {

    $explodeString = explode(",", $addressString);

    $output_array = array();
    preg_match('/[0-9]+ *[a-zA-Z]*$/', $explodeString[0], $output_array);

    if(empty($output_array)) {

        preg_match('/[0-9]+ *[a-zA-Z]*$/', $explodeString[1], $output_array);

    }

    $streetOne = str_replace($output_array[0], "", $explodeString[0]);
    $streetTwo = str_replace($output_array[0], "", $explodeString[1]);

    $resultAddressArray = array(
        "street1" => $streetOne,
        "street2" => "",
        "street3" => "",
    );

    if($streetTwo != "-") {

        $resultAddressArray['street2'] = $streetTwo;

    }

    $resultAddressArray['hsno'] = $output_array[0];

    if(count($explodeString) > 5 ) {

        if($explodeString[2] != "-") {

            $resultAddressArray['street3'] = $explodeString[2];

        }

        $resultAddressArray['city'] = $explodeString[count($explodeString)-3];
        $resultAddressArray['zipcode'] = $explodeString[count($explodeString)-1];
        $resultAddressArray['country'] = $explodeString[count($explodeString)-2];

    } else  {

        $resultAddressArray['city'] = $explodeString[count($explodeString)-3];
        $resultAddressArray['zipcode'] = $explodeString[count($explodeString)-1];
        $resultAddressArray['country'] = $explodeString[count($explodeString)-2];

    }

    return $resultAddressArray;

}

function votianGetLastTrackStatusUpdate($crUsrID, $timestamp) {

    global $db;

    $resultArray = array();

    $selectLastLocationSql = "SELECT loc_type, ROUND(loc_long, 8) AS loc_long, ROUND(loc_lat, 8) AS loc_lat, loc_acc, loc_time, loc_created FROM phoenix_log.locating WHERE usr_id = ". $crUsrID ." AND loc_type != 3 AND loc_type != 14 AND loc_type != 9 AND ((loc_time != '0000-00-00 00:00:00' AND loc_time <= '".$timestamp."') OR (loc_time = '0000-00-00 00:00:00' AND loc_created <= '".$timestamp."')) ORDER BY loc_created DESC LIMIT 0, 1";
    $selectLastLocation = $db->query($selectLastLocationSql);
    $selectLastLocation = $selectLastLocation->fetch_assoc();

    $resultArray['lat'] = $selectLastLocation['loc_lat'];
    $resultArray['lon'] = $selectLastLocation['loc_long'];

    return $resultArray;

}