<?php
require_once "LN_rest_include.php";
require_once "LN_loginext_include.php";
require_once "LN_votian_include.php";


checkRequest("orderAccepted");


/*
 * - status
 * - orderReferenceId
 * */
function orderAccepted() {

    $postData = json_decode(file_get_contents('php://input'), true);

    $lnStatus = $postData['status'];
    $lnOrderReferenceId = $postData['orderReferenceId'];

    if($lnStatus == "ORDER ACCEPTED" && $lnOrderReferenceId) {

        $orderGetData = array(
            "orderReferenceId" => $lnOrderReferenceId,
            "order_no" => $postData['clientShipmentId'],
            // "end_date" => $postData['deliveryEndDate'],
            // "start_date" => $postData['pickupEndDate'],
        );

        $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew".date("m-Y").".txt", "a");
        fwrite($myfile,"-------".$postData['clientShipmentId']."----------------REClogiNextMileOrderGetFirst-------------------". 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['clientShipmentId']."----------------ANSlogiNextMileOrderGetFirst-------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------");
        fclose($myfile);

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

        $postDataVotian = array(
            "branchName" => $lnOrderGetResponseData['branchName'],
            "orderReferenceId" => $postData['orderReferenceId'],
            "orderNo" => $postData['clientShipmentId'],
            "endTimeWindow" => $postData['deliveryEndDate'],
            "startTimeWindow" => $postData['pickupEndDate'],
            "originAddr" => $lnOrderGetResponseData['origin'],
            "destinationAddr" => $lnOrderGetResponseData['destination'],
            "awbNumber" => $lnOrderGetResponseData['awbNumber'],
            "shipmentNotes" => $lnOrderGetResponseData['deliveryNotes'],
        );

        if($lnOrderGetResponse[1]['status'] == 200 && $lnOrderGetResponse[1]['message'] == "SUCCESS") {

            $votianOrderRequestResponse = syncDataWithVotian($postDataVotian, $lnOrderGetResponse[1]);

            if($votianOrderRequestResponse) {
                
                echo json_encode($successArray);

            } else {

                error("The order could not be synchronized with the votian");

            }


        } else {

            error("No order Details could be found in LN-System");

        }

    } else {

        error("Missing order details");

    }

}