<?php

include_once "LN_rest_include.php";
include_once "LN_curl_include.php";
include_once "LN_votian_include.php";

$requestURL = "https://api.loginextsolutions.com/";
$tokenUserName = "mv@assecutor.de";
$tokenPassword = "ADSGmv8";
$tokenTimeout = "87600";
$tokenFile = hash('sha256', "token");

function getAbsoluteSystemPathLN () {
 // $dirName = dirname(__FILE__);
 // $dirName = str_replace("\\", "/", $dirName);
 // $lastSlashPos = strrpos($dirName,"/");
 // $path = substr($dirName, 0, $lastSlashPos);
 return dirname(__FILE__);
}

/*---------------------------------------------------LogiNext -> Authentication---------------------------------------*/

/*
 * Generate Token if none is Provided or Token is expired
 *
 * Response:
 *
 * {
 * "status": 200,
 * "message": "success",
 * "data": null,
 * "hasError": false
 * }
 *
 * */

function getToken() {

    global $tokenFile;

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

    $token = json_decode($token, true);

    return $token['mainAuth'];

}

function getAssociateToken($associate) {

    global $tokenFile;

    $assPass = $associate;

    if (strpos($associate, '_') !== false) {

        $temp = explode("_", $associate);
        $assPass = $temp[0];

    }

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

    $token = json_decode($token, true);

    return $token[$assPass];

}

function generateToken() {

    global $requestURL, $tokenUserName, $tokenPassword,  $tokenTimeout, $tokenFile;

    $requestData = array(
        "userName" => $tokenUserName,
        "password" => $tokenPassword,
        "sessionExpiryTimeout" => $tokenTimeout
    );

    $response = executeRESTCall("POST", $requestURL . "LoginApp/login/authenticate", $requestData, "json", array('Content-Type:application/json'), "mainAuth");

    $responseHeader = $response[0];
    $responseBody = $response[1];

    if($responseBody['status'] == 200 && $responseBody['hasError'] == false) {

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

        $authJson = json_decode($fileContent, true);

        $authJson['mainAuth'] = $responseHeader['WWW-Authenticate'];

        fwrite($file, json_encode($authJson));
        fclose($file);

        return true;

    } else {

        die("ERROR");

    }

}

function generateAssociateToken($associate) {

    global $requestURL, $tokenFile;

    $assPass = $associate;

    if (strpos($associate, '_') !== false) {

        $temp = explode("_", $associate);
        $assPass = $temp[0];

    }

    $requestData = array(
        "userName" => $associate,
        "password" => $assPass,
        "imei" => $associate,
        "androidId" => $associate,
        "androidTime" => gmdate("Y-m-d\TH:i:s\Z")
    );

    $responseTemp = executeRESTCall("POST", $requestURL . "LoginApp/login/mobile/auth", $requestData, "json", array('Content-Type:application/json', 'WWW-Authenticate:'. getToken()), "mainAuth");

    $responseHeader = $responseTemp[0];
    $responseBody = $responseTemp[1];

    // var_dump($responseBody);

    if($responseBody['status'] == 200 && $responseBody['hasError'] == false) {

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

        $authJson = json_decode($fileContent, true);

        $authJson[$assPass] = $responseHeader['WWW-Authenticate'];

        fwrite($file, json_encode($authJson));
        fclose($file);

        return true;

    } else {

        die("ERROR");

    }

}

/*
 * Call the mobile authenticate API to obtain the authentication token for a Delivery Associate.
 * You will have to pass the username and password entered at the time of creating the Delivery Associate in the LogiNext system in the request body.
 * The response will contain an authentication token which is unique to every specific Delivery Associate. This token will have a validaity of 4 years from the time of creation.
 * API Type: Tier 2 API
 *
 * Parameter	DataType	Length	Required	Description
 * userName	String	255	Mandatory	Username entered when created the Delivery Associate in the LogiNext system
 * password	String	255	Mandatory	Password entered when created the Delivery Associate in the LogiNext system
 * imei	String	50	Mandatory	IMEI Number of the Delivery Associate’s phone
 * latitude	Double	10,13	Optional	Geolocation(latitude) coordinate of the Delivery Associate
 * longitude	Double	10,13	Optional	Geolocation(longitude) coordinate of the Delivery Associate
 * androidId	String	10	Optional	Device ID of the Delivery Associate
 * androidTime	Date		Optional	Current Date and Time in UTC and the mentioned Format. Sample Value - 2017-12-11T07:21:39Z
 * */
function authenticationAuthenticateDeliveryAssociate() {

    global $requestURL;

    $data = array(
        "userName" => "johnc",
        "password" => "admin",
        "imei" => "854437655912443",
        "latitude" => "40.1114131",
        "longitude" => "74.9094666",
        "androidId" => "ce6448cf20b78483",
        "androidTime" => "2017-04-21T05:53:47Z"
    );

    $requestResult = executeRESTCall("POST", $requestURL."LoginApp/login/mobile/auth", $data);

    var_dump($requestResult);

}


/*---------------------------------------------------LogiNext -> Order------------------------------------------------*/

/*
 * GET ORDER DETAILS
 *
 * Retrieve orders and all the order associated information with this API.
 * API Type: Tier 1 API
 *
 * https://api.loginextsolutions.com/ShipmentApp/mile/v1/shipment?end_date=2017-03-07+18:29:59&start_date=2016-02-01+18:30:00&status=ALL&order_no=GKS12567&orderReferenceId=f40cf4493a5949199775499b5750a272&customer_code=123&employee_id=134367&page_no=1&page_size=10
 *
 * Param	DataType	Length	Required	Description
 * start_date	Date		Conditional Mandatory	If order_no is not passed in the request, then this field is mandatory. Range of date from which orders can be searched. This will return orders based on the order fulfillment date start time window.
 * Format 'yyyy-MM-dd HH:mm:ss’
 * end_date	Date		Conditional Mandatory	If order_no is not passed in the request, then this field is mandatory. Range of date upto which orders can be searched. This will return orders that have fulfillment end times less than the entered time.
 * Format 'yyyy-MM-dd HH:mm:ss’
 * status	String	20	Optional	If order_no is passed in the request,then status will not be considered for filtering the orders.Order status.
 * Ex: NOTDISPATCHED,INTRANSIT,COMPLETED,
 * NOTCOMPLETED,PICKEDUP(Only for First Mile),CANCELLED
 * order_no	String	100	Optional	Order Number(Only one order number can be passed at a time.If not passed ,all the orders for the specified date range will be fetched)
 * orderReferenceId	String	100	Optional	Order Reference ID(Only one order number can be passed at a time.If not passed, all the orders for the specified date range will be fetched)
 * page_no	Integer		Optional	This parameter lets you specify the page number. It is used to page through the orders. This is optional parameter and default value (if it isn’t specified) will be 1.
 * page_size	Integer		Optional	This parameter lets you specify the count of orders to return in your API call. This is optional parameter and default value (if it isn’t specified) will be 50. The maximum accepted value is 100; higher values will be accepted but you will only get 100 records.
 * customer_code	String		Optional	This is the Customer Address ID parameter. You can pass one customer Id at a time. The result will be list of all the orders created for the mentioned customer ID
 * employee_id	String		Optional	This is the Driver National ID parameter. You can pass one driver Id at a time. The result will be list of all the orders which were assigned to this Driver ID
 *
 * */
function logiNextMileOrderGet($requestData) {

    global $requestURL;

    $data = $requestData;

    // $data = array(
    //     "end_date" => $requestData['end_date'],
    //     "start_date" => $requestData['start_date'],
    //     "status" => $requestData['status'],
    //     "order_no" => $requestData['order_no'],
    //     "orderReferenceId" => $requestData['orderReferenceId'],
    //     "customer_code" => $requestData['customer_code'],
    //     "employee_id" => $requestData['employee_id'],
    //     "page_no" => $requestData['page_no'],
    //     "page_size" => $requestData['page_size']
    // );

    $requestResult = executeRESTCall("GET", $requestURL."ShipmentApp/mile/v1/shipment", $data);

    return $requestResult;

//    $requestResult = json_decode('{
//   "status":200,
//   "message":"SUCCESS",
//   "referenceId":null,
//   "data":[
//      {
//         "referenceId":"f40cf4493a5949199775499b5750a272",
//         "orderNo":"GR432U5",
//         "parentOrderNo":"GKS12",
//         "awbNumber":"435-16685675",
//         "clientName":"UNY Logistics",
//         "branchName":"West Brooklyn",
//         "origin":"West Brooklyn",
//         "destination":"2142 3rd Ave",
//         "shipmentOrderTypeCd":"DELIVER",
//         "orderState":"FORWARD",
//         "preparationTime":20,
//         "shippingCost":50,
//         "deliveryType":"TRK",
//         "deliveryLocationType":"PUP",
//         "shipmentOrderDt":1595498400,
//         "startTimeWindow":1595498400,
//         "endTimeWindow":1595598400,
//         "priority":"PRIORITY1",
//         "serviceType":"Express",
//         "paymentType":"COD",
//         "orderState":"FORWARD",
//         "notes":"Order recieved successfully.Thanks",
//         "packageValue":0,
//         "shippingCost":50,
//         "recalculatedValue":0,
//         "status":"DELIVERED",
//         "plannedServiceTime":5,
//         "serviceTime":2,
//         "deliveryMediumName":"5T-ACOM2",
//         "assignedThrough":"Manually",
//         "tripName":"T35D33",
//         "deliverEta":1597327443000,
//         "pickupEta":1597324443000,
//         "actualTravelledDistance":0,
//         "actualStartDt":1485154380000,
//         "actualEndDt":1485155021000,
//         "plannedDistance":16.708,
//         "actualDistance":6430.184,
//         "distanceFromHub":null,
//         "plannedStartDt":1485154380000,
//         "plannedEndDt":1485155640000,
//         "timeTakenDifferenceInMins":10,
//         "originLatitude":40.760838,
//         "originLongitude":-73.96732299999996,
//         "employeeId":3224567,
//         "pickupCheckInTime":1485154765000,
//         "pickupCheckOutTime":1485154887000,
//         "pickupCheckInLatitude":40.760838,
//         "pickupCheckInLongitude":-73.96732299999996,
//         "pickupCheckOutLatitude":40.760838,
//         "pickupCheckOutLongitude":-73.96732299999996,
//         "destinationLatitude":41.882702,
//         "destinationLongitude":101.706872,
//         "deliverCheckInTime":1485154905000,
//         "deliverCheckOutTime":1485155021000,
//         "deliverCheckInLatitude":41.882702,
//         "deliverCheckInLongitude":-87.61939,
//         "deliverCheckOutLatitude":41.882702,
//         "deliverCheckOutLongitude":-87.61939,
//         "orderSequence":5,
//         "pickupAccountCode":"PDT_124",
//         "customerCode":"CST_ACL1",
//         "customerName":"Steven Goods",
//         "amountCollected":200,
//         "podCount":2,
//         "noOfCrates":1,
//         "packageWeight":0,
//         "packageVolume":0,
//         "customerComments":"",
//         "deliveryNotes":"Order delivered successfully",
//         "customerRatings":5,
//         "customerPhoneNumber":"5163063377",
//         "deliveryMediumPhoneNumber":"3125096995",
//         "reason":null,
//         "vehicleNumber":"AC2T123",
//         "noOfAttempts":1,
//         "deliveryGeofenceEnterTime":1484727378000,
//         "deliveryGeofenceExitTime":1484727387000,
//         "isDelayed":false,
//         "partialDeliveryAllowedFl":false,
//         "returnAllowedFl":false,
//         "cancellationAllowedFl":false,
//         "delayedBy":null,
//         "pickupEmail":"steve@movenpick.com",
//         "deliverEmail":"james@ablog.com",
//         "shipmentCrateMappings":[
//            {
//               "crateCd":"Crate1",
//               "statusCd":"UNLOADED",
//               "crateType":"CRATE",
//               "crateAmount":0,
//               "shipmentlineitems":[
//
//               ],
//               "noOfUnits":1,
//               "loadedUnits":1,
//               "unloadedUnits":1,
//               "orderNo":"TEST_ACL1",
//               "crateQuantity":0,
//               "amountToCollect":0
//            }
//         ]
//      }
//   ],
//   "hasError":false
//}', true);
//
//    return array("", $requestResult);

}

/*
 * With this API, you can add Orders to a particular Trip or a Delivery Associate’s Default, Not Started Trip.
 * If you have a set of Orders to be manually assigned to a particular Delivery Associate or Trip, for eg- in the case that a Delivery Associate is Abesent or On Break, you can assign the Orders to be fulfilled to another Trip of another Delivery Associate using this API.
 * The API will take as input the Trip or Delivery Associate details and the list of orders to be added for that trip or Delivery Associate. The API can be used in 2 ways: If the trip details are passed (through trip reference id), then Delivery Associate details are not required and the list of orders will be added to that trip, irrespective of the trip being Started or Not Started. Other order and trip validations remain as is. If the trip details are not passed, then the Delivery Associate details will be required to be passed, either through username, mobile number or employee id (unique identifiers) and a control flag identifying which of these values is being passed. The orders will be added to the Default trip (Started or Not Started) of the Delivery Associate.
 * API Type: Tier 1 API
 *
 * Param	DataType	Length	Required	Description
 * trip.referenceId	String	32	Conditional Mandatory	Reference ID of the trip to which the Order has to be assigned. This field has to be passed in case the Delivery Associate details are not passed.
 * deliveryMedium.identifier	String	32	Conditional Mandatory	This is the control flag field for the Delivery Associate, to identify which details of the Delivery Associate are being passed. Possible values are 'employeeId’, 'phoneNumber’, 'userName’.
 * deliveryMedium.identifierValue	String	32	Conditional Mandatory	This field will hold the Delivery Associate information to whom the Order is to be assigned, as per the flag set above. For eg - If you wish to assign an Order to a Delivery Associate whose 'employeeId’ is 'John1’, you would send 'employeeId’ in the identifier field and 'John1’ in the identifierValue field.
 * orderReferenceIds	List		Mandatory	These are the Reference IDs of the Order to be assigned.
 * */
function logiNextMileOrderAssign($referenceID, $vehicleID) {

    global $requestURL;

//    {
//        "deliveryMedium":{
//        "identifier":"employeeId",
//    "identifierValue":"STVH1011"
//  },
//  "orderReferenceIds":["955b188a9e884b7e823bc50a7296ae74"]
//}

    $data = array(
//        "trip" => array(
//            "referenceId" => $referenceID
//        ),
        "deliveryMedium" => array(
            "identifier" => "employeeId",
            "identifierValue" => $vehicleID,
        ),
        "orderReferenceIds" => array(
            $referenceID,
        )
    );

    $requestResult = executeRESTCall("PUT", $requestURL."ShipmentApp/mile/v1/manual/assign", $data);

    return $requestResult;

}

/*
 * With this API, you will be able to update the the status of a Order. You can pass multiple Order reference IDs and can update one or more parameters.
 * API Type: Tier 1 API
 *
 * Param	DataType	Length	Required	Description
 * newStatus	String	20	Mandatory	One status for multiple orders.The orders will be updated with this new status
 * Available Values -
 * DELIVERED - When an order has been Delivered by the associate
 * NOTPICKEDUP - When the associate reached the Pick-up location, but could not pick-up the order due to one or the other reason
 * NOTDELIVERED - When the associate reached the delivery location, but could not deliver the order due to one or the other reason
 * orderReferenceId	String	100	Mandatory	This is the LogiNext Reference ID for the Order
 * This is generated when the order is added in the LogiNext application.
 * reasonCd	String	255	Conditional Mandatory	Mandatory depending upon the status selected : NOTDELIVERED, NOTPICKEDUP, CANCELLED
 * Else Optional.
 * If you have pre-configured the reasons for Order Status Update - NOTDELIVERED, NOTPICKEDUP and CANCELLED in LogiNext application, then it is mandatory to mention that relevant configured reason here.
 * One of the other values here is Other, in case the delivery Associate selects the reason as Others.
 * otherReason	Date		Conditional Mandatory	Mandatory when reasonCd is OTHER
 * latitude	Double	15	Conditional Optional	Geo-location where Order status was updated
 * Sample Value - “17.996”
 * otherReason	Date	15	Conditional Optional	Geo-location where Order status was updated
 * Sample Value - “17.996”
 * updateTime	Date	15	Conditional Optional	This is the timestamp (in UTC format) when the order status was changed. This cannot be greater than the time at which the API is hit. If not passed, the timestamp of the API hit is considered as the timestamp for the status change.
 * */
function logiNextMileOrderUpdateStatus($orderStatus) {

    global $requestURL;

    $data = $orderStatus;

    $requestResult = executeRESTCall("PUT", $requestURL."ShipmentApp/mile/v1/update/status", $data);

    return $requestResult;

}


/*---------------------------------------------------LogiNext -> Associate--------------------------------------------*/

/*
 * Create a new Delivery Associate in the LogiNext system with this API. A delivery associate will be created and assigned a unique Reference ID that can be used to identify the Delivery Associate later.
 * Address field validations will be based on the behaviour defined in the Address Configuration screen of your LogiNext accounthere
 * API Type: Tier 1 API
 *
 * Parameter	DataType	Length	Required	Description
 * employeeId	String	50	Mandatory	Delivery Associate employee ID.
 * userGroupName	String	255	Mandatory	Delivery Associate user group name.
 * branchName	String	255	Mandatory	Delivery Associate client branch name.
 * deliveryMediumMasterName	String	255	Mandatory	Delivery Associate full name.
 * phoneNumber	String	255	Mandatory	Delivery associate mobile number.
 * imei	String	40	Optional	TDelivery Associate IMEI number.
 * emailId	String	100	Optional	Delivery Associate email ID.
 * userName	String	255	Mandatory	Delivery Associate username.
 * password	String	255	Mandatory	Delivery Associate password.
 * capacityInUnits	Integer	20	Mandatory	Delivery Associate capacity in units.
 * capacityInVolume	Integer	20	Optional	Delivery Associate capacity in volume.
 * capacityInWeight	Integer	20	Optional	Delivery Associate capacity in weight.
 * dob	String		Optional	Delivery Associate date of birth.
 * gender	ISODate	12	Optional	Delivery Associate Gender. Ex - Male,Female.
 * deliveryMediumMasterTypeCd	String	255	Optional	Delivery Associate type. For example, 'Bakery’ if the Delivery Associate can fulfill Bakery type of Orders 'Groceries’ if the Delivery Associate can fulfill Groceries’ type of Orders. This will be mapped to the 'deliveryType’ field at the Order level.
 * vehicleNumber	String	255	Optional	delivery associate Vehicle number.
 * isOwnVehicleFl	String	1	Optional	Owner of vehicle. Ex - Owned, Company
 * maxDistance	Integer	20	Optional	This is the maximum distance the Delivery Associate is allowed to cover within a trip. This value is considered when creating a route plan for the Delivery Associate.
 * dmPreference	String	255	Optional	Delivery Associate Preferred Pincode. The Route Planning engine will consider this piccode preference when assignming Orders to the Delivery Associate if the Pin Code Preference’ property is set.
 * maritalStatus	String	Optional	255	Delivery Associate Marital Status.
 * alternateMobileNo	String	Optional	255	Delivery Associate alternate Mobile NUmber.
 * landlineNo	String	Optional	255	Delivery Associate landline Number.
 * licenseValidity	String	Optional	255	This is the expiry Date of the Driver’s License in YYYY-MM-HH format.
 * licenseValidityInYears	Optional	String	255	Delivery Associate license Validity in years.
 * licenseIssuanceDate	String	Optional	255	Delivery Associate license issuance Date in YYYY-MM-HH format.
 * loadingTimeInMins	Number	Optional	32	Average time taken to load Orders into the Vehicle at the Pickup location. This can be different for different types of Fleet. A larger Vehicle may require more time to load, whereas a small Vehicle may require only a few minutes.
 * unloadingTimeInMins	Number	Optional	32	Average time taken to load Orders into the Vehicle at the Delivery location. This can be different for different types of Fleet. A larger Vehicle may require more time to load, whereas a small Vehicle may require only a few minutes.
 * fixedCost	Number	Optional	Fixed cost associated with using a delivery medium in Route Optimization.
 * variableCost	Number	Optional	Variable cost associated with each unit of distance travelled by the Delivery Associate during a trip. This is considered in Route Optimization
 * weeklyOffList	String	255	Optional	Delivery Associate days off. Ex - Monday, Tuesday etc.
 * deliveryMediumMapList.name	String	255	Optional	Delivery Associate language list.
 * shiftTimeList.shiftStartTime	String		Optional	Delivery Associate Shift start time in HH:MM format.
 * shiftTimeList.shiftEndTime	String		Optional	Delivery Associate Shift end time in HH:MM format.
 * breakTimeList	List		Optional	This is the break time of the Delivery Associate. The LogiNext Route Planning engine will not assign orders with Service time windows within a Delivery Associate’s break time to that Delivery Associate.
 * breakTimeList.breakStartTime	String		Optional	Delivery Associate Break start time in HH:MM format.
 * breakTimeList.breakEndTime	String		Optional	Delivery Associate Break end time in HH:MM format.
 + breakTimeList.breakDurationInMins	Integer		Optional	Delivery Associate Break Time Duration in minutes
 + addressList	List			Delivery Associate address details.
 * addressList.apartment	String	Optional	255	Delivery Associate Apartment number.
 * addressList.streetName	String	Optional	255	Delivery Associate Street Name.
 * addressList.landmark	String	Optional	255	Delivery Associate landmark.
 * addressList.countryShortCode	String	Optional	255	This is the Delivery Associate country code. Please refer to the list of country codes provided in the “Country Codes” section.
 * addressList.city	String	Optional	255	Delivery Associate city.
 * addressList.pincode	String	Optional	255	Delivery Associate postal code.
 * addressList.addressType	String	Optional	255	Identifies if this is the current or permanent address of the Delivery Associate. If set to “CURRENT”, it will select the entered address as current. If “PERMANENT”, it will set the entered address as permanent. This field does not accept any other value. You must send this field if adding an address for the Delivery Associate.
 * */
function logiNextMileDeliveryAssociateCreate($vehicleData) {

    global $requestURL;

//    $data = array(
//                array(
//                    "addressList" => array(
//                        array(
//                            "addressType" => "PERMANENT",
//                            "apartment" => "901",
//                            "city" => "Ney York",
//                            "countryShortCode" => "USA",
//                            "landmark" => "Opp. McDonalds",
//                            "pincode" => "10035",
//                            "streetName" => "2142 3rd Ave"
//                        ),
//                        array(
//                            "addressType" => "CURRENT",
//                            "apartment" => "901",
//                            "city" => "New York",
//                            "countryShortCode" => "USA",
//                            "landmark" => "Opp McDonalds",
//                            "pincode" => "10035",
//                            "streetName" => "2142 3rd Ave"
//                        ),
//                    ),
//                    "alternateMobileNo" => 9892134489,
//                    "branchName" => "California",
//                    "breakTimeList" => array(
//                        array(
//                            "breakDurationInMins" => 12,
//                            "breakEndTime" => "13:30",
//                            "breakStartTime" => "13:00"
//                        )
//                    ),
//                    "capacityInUnits" => 10,
//                    "capacityInVolume" => 10,
//                    "capacityInWeight" => 10,
//                    "deliveryMediumMapList" => array(
//                        array(
//                            "name" => "SPANISH"
//                        ),
//                        array(
//                            "name" => "ENGLISH"
//                        )
//                    ),
//                    "deliveryMediumMasterName" => "James",
//                    "deliveryMediumMasterTypeCd" => "Bakery",
//                    "dmPreference" => "10035",
//                    "dob" => "2016-12-12",
//                    "emailId" => "james@ablogistics.com",
//                    "employeeId" => "",
//                    "fixedCost" => 10,
//                    "gender" => "Male",
//                    "imei" => 123456789012123,
//                    "isOwnVehicleFl" => "Company",
//                    "isPresentFl" => "Y",
//                    "landlineNo" => 28215678,
//                    "licenseIssuanceDate" => "2016-12-12",
//                    "licenseNumber" => 2123123123,
//                    "licenseValidity" => "2026-12-12",
//                    "licenseValidityInYears" => 10,
//                    "loadingTimeInMins" => 20,
//                    "maritalStatus" => "Single",
//                    "maxDistance" => 10,
//                    "password" => "admin",
//                    "phoneNumber" => 9892147969,
//                    "shiftTimeList" => array(
//                        array(
//                            "shiftEndTime" => "14:30",
//                            "shiftStartTime" => "12:30"
//                        )
//                    ),
//                    "unloadingTimeInMins" => 20,
//                    "userGroupName" => "MobileUser",
//                    "userName" => "james003",
//                    "variableCost" => 10,
//                    "vehicleNumber" => "1AB54F",
//                    "weeklyOffList" => array(
//                        "Thursday",
//                        "Monday"
//                    )
//                )
//            );

    $data = $vehicleData;

    $requestResult = executeRESTCall("POST", $requestURL."DeliveryMediumApp/mile/v1/create", $data);

    return $requestResult;

}

function logiNextMileDeliveryAssociateGet($referenceId) {

    global $requestURL;

    $data = array(
        $referenceId
    );

    $requestResult = executeRESTCall("POST", $requestURL."DeliveryMediumApp/mile/v1/list", $data);

    return $requestResult;
}


/*---------------------------------------------------LogiNext -> Trip-------------------------------------------------*/

/*
 * Get all the details of a trip with this API. You can call this API to get the Order ETAs for Orders within a particular trip. The API will provide both the original ETAs and revised ETAs of Orders within that trip.
 * API Type: Tier 1 API
 * Param	    DataType	Length	Required	Description
 * referenceId	String		        Conditional Mandatory	If tripname is not passed in the request, then this field is mandatory. This is the reference ID of the trip.
 * tripname	    String		        Conditional Mandatory	If referenceId is not passed in the request, then this field is mandatory. This is the trip name of the trip for which details are to be fetched.
 * */
function logiNextMileTripStop($data) {

    global $requestURL;

    $requestResult = executeRESTCall("POST", $requestURL."TripApp/mile/v1/trip/stop", $data);

    return $requestResult;

}

/*
 * Start the trip for a Delivery Associate using this API.
 * Parameter	DataType	Required	Description
 * reference_ids	List	Mandatory	Reference Id associated with the trip.
 * */
function logiNextMileTripStart($tripNameList) {

    global $requestURL;

    $data = $tripNameList;

    $requestResult = executeRESTCall("POST", $requestURL."TripApp/mile/v1/trip/start", $data);

    return $requestResult;

}


/*---------------------------------------------------LogiNext -> Mobile-----------------------------------------------*/

/*
 * With this API, the Delivery associate can Check In at the time of Order Delivery at the Deliver location.
 * Please note that in headers for this API, you will have to pass the Delivery Associate’s Token and Key and not the Account level Token and Key.
 * You can fetch the Delivery Associate’s Token and Key by calling the Delivery Associate Authenticate API.
 * API Type: Tier 2 API
 *
 * Parameter	DataType	Length	Required	Description
 * orderReferenceId	List	32	Mandatory	This is the LogiNext Order Reference ID created when the order is added in the LogiNext system.
 * If your Order is Single Pick-up - Single destination, then pass the Order Reference ID generated against that Order No.
 * If your Order is Single Pick-up - Multiple destination, then pass any one of the order’s Reference ID.
 * checkInLocation	String	100	Mandatory	This can be “PICKUP” or “DELIVER”.
 * checkinLatitude	Double	100	Optional	Geocoordinate(Latitude) for the Check In location.
 * checkinLongitude	Double	100	Optional	Geocoordinate(Longitude) for the Check In location.
 * checkInTime	Date	100	Mandatory	Check In Time in UTC format - YYYY-MM-DDTHH:MM:SS.SSSZ e.g. : 2016-07-01T11:18:00.000Z.
 * */
function logiNextMileMobileCheckIn($orderPickedUpData) {

    global $requestURL;

    $orderPickedUpTime = $orderPickedUpData['checkInTime'];

    // if(!$orderPickedUpTime) {

    //     $orderPickedUpTime = gmdate("Y-m-d\TH:i:s\Z");

    // }

    $orderPickedUp = array(
        "orderReferenceIds" => array($orderPickedUpData['orderReferenceIds']),
        "checkInLocation" => $orderPickedUpData['checkInLocation'],
        "checkinLatitude" => $orderPickedUpData['checkinLatitude'],
        "checkinLongitude" => $orderPickedUpData['checkinLongitude'],
        "checkInTime" => $orderPickedUpTime,
    );

    lnFunctionLog(array(
        "function" => "logiNextMileMobileCheckIn - ". time(),
        "type" => json_encode($orderPickedUpData),
        "data" => json_encode($orderPickedUp)
    ));

    $imei = votianGetImei($orderPickedUpData['orderReferenceIds']);

    $requestResult = executeRESTCall("PUT", $requestURL."ShipmentApp/v1/mobile/checkin", $orderPickedUp, "json", array('Content-Type:application/json', 'WWW-Authenticate:'. getAssociateToken($imei)), $imei);

    return $requestResult;

}

/*
 *With this API, you can send the current position of your Delivery Associates / Field Executives when they are not using LogiNext Mobile App.
 * Note that the 'msg’ field in the API success response is the time at which the API is called. The 'previousTime’ field in the success response is the timestamp of previous tracking date in epoch format.
 * API Type: Tier 2 API
 *
 * Parameter	DataType	Length	Required	Description
 * latitude	Double	13,10	Mandatory	The geocoordinate(Latitude) of the Delivery Associate’s location. Sample Value - 40.760838
 * longitude	Double	13,10	Mandatory	The geocoordinate(Longitude) of the Delivery Associate’s location. Sample Value - 74.9094089
 * trackingDt	String		Mandatory	This is the timestamp of the tracking Date and Time in UTC and the mentioned Format. Sample Value - 2018-12-11T07:21:39Z
 * currentTime	Long		Mandatory	This is the current timestamp at the time of sending the tracking data to LogiNext. Sample Value - 2018-12-11T07:21:39Z
 * speed	Number		Mandatory	The speed of the Delivery Associate at the time of sending the tracking data.Current Speed in meters / second. This can be received from the Android system classes. More information on this can be found in the Android documentation here
 * battery	Integer	3	Mandatory	This is the pattery percentage on the Delivery Associate’s phone at the time of sending the tracking point. Sample Value - 92. MOre details on this can be found here.
 * accuracy	Number	13,10	Mandatory	Estimated accuracy of the current location in meters Sample Value - 23.878000259
 * altitude	Number	10	Optional	In meters Sample Value - 235
 * bearing	Number	10	Optional	Horizontal distance of travel of the device, in degrees. If the phone has this sensor, then send this value. Sample Value - Any value between 0 to 3600. 0 is North. Consider Clockwise movement.
 * locationSource	String	32	Optional	Location Provider Values like - “fused” , “wifi”, “gps”
 * type	String	40	Mandatory	The tracking type field is used to identify if the tracking is coming from the Delivery Associate’s phone or some other device. This is to be hardcoded to “MOBREG” in case the tracking points will be coming from the phone.
 * isFirstPointFl	Boolean	1	Mandatory	This is used to identify if the current tracking data being sent from the Delivery Associate’s device is the first update after every login.
 * lastLatitude	Double	13,10	Mandatory	Last known Latitude Note that if the isFirstPointFl value is “1”, then you can pass zero in this field Sample Value - 40.760838
 * lastLongitude	Double	13,10	Mandatory	Last known Longitude Note that if the isFirstPointFl value is “1”, then you can pass zero in this field Sample Value - 74.9094089
 * distanceFromLastLocation	Number		Mandatory	Distance between last location update in meters. Note that if the isFirstPointFl value is “1”, then you can pass zero as the distance from last location. Sample Value - 23.5
 * previousTime	Long		Mandatory	Timestamp of last location update in milliseconds Sample Value - 23.878000259
 * hasAccuracy	Boolean	1	Optional	True, if the current location has an accuracy 0 (= False) / 1 (= True)
 * hasBearing	Boolean	1	Optional	True, if the current location has a bearing 0 (= False) / 1 (= True)
 * hasSpeed	Boolean	1	Optional	True, if the current location has a speed 0 (= False) / 1 (= True)
 * networkType	String		Optional	This field is used to identify the network type the Delivery Associate’s phone is connected to when the tracking point is sent. This can be received from the Android core Connectivity Manager APIs here. Sample Value can include WIFI / MOBILE / UNKNOWN
 * signalStrength	Integer		Mandatory	This field is to signify the strength of the mobile network on the Delivery Associate’s phone at the time when the tracking point is sent. (Wifi, GSM, LTE)
 * dataNetworkType	String		Optional	Data Connectivity Type. Sample Values - 1xRTT, EDGE, LTE, CDMA, GPRS, HSPA
 * isGsmFl	Boolean	1	Optional	Current connectivity type. Sample Value - 0 (= False) 1 (= True). This can be received from the Android core Connectivity Manager here.
 * isActiveNetworkMetered	Boolean	1	Optional	Is the currently active data network is metered. A network is classified as metered when the user is sensitive to heavy data usage on that connection due to monetary costs, data limitations or battery/performance issues. Sample Value - 0 (= False) 1 (= True). This can be received from the Android core Connectivity Manager APIs here.
 * appStatus	Integer		Optional	Activity status of the app (Foreground, Background, Service, Gone, Sleep, Visible, Unknown). Sample Values - 100 (~ Foreground) 400 (~ Background) 500 (~ Empty) 125 (~ Foreground_Service) 1000 (~ Gone) 200 (~ Visible). More information on this can be found on the Android Activity Manager documentation here.
 * imei	String	40	Mandatory	IMEI number for device Sample Value - 911380134661315
 * */
function logiNextMileMobileCreateTracking($locationList, $imei) {

    global $requestURL;

    $data = $locationList;

    $requestResult = executeRESTCall("POST", $requestURL."TrackingApp/track/mobile/put", $data, "json", array('Content-Type:application/json', 'WWW-Authenticate:'. getAssociateToken($imei)), $imei);

    return $requestResult;

}

/*
 * This endpoint downloads the EPODs and ESIGNs for given order.
 * The API responds with a 202 Request received response along with a request ID that uniquely identifies each request of the API. A webhook response is triggered once the images are fetched with the URL to the EPOD/ ESign images. This webhook also has the same request ID to confirm which Order images are being sent.
 * Calling the URL in the webhook downloads a compressed zip file with the EPOD and ESigns for the Orders sent in the request.
 * The URL in the webhook has a validity of 1 hour. If you wish to download and save the images in your system, please download these files within one hour of consuming this webhook.
 * Note that this API accepts only 1 order number or order reference ID in one request and does not support batching.
 * NOTE: The dates accepted are in UTC.
 * API Type: Tier 1 API
 *
 * Parameter	DataType	Length	Required	Description
 * orderNo	String	40	Conditional Mandatory	Order Number of the Order for which EPOD/ ESign is required. Mandatory if orderReferenceId is not passed.
 * orderReferenceId	String	32	Conditional Mandatory	Order Number of the Order for which EPOD/ ESign is required Mandatory if orderNo is not passed.
 * */
function logiNextMileMobileCreateEsignEpodUpload() {

    global $requestURL;

    $data = array(
        "orderReferenceId" => "5e7a0f2804f14cd591a4740dfc7abdf1"
    );

    $requestResult = executeRESTCall("GET", $requestURL."ShipmentApp/mile/v2/epod/list", $data);

    var_dump($requestResult);

}

function lnStartTrip($tripIDsList) {

//    if(!is_array($lnOrderReferenceId)) {
//
//        $lnOrderReferenceId = array($lnOrderReferenceId);
//
//    }
//
//    $tripIDsList = array();
//
//    foreach ($lnOrderReferenceId as $key=>$value) {
//
////        $orderGetData = votianGetOrderInfo($value);
//
//        $lnOrderGetResponse = logiNextMileOrderGet($value);
//
//        $tripIDsList[] = $lnOrderGetResponse[1]['data'][0]['tripReferenceId'];
//
//    }

    $lnStartTripResult = logiNextMileTripStart(array($tripIDsList));

    return $lnStartTripResult[1];

//    if($lnStartTripResult[1]['status'] == 200 && $lnStartTripResult[1]['data'] == true) {
//
//        return true;
//
//    }
//
//    return false;

}

function calcSpeed($distanceM, $from, $to) {

    $timeDifSek = intval($to) - intval($from);
    
    return number_format(floatval($distanceM) / $timeDifSek, 2, '.', '');

}

function lnCreateTracking($lnTrackingData) {

    $time = time();

    lnFunctionLogTrack(array(
        "function" => "----------------------------------------TRACKING-CHECK-------------------------------------------",
        "type" => "-----------------------------------------------------------------------------------",
        "data" => "-----------------------------------------------------------------------------------"
    ));

    lnFunctionLogTrack(array(
        "function" => "createTracking - ". $time,
        "type" => "setlocation",
        "data" => $lnTrackingData
    ));

    $imei = "";

    foreach ($lnTrackingData as $imei=>$locationData) {

        $lnLocationArray = array(
            "location" => array()
        );

        $locationArray = array(
            "latitude" => $locationData['latitude'],
            "longitude" => $locationData['longitude'],
            "trackingDt" => gmdate("Y-m-d\TH:i:s\Z", strtotime("-1 Minute")),
            // "trackingDt" => gmdate("Y-m-d\TH:i:s\Z"),
            "currentTime" => strtotime(gmdate("Y-m-d\TH:i:s\Z")),
            "speed" => 0,
            "battery" => 90,
            "hasSpeed" => 0,
            "hasAccuracy" => 1,
            "accuracy" => 5,
            "type" => "MOBREG",
            "isFirstPointFl" => 1,
            "imei" => $imei,
            "signalStrength" => 30,
            "lastLatitude" => 0,
            "lastLongitude" => 0,
        );

        $votianCheckFistTrackResult = votianCheckFistTrack($imei);

        lnFunctionLogTrack(array(
            "function" => "votianCheckFistTrack - ". $time,
            "type" => $imei,
            "data" => $votianCheckFistTrackResult
        ));
//        var_dump($votianCheckFistTrackResult);

        if($votianCheckFistTrackResult) {

            $distance = haversineGreatCircleDistance($locationData['latitude'], $locationData['longitude'], $votianCheckFistTrackResult['lastLatitude'], $votianCheckFistTrackResult['lastLongitude']);

            $locationArray["isFirstPointFl"] = 0;
            $locationArray["lastLatitude"] = $votianCheckFistTrackResult['lastLatitude'];
            $locationArray["lastLongitude"] = $votianCheckFistTrackResult['lastLongitude'];
            $locationArray["distanceFromLastLocation"] = $distance;
            $locationArray["previousTime"] = strtotime($votianCheckFistTrackResult['previousTime']);
            $locationArray["hasSpeed"] = 1;
            $locationArray["speed"] = calcSpeed($distance, strtotime($votianCheckFistTrackResult['previousTime']), strtotime(gmdate("Y-m-d\TH:i:s\Z")));

        }

        $lnLocationArray['location'][] = $locationArray;

        //    var_dump(json_encode($lnLocationArray));
        $lnCreateTrackingResult = logiNextMileMobileCreateTracking($lnLocationArray, $imei);
//    var_dump($lnCreateTrackingResult);

        lnFunctionLogTrack(array(
            "function" => "votianCheckFistTrack - ". $time,
            "type" => $lnLocationArray,
            "data" => $lnCreateTrackingResult
        ));

        if($lnCreateTrackingResult[1]['status'] == 200 && $lnCreateTrackingResult[1]['message'] == "success") {

        lnFunctionLogTrack(array(
            "function" => "-----------------------------------------------------------------------------------",
            "type" => "-----------------------------------------------------------------------------------",
            "data" => "------------------------------------FINISH--------------". $imei ."--------------------------"
        ));


            $lastTrackJson = array(
                "lastLatitude" => $locationData['latitude'],
                "lastLongitude" => $locationData['longitude'],
                "previousTime" => $lnCreateTrackingResult[1]['data']['msg'][0] . "Z"
            );

            votianSaveLastTrack($imei, $lastTrackJson);

        } else {

            return false;

        }

    }

//    var_dump(json_encode($lnLocationArray));
//    $lnCreateTrackingResult = logiNextMileMobileCreateTracking($lnLocationArray, $imei);
//    var_dump($lnCreateTrackingResult);
//
//    if($lnCreateTrackingResult[1]['status'] == 200 && $lnCreateTrackingResult[1]['message'] == "success") {
//
//        $resultCount = 0;
//
//        foreach ($lnTrackingData as $imei=>$locationData) {
//
//            $lastTrackJson = array(
//                "lastLatitude" => $locationData['latitude'],
//                "lastLongitude" => $locationData['longitude'],
//                "previousTime" => $lnCreateTrackingResult[1]['data']['msg'][$resultCount] . "Z"
//            );
//
//            votianSaveLastTrack($imei, $lastTrackJson);
//
//            $resultCount++;
//
//        }
//
//        return true;
//
//    }

    return true;

}

function lnStopTrip($lnOrderReferenceId) {

    if(!is_array($lnOrderReferenceId)) {

        $lnOrderReferenceId = array($lnOrderReferenceId);

    }

    $tripIDsList = array();

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

        $orderGetData = votianGetOrderInfo($value);

        $lnOrderGetResponse = logiNextMileOrderGet($orderGetData);

        $tripIDsList[] = array(
            "tripReferenceId" => $lnOrderGetResponse[1]['data'][0]['tripReferenceId'],
            "notDispatchedOrders" => array(),
            "deliveredOrders" => $lnOrderReferenceId
        );

    }

    lnFunctionLog(array(
        "function" => "lnStopTrip - ". time(),
        "type" => "LNSTOPTRIP",
        "data" => $tripIDsList
    ));

    $lnStartTripResult = logiNextMileTripStop($tripIDsList);

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

        return true;

    }

    return false;

}

function lnUpdateOrderStatus($orderStatusData) {

/*    $array = array(
        "03af782b70d246ebb5d8d183dfe26b26",
        "9aee3047cb264b6a81745f13cb69c870",
        "f62f9f0ec38d4f3893ee9966db7bbad5"
    );

    if(in_array($orderStatusData['orderReferenceId'], $array)) {

        lnFunctionLog(array(
        "function" => "--------------------------------TRUE----------------------TRUE-----------------TRUE------------",
        "type" => $orderStatusData['orderReferenceId'],
        "data" => "-------------------------------TRUE---------------------------TRUE-----------TRUE--------------"
        ));

        return true;

    }*/

    // if($orderStatusData['recipientName'] != "") {

    //     lnFunctionLog(array(
    //         "function" => "--------------------------------recipientName---------------------------------------------------",
    //         "type" => iconv("UTF-8", "Windows-1252", utf8_ansi(utf8_encode($orderStatusData['recipientName']))),
    //         "data" => "--------------------------------------".json_encode(iconv("UTF-8", "Windows-1252", utf8_ansi(utf8_encode($orderStatusData['recipientName']))))."---------------------------------------------"
    //     ));

    // }

    if($orderStatusData['orderReferenceId'] == null) {

        return false;

    }

    $time = time();

    lnFunctionLog(array(
        "function" => "--------------------------------Testr---------------------------------------------------",
        "type" => print_r($orderStatusData, true),
        "data" => "-----------------------------------------------------------------------------------"
    ));

    lnFunctionLog(array(
        "function" => "statusUpdate - ". $time,
        "type" => json_encode($orderStatusData),
        "data" => $orderStatusData
    ));

    $reason = $orderStatusData['reasonCd'];
    $otherReason = "";

    if($reason == null) {

        $reason = $orderStatusData['status'];

    }

    if($orderStatusData['status'] == "NOTDELIVERED") {

        $reason = "Other";
        $otherReason = $reason;


    }

    if(!$orderStatusData['updateTime']) {

        $orderStatusData['updateTime'] = gmdate("Y-m-d\TH:i:s\Z");

    } else {

        $timestamp_UNIX = strtotime($orderStatusData['updateTime']);
        $orderStatusData['updateTime'] = gmdate("Y-m-d\TH:i:s\Z", $timestamp_UNIX);

    }

    $lnOrderCheckInArray = array(
        "orderReferenceIds" => $orderStatusData['orderReferenceId'],
        "checkInTime" => $orderStatusData['updateTime']
    );

    if($orderStatusData['crUsrID'] != "") {

        $lastPositions = votianGetLastTrackStatusUpdate($orderStatusData['crUsrID'], $orderStatusData['updateTime']);

        $lnOrderCheckInArray['checkinLatitude'] = $lastPositions['lat'];
        $lnOrderCheckInArray['checkinLongitude'] = $lastPositions['lon'];
        
    }

    if($orderStatusData['status'] == "PICKEDUP" || $orderStatusData['status'] == "NOTPICKEDUP") {

        $lnOrderCheckInArray["checkInLocation"] = "PICKUP";

    } else if($orderStatusData['status'] == "DELIVERED" || $orderStatusData['status'] == "NOTDELIVERED") {

        $lnOrderCheckInArray["checkInLocation"] = "DELIVER";

    }

    $lnCheckInResult = logiNextMileMobileCheckIn($lnOrderCheckInArray);

    lnFunctionLog(array(
        "function" => "lnCheckInResult - ". $time,
        "type" => $orderStatusData['status'],
        "data" => $lnCheckInResult
    ));

    if(($lnCheckInResult[1]['status'] == 200 && $lnCheckInResult[1]['hasError'] == false) || ($lnCheckInResult[1]['status'] == 409 && $lnCheckInResult[1]['error'][0]['errorList'][0]['key'] == "alreadyCheckedIn")) {

        $data = array(
            "newStatus" => $orderStatusData['status'],
            "orderDetails" => array(
                array(
                    "orderReferenceId" => $orderStatusData['orderReferenceId'],
                    "reasonCd" => $reason,
                    "otherReason" => $otherReason,
                    "latitude" => $orderStatusData['latitude'],
                    "longitude" => $orderStatusData['longitude'],
                    "updateTime" => $orderStatusData['updateTime'],
                )
            )
        );

        if($orderStatusData['recipientName'] != "") {

            // $temp = iconv("UTF-8", "Windows-1252", utf8_encode($orderStatusData['recipientName']));
            $temp = utf8_ansi(utf8_encode($orderStatusData['recipientName']));

            $data['orderDetails'][0]['recipientName'] = $temp;

        }

        lnFunctionLog(array(
            "function" => "lnCheckInResult - ". $time,
            "type" => $orderStatusData['status'],
            "data" => $data
        ));

        $lnUpdateOrderStatusResponse = logiNextMileOrderUpdateStatus($data);

        lnFunctionLog(array(
            "function" => "lnUpdateOrderStatusResponse - ". $time,
            "type" => $orderStatusData['status'],
            "data" => $lnUpdateOrderStatusResponse
        ));

        if($lnUpdateOrderStatusResponse[1]['status'] == 200 && $lnUpdateOrderStatusResponse[1]['hasError'] == false) {

            if($orderStatusData['status'] == "NOTPICKEDUP" || $orderStatusData['status'] == "DELIVERED" || $orderStatusData['status'] == "NOTDELIVERED") {

//                $lnStopTripResult = lnStopTrip($orderStatusData['orderReferenceId']);
//
//                lnFunctionLog(array(
//                    "function" => "lnStopTripResult - ". $time,
//                    "type" => $orderStatusData['status'],
//                    "data" => $lnStopTripResult
//                ));
//
//                if($lnStopTripResult) {

                $imei = votianGetImei($orderStatusData['orderReferenceId']);

                setDummyVehicleStatus($imei);

                lnFunctionLog(array(
                    "function" => "-----------------------------------------------------------------------------------",
                    "type" => "-----------------------------------------------------------------------------------",
                    "data" => "-----------------------------------------------------------------------------------"
                ));

                return true;

//                }
//
//                lnFunctionLog(array(
//                    "function" => "-----------------------------------------------------------------------------------",
//                    "type" => "-----------------------------------------------------------------------------------",
//                    "data" => "-----------------------------------------------------------------------------------"
//                ));
//
//                return false;

            }

            lnFunctionLog(array(
                "function" => "-----------------------------------------------------------------------------------",
                "type" => "-----------------------------------------------------------------------------------",
                "data" => "-----------------------------------------------------------------------------------"
            ));

            return true;

        }

    }

    lnFunctionLog(array(
        "function" => "-----------------------------------------------------------------------------------",
        "type" => "-----------------------------------------------------------------------------------",
        "data" => "-----------------------------------------------------------------------------------"
    ));

    return false;

}

function utf8_ansi($valor='') {

    $utf8_ansi2 = array(
    "\u00c0" =>"À",
    "\u00c1" =>"Á",
    "\u00c2" =>"Â",
    "\u00c3" =>"Ã",
    "\u00c4" =>"Ä",
    "\u00c5" =>"Å",
    "\u00c6" =>"Æ",
    "\u00c7" =>"Ç",
    "\u00c8" =>"È",
    "\u00c9" =>"É",
    "\u00ca" =>"Ê",
    "\u00cb" =>"Ë",
    "\u00cc" =>"Ì",
    "\u00cd" =>"Í",
    "\u00ce" =>"Î",
    "\u00cf" =>"Ï",
    "\u00d1" =>"Ñ",
    "\u00d2" =>"Ò",
    "\u00d3" =>"Ó",
    "\u00d4" =>"Ô",
    "\u00d5" =>"Õ",
    "\u00d6" =>"Ö",
    "\u00d8" =>"Ø",
    "\u00d9" =>"Ù",
    "\u00da" =>"Ú",
    "\u00db" =>"Û",
    "\u00dc" =>"Ü",
    "\u00dd" =>"Ý",
    "\u00df" =>"ß",
    "\u00e0" =>"à",
    "\u00e1" =>"á",
    "\u00e2" =>"â",
    "\u00e3" =>"ã",
    "\u00e4" =>"ä",
    "\u00e5" =>"å",
    "\u00e6" =>"æ",
    "\u00e7" =>"ç",
    "\u00e8" =>"è",
    "\u00e9" =>"é",
    "\u00ea" =>"ê",
    "\u00eb" =>"ë",
    "\u00ec" =>"ì",
    "\u00ed" =>"í",
    "\u00ee" =>"î",
    "\u00ef" =>"ï",
    "\u00f0" =>"ð",
    "\u00f1" =>"ñ",
    "\u00f2" =>"ò",
    "\u00f3" =>"ó",
    "\u00f4" =>"ô",
    "\u00f5" =>"õ",
    "\u00f6" =>"ö",
    "\u00f8" =>"ø",
    "\u00f9" =>"ù",
    "\u00fa" =>"ú",
    "\u00fb" =>"û",
    "\u00fc" =>"ü",
    "\u00fd" =>"ý",
    "\u00ff" =>"ÿ");

    return strtr($valor, $utf8_ansi2);      

}

function lnFunctionLog($data) {

    $myfile = fopen(getAbsoluteSystemPathLN()."/"."lnFunctionLog".date("m-Y").".txt", "a");
    fwrite($myfile, "--------------------------". $data['function'] ."---------". $data['type'] ."------------\n");
    fwrite($myfile, json_encode($data['data'], true));
    fwrite($myfile, $data['data']);
    fwrite($myfile, "\n");
    fwrite($myfile, "\n");
    fclose($myfile);

}

function lnFunctionLogTrack($data) {

    $myfile = fopen(getAbsoluteSystemPathLN()."/"."lnFunctionLogTrack".date("m-Y").".txt", "a");
    fwrite($myfile, "--------------------------". $data['function'] ."---------". $data['type'] ."------------\n");
    fwrite($myfile, json_encode($data['data'], true));
    fwrite($myfile, $data['data']);
    fwrite($myfile, "\n");
    fwrite($myfile, "\n");
    fclose($myfile);

}