<?php if ( ! defined( 'BASEPATH' ) ) {
    exit( 'No direct script access allowed' );
}

use App\Authorization\Authorization;
use App\Order\Models\OrderReference;
use App\Pagination\GetArgumentsResolver;
use Zebra\Client;
use Zebra\Zpl\Builder;
use Zebra\Zpl\GdDecoder;
use Zebra\Zpl\Image;
use App\Models\OrderList\Search\Search;
use App\Models\OrderList\Search\Properties;
use App\Models\OrderList\ExcelUpload;
use App\Models\OrderList\Search\AdvancedSearch;
use App\Pagination\Pagination;
use App\Traits\AutoRoutingTrait;

/**
 * @property CI_Loader $load
 * @property Common $common
 * @property CI_DB_mysqli_driver $db
 * @property CI_Session session
 */
class Orders extends CI_Controller
{

    use AutoRoutingTrait;

    public const IGNORED_ARGUMENT_KEYS = ['limit', 'page', 'searchsubmit'];
    private const GRAMS_ARRAY = ["G", "Gms", "gms", "grm"];
    private const KILOGRAMS_ARRAY = ["Kg", "kg"];
    private const TONS_ARRAY = ["Tons", "tons"];

    /** @var CodeIgniterAuthorization $codeigniterauthorization */
    public $codeigniterauthorization;

    public function __construct()
    {
        parent::__construct();
        if ($this->session->userdata('user_id') == '') {
            redirect('login');
        }
        if ($this->session->userdata('company_code') == "UKKN") {
            redirect('amzorders');
        }
        $this->load->model(['common', 'Order', 'smtcorder', 'triptemplatemodel', 'completedordersmodel', 'DeliveryDocumentModel', 'Order_details']);
        $this->load->library(['TripCreateFromOrders', 'Openbox_status_execution', 'OpenboxStatusAccept', 'm_pdf', 'etrucknowquote', 'shippeostatusintigration', 'statusintigration', 'email', 'Ratemanagement', 'form_validation', 'CodeIgniterAuthorization', 'carrierweightupdate', 'session', 'altovaordercreation', 'knlogin', 'Standard_status_execution', 'Carriercommonedilib', 'apis/FlipkartEDIServices']);
        $this->load->helper('user_helper');
    }

    public function index( $id = null ) {
        if($this->session->userdata('business_type') == "Carrier")
        {
            redirect('welcome/logout');
        }
        /*if (!checkUrlAccessForUser('ORDERS')) {
            redirect("Forbiddenaccess");
        }*/
        if ($id != "") {
            $this->orderslist($id);
        } else {
            $this->orderslist();
        }
    }

    /**
     * @param null|string $id
     * @throws Exception
     */
    public function orderslist($id = null)
    {
        if($this->session->userdata('business_type') == "Carrier")
        {
            redirect('welcome/logout');
        }
        if ($this->session->userdata('user_role_id') == 5) {
            redirect('knopsorders');
        }
        if (checkAccessConditions('RELATED_2_SG_MY', $this->session->userdata('company_code'))) {
            redirect('smtcorders');
        }
        /*if (!checkUrlAccessForUser('ORDERS')) {
            redirect("Forbiddenaccess");
        }*/
        $getArguments = [];
        $properties = new Properties($this->db);
        $order = $excel_uploaddata = $clexcel_uploaddata = $chexcel_uploaddata = $knlogin_uploaddata = [];

        $ats_parties = [];
        $whr = [];
        $conditions = [];

        $data['page_title'] = $this->lang->line( 'order_list' );
        $data['sub_title']  = $this->lang->line( 'menu_orders' );

        $userid = $this->session->userdata( "user_id" );
        $custid = $this->session->userdata( "cust_id" );
        $country_userids = $this->session->userdata( "country_user_ids" );
        $branch_code = $this->session->userdata('branch_code');
        $company_code = $this->session->userdata( 'company_code' );
        $role_id = $this->session->userdata( 'user_role_id' );
        $subcusts = $this->session->userdata( 'sub_cust' );
        $curtz = $this->session->userdata( "usr_tzone" )['timezone'];

        if (in_array($id, ExcelUpload::IDS_FOR_UPLOAD)) {
            $excel = new ExcelUpload($id);
            $result = $excel->upload($company_code);
            if (isset($result['booking_ids']) && !empty($result['booking_ids'])) {
                $properties->getOrderBookings($result['booking_ids'], $this->Order, $ats_parties);
                $data['ats_parties'] = (!empty($ats_parties)) ? htmlentities(json_encode($ats_parties)) : [];
            }
        } elseif ($id != "") {
            $getArguments['bookingid'] = $properties->getBooking($id, $this->Order, $ats_parties);
            $data['getbookingid'] = $getArguments['bookingid'];
            $data['ats_parties'] = (!empty($ats_parties)) ? htmlentities(json_encode($ats_parties)) : [];
        }

        $list_type = $result['list_types']['list_type'] ?? 0;
        $cllist_type = $result['list_types']['cllist_type'] ?? 0;
        $charge_list_type = $result['list_types']['charge_list_type'] ?? 0;
        $knlogin_list_type = $result['list_types']['knlogin_list_type'] ?? 0;

        if($cllist_type==1){
            $filenamecl = @file_get_contents("assets/ordertemplate/clexceluploaddata.txt");
            $clexcel_uploaddata = json_decode($filenamecl);
            if (!empty($clexcel_uploaddata)) {
                @file_put_contents("assets/ordertemplate/clexceluploaddata.txt", "");
            }
        } elseif ($list_type == 1) {
            if ($company_code == "KNAU") {
                $filenameex = @file_get_contents("assets/ordertemplate/excelauuploaddata.txt");
            } else {
                $filenameex = @file_get_contents("assets/ordertemplate/exceluploaddata.txt");
            }
            $excel_uploaddata = json_decode($filenameex);
            if (!empty($excel_uploaddata)) {
                @file_put_contents("assets/ordertemplate/excelauuploaddata.txt", "");
            }
        } elseif ($charge_list_type == 1) {
            $filenamech = @file_get_contents("assets/ordertemplate/charges_exceluploaddata.txt");
            $chexcel_uploaddata = json_decode($filenamech);
            if (!empty($chexcel_uploaddata)) {
                @file_put_contents("assets/ordertemplate/charges_exceluploaddata.txt", "");
            }
        } elseif ($knlogin_list_type == 1) {
            $filenamech = @file_get_contents("assets/ordertemplate/exceluploaddata.txt");
            $knlogin_uploaddata = json_decode($filenamech);
            if (!empty($knlogin_uploaddata)) {
                @file_put_contents("assets/ordertemplate/exceluploaddata.txt", "");
            }
        }
        
        $getArguments = (new GetArgumentsResolver())->resolve(
            $this->getDefaultFilters(),
            $getArguments,
            self::IGNORED_ARGUMENT_KEYS
        );

        if (isset($getArguments['search_type']) && $getArguments['search_type'] === 'advanced') {
            $search = new AdvancedSearch($this->db, $getArguments);
            $conditions = $search->buildWhereClause($this->input, $role_id, $userid,$company_code);
        } else {
            $search = new Search($this->db, $getArguments);
        }

        $field = $properties->getDateFieldName($getArguments);
        $search->fromDate($field,$whr);
        $search->toDate($field, $whr);

        /*----------pickup date-----------------------------------------*/
        if (isset($getArguments['advpickupfrom_date']) && !empty($getArguments['advpickupfrom_date'])) {
            $post_advpickupfrom_date = $this->db->escape_str($getArguments['advpickupfrom_date']);
            $advpickupfrom_date = date('Y-m-d', strtotime($post_advpickupfrom_date));
            $whr["DATE_FORMAT(o.pickup_datetime,'%Y-%m-%d') >="] = $advpickupfrom_date;
        }
        if (isset($getArguments['advpickupto_date']) && !empty($getArguments['advpickupto_date'])) {
            $post_advpickupto_date = $this->db->escape_str($getArguments['advpickupto_date']);
            $advpickupto_date = date('Y-m-d', strtotime($post_advpickupto_date));
            $whr["DATE_FORMAT(o.pickup_datetime,'%Y-%m-%d') <="] = $advpickupto_date;
        }

        /*----------Delivery date-----------------------------------------*/
        if (isset($getArguments['advdeliveryfrom_date']) && !empty($getArguments['advdeliveryfrom_date'])) {
            $post_advdeliveryfrom_date = $this->db->escape_str($getArguments['advdeliveryfrom_date']);
            $advdeliveryfrom_date = date('Y-m-d', strtotime($post_advdeliveryfrom_date));
            $whr["DATE_FORMAT(o.delivery_datetime,'%Y-%m-%d') >="] = $advdeliveryfrom_date;
        }
        if (isset($getArguments['advdeliveryto_date']) && !empty($getArguments['advdeliveryto_date'])) {
            $post_advdeliveryto_date = $this->db->escape_str($getArguments['advdeliveryto_date']);
            $advdeliveryto_date = date('Y-m-d', strtotime($post_advdeliveryto_date));
            $whr["DATE_FORMAT(o.delivery_datetime,'%Y-%m-%d') <="] = $advdeliveryto_date;
        }

        $whr = array_merge($whr, $conditions);

        $order_status   = isset( $getArguments['status'] ) ? $this->db->escape_str($getArguments['status']) : "";
        $ad_orderstatus = isset( $getArguments['order_status'] ) ? $this->db->escape_str($getArguments['order_status']) : "";

        $status_search  = $order_status;

        if ( $status_search == "" ) {
            $status_search = $ad_orderstatus;
        }

        $searchids = isset($getArguments['bookingid']) ? $this->db->escape_str($getArguments['bookingid']) : [];

        /* container number search  */
        if (empty($searchids) && isset($getArguments['container_no']) && ! empty($getArguments['container_no'])) {
            $searchids = $this->GetContainernum($userid, $country_userids, $branch_code);
        } elseif ( ! empty( $searchids ) && isset( $getArguments['container_no'] ) && ! empty( $getArguments['container_no'] ) ) {
            $container_num_arr = $this->GetContainernum($userid, $country_userids, $branch_code);
            $searchids         = array_intersect( $container_num_arr, $searchids );
        }

        /* advanced search order referance type  */
        if (isset( $getArguments['order_reftype'] ) && $getArguments['order_reftype'] != "") {
            $advancedids = $this->getrefnum($userid, $getArguments);

            if (!empty($advancedids)) {
                $searchids = $advancedids;
            } else {
                $whr['o.id'] = '0';
            }
        }

        if (isset( $getArguments['salog_ref'] ) && $getArguments['salog_ref'] != ""){
            $advancedids = getSalogRefNum($userid, $getArguments, $company_code);
            if (!empty($advancedids)) {
                $searchids = $advancedids;
            } else {
                $whr['o.id'] = '0';
            }
        }

        $wildcard_search = isset($getArguments['wildcard_order_id']) ? $getArguments['wildcard_order_id'] : "";

        if (isset($getArguments['order_id']) && !empty($getArguments['order_id'])) {
            $searchids = [$getArguments['order_id']];
        }

        $orderIdsMap = $properties->getOrderIdsMapping($wildcard_search, $searchids, $company_code, $userid, $country_userids);

        if ( $role_id == "4" && $subcusts && !empty($subcusts)) {
            array_push( $subcusts, $custid );
        }
        if (isset($getArguments['order_references']) && !empty($getArguments['order_references'])) {
            $referenceResults = $this->Order->getOrderIdsByReferenceValues($getArguments['order_references']);
            $searchids = empty($referenceResults) ? [0] : $referenceResults;
        }
        $orderdataQuery = $this->Order->indexQuery($userid, $searchids, $status_search, $custid, $country_userids, $whr, $subcusts, $orderIdsMap);
       
        $this->db->query("SET SESSION group_concat_max_len = 1000000");
       
        $pagination = new Pagination(
            $orderdataQuery,
            isset($_GET['limit']) ? (int)$_GET['limit'] : 10,
            isset($_GET['page']) ? (int)$_GET['page'] : 1,
            $getArguments
        );

        $paginationResponse = $pagination->paginate();

        if ($paginationResponse->hasItems()) {
            $au_i = -1;
        }
       
        foreach ($paginationResponse->items() as $res) {
            
            $au_i ++;
            $trip_no = $res['shipmentid'] == '0' ? "" : $res['shipmentid'];
            $Stoppage  = $res['Stoppage'];
            $created_source = $res['created_source'];

            $order_status = $properties->getStatusName($res);
            $otherstatus = $properties->getOtherStatus($res);
            $referenceData = $properties->getReferences($res);

            $invoiceArray = $properties->getInvoices($res);
            $html = $invoiceArray['html'] ?? "";
            $JFR = $invoiceArray['finaljfr'] ?? "";
            $chkdate      = '2020-07-01 00:00:00';
            $createdon    = isset($res['createdon']) ? $res['createdon'] : '0000-00-00';
            $order_str    = strtotime( $createdon );
            $chk_str      = strtotime( $chkdate );
            $early_pickup = $res['pickup_datetime'];

            $early_delivery = $res['delivery_datetime'];
 
            if($res['company_code'] == "VNKN"){
                $early_delivery = $res['drop_endtime'];
            }

            if ( $order_str > $chk_str ) {
                if ( $early_pickup != "" && $early_pickup != "0000-00-00 00:00:00" ) {
                    $epickup      = getdatetimebytimezone( $curtz, $early_pickup, DFLT_TZ );
                    $early_pickup = $epickup['datetime'];
                }
                if ( $early_delivery != "" && $early_delivery != "0000-00-00 00:00:00" ) {
                    $edelivery      = getdatetimebytimezone( $curtz, $early_delivery, DFLT_TZ );
                    $early_delivery = $edelivery['datetime'];
                }
            }
            $orderUpdatedDate = getdatetimebytimezone($curtz, $res['updatedon'], DFLT_TZ);
            $updatedDate = $orderUpdatedDate['datetime'];
            $delivered_time = $final_delivery  = $res['delivered_time'];

            if($delivered_time != "" && $delivered_time != "0000-00-00 00:00:00" && $delivered_time != "0"){
                $fdelivery      = getdatetimebytimezone( $curtz, $delivered_time, DFLT_TZ );
                $final_delivery = date('Y-m-d h:i A',strtotime($fdelivery['datetime']));
            }

            //Enable vendor name for AUKN,KNAU
            //$vendor_name = $res['customer_name'];
            $carrier_name = $res['shift_id'] > 0 ? $res['vendor_name'] : "";
            $carrier_code = $res['shift_id'] > 0 ? $res['vendor_code'] : "";
            
            $australiaCarrierNameCondition = checkAccessConditions('RELATED_2_AUKN_KNAU', $company_code);
            if ($australiaCarrierNameCondition) {
                $vendor_name = $res['vendor_name'];
                $carrier_name = $res['vendor_name'];
                $carrier_code = $res['vendor_code'];
            }
            $POD = $res['pod'];
            $second_weight = (isset($res['second_weight']) && $res['second_weight'] != "") ? $res['second_weight'] : 0;
            $second_volume = (isset($res['second_volume']) && $res['second_volume'] != "") ? $res['second_volume'] : 0;
            $weight_unit = (isset($res['weight_unit']) && $res['weight_unit'] != "") ? $this->getWeightHigherUnit(
                $res['weight_unit']
            ) : "kg";

            $shiftId = $res['shift_id'] ?? 0;
            $triptId = $res['trip_id'] ?? 0;

            $getTripAccepted = $this->db->query("SELECT count(*) as cnt FROM tb_stop_status WHERE shipment_id = ? AND status_code = ? AND status_id = ? LIMIT 1", [
                $shiftId, '0212', 10
            ])->row();

            $tripAccepted = (int)($getTripAccepted->cnt ?? '0');

            $rlgRefVal = $this->common->gettblrowdata(['order_id' => $res['id'], 'reference_id' => 'RLG'], 'id,reference_id,ref_value', 'tb_order_references', 0, 0);
            $created_source = (count($rlgRefVal) > 0) ? "18" : $created_source;

            $order[] = [
                'can_cancel' => !$tripAccepted,
                'order_row_id' => $res['id'],
                'order_id' => $res['order_id'],
                'trip_id' => $triptId,
                'shift_id' => $shiftId,
                'username' => $res['username'],
                'delivery_note' => $referenceData['delivery_note'],
                'pickup' => $res['pickup'],
                'delivery' => $res['delivery'],
                'trip_no' => $trip_no,
                'order_status' => $order_status,
                'transport_mode' => $res['transport_mode'],
                'createdon' => $createdon,
                'total_packages' => round(floatval($res['totqty'])),
                'weight' => $this->calculateWeight($res['totwg'], $weight_unit),
                'gross_weight' => $res['weight'],
                'gross_weight_uom' => $res['gross_weight_uom'],
                'chargeable_weight' => $res['chargeable_weight'],
                'chargeable_weight_uom' => $res['chargeable_weight_uom'],
                'volume' => $res['totvol'],
                'second_weight' => $second_weight . " " . $res['secondweight_uom'],
                'second_volume' => $second_volume . " " . $res['secondvolume_uom'],
                'company_code' => $res['company_code'],
                'branch_code' => $res['branch_code'],
                'department_code' => $res['department_code'],
                'otherstatus' => $otherstatus,
                'Stoppage' => $Stoppage,
                'delivery_date' => $early_delivery,
                'pickup_date' => $early_pickup,
                'html' => $html,
                'container_no' => $referenceData['container_no'],
                'purchase_order' => $referenceData['purchase_order'],
                'vendor_name' => $vendor_name,
                'vendor_id' => $res['vendor_id'] ?? '',
                'external_customer' => ($created_source == 5) ? $res['external_customer'] : '',
                'manifestno' => $referenceData['manifestno'],
                'num_of_pallets' => $res['num_of_pallets'],
                'tot_scanned_qty' => $res['tot_scanned_qty'],
                'deliverycity' => $res['delivery_city'],
                'final_delivery' => $final_delivery,
                'loadplanconnote' => $referenceData['loadplanconnote'],
                'created_source'=>$created_source,
                'salog_ref' => $referenceData['salog_ref'],
                'pq_ref' => $referenceData['pq_ref'],
                'pos_ref'=>$referenceData['pos_ref'],
                'weight_unit'=>$weight_unit,
                'order_type'=>$res['order_type'],
                'customer_name' => $res['customer_name'],
                'carrier_name' => $carrier_name,
                'carrier_code' => $carrier_code,
                'customer_code' => $res['customer_code'],
                'POD'=>$POD,
                'JFR'=>$JFR,
                'updatedDate'=>$updatedDate
            ];
           
            /* Australia ASN check import all values or not, If any missing value index page row color chnage */
            if ( $company_code == "AUKN" ) {
                $asndata = $this->emptycheckasnorder( $res['id'] );
                if ( ! empty( $asndata ) ) {
                    $order[ $au_i ]['alert_msg'] = $asndata['keys'];
                    $order[ $au_i ]['check_val'] = $asndata['check_val'];
                } else {
                    $order[ $au_i ]['alert_msg'] = 0;
                    $order[ $au_i ]['check_val'] = 0;
                }
            }
        }


        $paginationResponse->updateItems($order);
        $data['list_type'] = $list_type;
        $data['excel_uploaddata'] = $excel_uploaddata;
        $data['bill_type'] = "Svkonekt";
        $data['charge_list_type'] = $charge_list_type;
        $data['chexcel_uploaddata'] = $chexcel_uploaddata;
        $data['cllist_type'] = $cllist_type;
        $data['knlogin_uploaddata'] = $knlogin_uploaddata;
        $data['knlogin_list_type'] = $knlogin_list_type;
        $data['clexcel_uploaddata'] = $clexcel_uploaddata;

        $getbilltype = $this->db->select( "bill_type" )->get_where( "tb_branch_master", array( 'branch_code' => $branch_code, 'company_code' => $company_code ) );

        if ( $getbilltype->num_rows() > 0 ) {
            $data['bill_type'] = $getbilltype->row()->bill_type;
        }

        $data['ref_names_arr'] = $this->Order->getrefnums();

        $data['consolidation_data'] = array();
        $get_consolidation_data = $this->common->gettbldata(
            array('company_code' => $company_code, 'status' => '1'),
            "id,consolidation_id,consolidation_name	",
            "tb_consolidation_rules",
            0,
            0
        );
        if (!empty($get_consolidation_data)) {
            foreach ($get_consolidation_data as $consolidation_data) {
                $consolidation_name = htmlentities($consolidation_data['consolidation_name'], ENT_COMPAT, 'UTF-8');
                $data['consolidation_data'][] = array(
                    'id' => $consolidation_data['id'],
                    'consolidation_id_name' => $consolidation_data['consolidation_id'] . "-" . $consolidation_name
                );
            }
        }

        $data['user_currency'] = $this->session->userdata("usr_tzone")['currency'];
        $res = $this->common->gettbldata(array('status' => '1'), "currency", "tbl_country_master", 0, 0);
        if (!empty($res)) {
            foreach ($res as $result) {
                $data['currencies'][] = $result['currency'];
            }
        }

        $data['pagination'] = $paginationResponse;
        $data['postData'] = $this->input->post(null, true);
        $this->newtemplate->dashboard("orders/order", $data);
    }

    /**
     * @param $weightUnit
     * @return string
     */
    private function getWeightHigherUnit($weightUnit): string
    {
        $weightUnitArray = explode(",", $weightUnit);

        if (array_intersect(self::TONS_ARRAY, $weightUnitArray)) {
            return 'tons';
        } elseif (array_intersect(self::KILOGRAMS_ARRAY, $weightUnitArray)) {
            return 'kg';
        } elseif (array_intersect(self::GRAMS_ARRAY, $weightUnitArray)) {
            return 'g';
        }

        return 'kg';
    }

    /**
     * @param $weight
     * @param string $weightUnit
     * @return float|int
     */
    private function calculateWeight($weight, string $weightUnit)
    {
        if ($weightUnit == 'tons') {
            return $weight / 1000;
        } elseif ($weightUnit == 'g') {
            return $weight * 1000;
        }

        return $weight;
    }

    public function checkpurchaseordervalue()
    {
        $p_order = $this->input->post('purchase_order');
        $customer = isset($_POST['customer_id']) ? $_POST['customer_id'] : "";
        $user_id = $this->session->userdata('user_id');
        $cust_id = 0;
        $permission = checkuserpermissions();
        $company_code = $this->session->userdata('company_code');
        if ($company_code == "PHKN") {
            echo '0';
            return;
        }
        if ($customer != "") {
            if (in_array("orders", $permission)) {
                $getcustomerid = $this->common->gettblrowdata(
                    array('code' => $customer, 'company_code' => $company_code, 'status' => '1'),
                    "id",
                    "tb_customers",
                    0,
                    0
                );
                if (!empty($getcustomerid)) {
                    $cust_id = $getcustomerid['id'];
                }
            } else {
                $getcustomerid = $this->common->gettblrowdata(
                    array('code' => $customer, 'user_id' => $user_id, 'status' => '1'),
                    "id",
                    "tb_customers",
                    0,
                    0
                );
                if (!empty($getcustomerid)) {
                    $cust_id = $getcustomerid['id'];
                }
            }

        }
        if ( $cust_id > 0 ) {
            /* $chkorder = $this->db->select('id')->get_where("tb_order_details", array('purchase_order' => $p_order));*/
            if ( $company_code == 'RUKN' ) {
                $chkorder = $this->db->query( "SELECT o.id FROM tb_orders o,tb_order_references r WHERE o.customer_id='" . $cust_id . "' AND o.company_code LIKE '" . $company_code . "' AND o.status !=0 AND o.id=r.order_id AND r.reference_id LIKE 'PO' AND r.ref_value ='" . $p_order . "'" );
            } else {
                $chkorder = $this->db->query( "SELECT o.id FROM tb_orders o,tb_order_references r WHERE o.customer_id='" . $cust_id . "' AND o.user_id LIKE '" . $user_id . "' AND o.status !=0 AND o.id=r.order_id AND r.reference_id LIKE 'PO' AND r.ref_value ='" . $p_order . "'" );
            }
            if ( $chkorder->num_rows() > 0 ) {
                echo '1';
            } else {
                echo '0';
            }
        } else {
            echo '0';
        }


    }

    public function findcountrybyname() {
        $name   = $this->input->post( 'name' );
        $result = array();
        $chkqry = $this->db->select( 'id,company_name,company_code,description' )->get_where( "tb_company_master", array( 'company_code' => $name ) );
        if ( $chkqry->num_rows() > 0 ) {
            foreach ( $chkqry->result() as $res ) {
                $check    = "<input type='radio' name='listcompany' id='listcompany_" . $res->id . "' class='listcompany' onchange='selectcompany(" . $res->id . ")' value='" . $res->company_code . "'>";
                $result[] = array( 'check' => $check, 'company_code' => $res->company_code, 'company_name' => $res->company_name, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function findbranchbyname() {
        $name   = $this->input->post( 'name' );
        $result = array();
        $chkqry = $this->db->select( 'id,branch_name,company_code,description,branch_code' )->get_where( "tb_branch_master", array( 'branch_code' => $name ) );
        if ( $chkqry->num_rows() > 0 ) {
            foreach ( $chkqry->result() as $res ) {
                $check    = "<input type='radio' name='listbranch' id='listbranch_" . $res->id . "' class='listbranch' onchange='selectbranch(" . $res->id . ")' value='" . $res->branch_code . "'>";
                $result[] = array( 'check' => $check, 'branch_code' => $res->branch_code, 'branch_name' => $res->branch_name, 'company_code' => $res->company_code, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function viewcompanylist() {
        
        $result = array();
        $check  = "";
        $popup  = isset( $_POST['popup'] ) ? $_POST['popup'] : "";
        $chkqry = $this->db->select( "id,company_name,company_code,description" )->get_where( "tb_company_master", array( 'status' => 1 ) );
        if ( $chkqry->num_rows() > 0 ) {
            foreach ( $chkqry->result() as $res ) {
                if ( $popup == 'popup' ) {
                    $check = "<input type='radio' name='listpopupcompany' id='listpopupcompany_" . $res->id . "' class='listpopupcompany' onchange='selectpopupcompany(" . $res->id . ")' value='" . $res->company_code . "'>";
                } else {
                    $check = "<input type='radio' name='listcompany' id='listcompany_" . $res->id . "' class='listcompany' onchange='selectcompany(" . $res->id . ")' value='" . $res->company_code . "'>";
                }
                $result[] = array( 'check' => $check, 'id' => $res->id, 'company_code' => $res->company_code, 'company_name' => $res->company_name, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function getcompanyname() {
        $post   = $this->input->post();
        $term   = $post['term'];
        $result = array();
        $check  = "";
        $popup  = isset( $_POST['popup'] ) ? $_POST['popup'] : "";
        $this->db->select( "id,company_code,company_name,description" );
        $this->db->from( "tb_company_master" );
        $this->db->like( 'company_code', $term );
        $this->db->order_by( 'createdon', 'DESC' );
        $getcompanyname = $this->db->get();
        if ( $getcompanyname->num_rows() > 0 ) {
            foreach ( $getcompanyname->result() as $res ) {
                if ( $popup == 'popup' ) {
                    $check = "<input type='radio' name='listpopupcompany' id='listpopupcompany_" . $res->id . "' class='listpopupcompany' onchange='selectpopupcompany(" . $res->id . ")' value='" . $res->company_code . "'>";
                } else {
                    $check = "<input type='radio' name='listcompany' id='listcompany_" . $res->id . "' class='listcompany' onchange='selectcompany(" . $res->id . ")' value='" . $res->company_code . "'>";
                }
                $result[] = array( 'check' => $check, 'company_code' => $res->company_code, 'company_name' => $res->company_name, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function addcompanydetails() {
        $post   = $this->input->post();
        $cdate  = date( 'Y-m-d H:i:s' );
        $ins_ar = array( 'company_name' => $post['company_name'], 'company_code' => $post['company_code'], 'description' => $post['description'], 'status' => 1, 'createdon' => $cdate );
        $chkqry = $this->db->select( 'id' )->get_where( "tb_company_master", array( 'company_name' => $post['company_name'], 'company_code' => $post['company_code'] ) );
        if ( $chkqry->num_rows() > 0 ) {
            echo json_encode( 2 );
        } else {
            $ins = $this->db->insert( 'tb_company_master', $ins_ar );
            if ( $ins ) {
                echo json_encode( 1 );
            } else {
                echo json_encode( 0 );
            }
        }

    }

    public function adddepartmentdetails() {
        $post   = $this->input->post();
        $cdate  = date( 'Y-m-d H:i:s' );
        $ins_ar = array( 'department_name' => $post['department_name'], 'department_code' => $post['department_code'], 'company_code' => $post['company_code'], 'branch_code' => $post['branch_code'], 'description' => $post['description'], 'status' => 1, 'createdon' => $cdate );
        $chkqry = $this->db->select( 'id' )->get_where( "tb_department_master", array( 'department_code' => $post['department_code'], 'department_name' => $post['department_name'], 'company_code' => $post['company_code'], 'branch_code' => $post['branch_code'] ) );
        if ( $chkqry->num_rows() > 0 ) {
            echo json_encode( 2 );
        } else {
            $ins = $this->db->insert( 'tb_department_master', $ins_ar );
            if ( $ins ) {
                echo json_encode( 1 );
            } else {
                echo json_encode( 0 );
            }
        }

    }

    public function getbranchbycompany() {
        $cmp_id = $this->input->post( 'cmp_code' );
        $id     = $this->input->post( 'term' );
        $result = array();
        $this->db->select( 'id,branch_code' );
        $this->db->from( 'tb_branch_master' );
        $this->db->like( 'company_code', $cmp_id );
        $this->db->like( 'branch_code', $id );
        $qry = $this->db->get();
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                $result[] = array( 'id' => $res->id, 'branch_code' => $res->branch_code );
            }
        }
        echo json_encode( $result );
    }

    public function getbranchbyname() {
        $cmp_id = $this->input->post( 'name' );
        $result = array();
        $this->db->select( 'id,branch_code,branch_name,company_code,description' );
        $this->db->from( 'tb_branch_master' );
        $this->db->like( 'branch_code', $cmp_id );
        $qry = $this->db->get();
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                $check    = "<input type='radio' name='listbranch' id='listbranch_" . $res->id . "' class='listbranch' onchange='selectbranch(" . $res->id . ")' value='" . $res->branch_code . "'>";
                $result[] = array( 'check' => $check, 'id' => $res->id, 'branch_code' => $res->branch_code, 'branch_name' => $res->branch_name, 'company_code' => $res->company_code, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function viewbranchlist() {
        $result       = array();
        $company_code = isset( $_POST['company_code'] ) ? $_POST['company_code'] : "";
        $check        = "";
        $popup        = isset( $_POST['popup'] ) ? $_POST['popup'] : "";

        $where = array( 'status' => 1 );
        if ( $company_code != "" ) {
            $where['company_code'] = $company_code;
        }
        $this->db->select( 'id,branch_code,branch_name,company_code,description' );
        $this->db->from( 'tb_branch_master' );
        $this->db->where( $where );
        $qry = $this->db->get();
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                if ( $popup == 'popup' ) {
                    $check = "<input type='radio' name='listpopupbranch' id='listpopupbranch_" . $res->id . "' class='listpopupbranch' onchange='selectpopupbranch(" . $res->id . ")' value='" . $res->branch_code . "'>";
                } else {
                    $check = "<input type='radio' name='listbranch' id='listbranch_" . $res->id . "' class='listbranch' onchange='selectbranch(" . $res->id . ")' value='" . $res->branch_code . "'>";
                }
                $result[] = array( 'check' => $check, 'id' => $res->id, 'branch_code' => $res->branch_code, 'branch_name' => $res->branch_name, 'company_code' => $res->company_code, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function addbranchdetails() {
        $post   = $this->input->post();
        $cdate  = date( 'Y-m-d H:i:s' );
        $ins_ar = array( 'branch_name' => $post['branch_name'], 'branch_code' => $post['branch_code'], 'company_code' => $post['company_code'], 'description' => $post['description'], 'status' => 1, 'createdon' => $cdate );
        $chkqry = $this->db->select( "id" )->get_where( "tb_branch_master", array( 'branch_code' => $post['branch_code'], 'branch_name' => $post['branch_name'] ) );
        if ( $chkqry->num_rows() > 0 ) {
            echo json_encode( 2 );
        } else {
            $ins = $this->db->insert( "tb_branch_master", $ins_ar );
            if ( $ins ) {
                echo json_encode( 1 );
            } else {
                echo json_encode( 0 );
            }
        }

    }

    public function getdepartmentbybranch() {
        $cmp_id = $this->input->post( 'branch_code' );
        $id     = $this->input->post( 'term' );
        $result = array();
        $qry    = $this->db->select( "id,department_code" );
        $this->db->from( "tb_department_master" );
        $this->db->where( array( 'branch_code' => $cmp_id ) );
        $this->db->like( 'department_code', $id );
        $qry = $this->db->get();
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                $result[] = array( 'id' => $res->id, 'department_code' => $res->department_code );
            }
        }
        echo json_encode( $result );
    }

    public function finddepartmentlist() {
        $name   = $this->input->post( 'name' );
        $result = array();
        $qry    = $this->db->select( "id,department_code,department_name,company_code,branch_code,description" )->get_where( "tb_department_master", array( 'department_code' => $name ) );
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                $check    = "<input type='radio' name='listdepartment' id='listdepartment_" . $res->id . "' class='listdepartment' onchange='selectdepartment(" . $res->id . ")' value='" . $res->department_code . "'>";
                $result[] = array( 'check' => $check, 'id' => $res->id, 'department_code' => $res->department_code, 'department_name' => $res->department_name, 'company_code' => $res->company_code, 'branch_code' => $res->branch_code, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function finddepartmentlikelist() {
        $name   = $this->input->post( 'name' );
        $result = array();
        $qry    = $this->db->select( "id,department_code,department_name,company_code,branch_code,description" )->get_where( "tb_department_master", array( 'department_code' => $name ) );
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                $check    = "<input type='radio' name='listdepartment' id='listdepartment_" . $res->id . "' class='listdepartment' onchange='selectdepartment(" . $res->id . ")' value='" . $res->department_code . "'>";
                $result[] = array( 'check' => $check, 'id' => $res->id, 'department_code' => $res->department_code, 'department_name' => $res->department_name, 'company_code' => $res->company_code, 'branch_code' => $res->branch_code, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function viewdepartmentlist() {
        $result       = array();
        $company_code = isset( $_POST['company_code'] ) ? $_POST['company_code'] : "";
        $branch_code  = isset( $_POST['branch_code'] ) ? $_POST['branch_code'] : "";
        $popup        = isset( $_POST['popup'] ) ? $_POST['popup'] : "";
        $whr          = array( 'status' => 1 );
        if ( $company_code != "" ) {
            $whr['company_code'] = $company_code;
        }
        if ( $branch_code != "" ) {
            $whr['branch_code'] = $branch_code;
        }
        $this->db->select( "id,department_code,department_name,company_code,branch_code,description" );
        $this->db->from( "tb_department_master" );
        $this->db->where( $whr );
        $qry = $this->db->get();
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                if ( $popup == 'popup' ) {
                    $check = "<input type='radio' name='listpopupdepartment' id='listpopupdepartment_" . $res->id . "' class='listpopupdepartment' onchange='selectpopupdepartment(" . $res->id . ")' value='" . $res->department_code . "'>";
                } else {
                    $check = "<input type='radio' name='listdepartment' id='listdepartment_" . $res->id . "' class='listdepartment' onchange='selectdepartment(" . $res->id . ")' value='" . $res->department_code . "'>";
                }
                $result[] = array( 'check' => $check, 'id' => $res->id, 'department_code' => $res->department_code, 'department_name' => $res->department_name, 'company_code' => $res->company_code, 'branch_code' => $res->branch_code, 'description' => $res->description );
            }
        }
        echo json_encode( $result );
    }

    public function checkcompanycode() {
        $companys = array();
        $c_code   = isset( $_POST['data'] ) ? $_POST['data'] : "";
        if ( ! empty( $c_code ) ) {
            $this->db->select( 'company_code' );
            $this->db->from( "tb_company_master" );
            $this->db->where_in( 'company_code', $c_code );
            $chk = $this->db->get();
            if ( $chk->num_rows() > 0 ) {
                foreach ( $chk->result() as $res ) {
                    $companys[] = $res->company_code;
                }
            }
        }
        $diff_companys = array();
        if ( ! empty( $companys ) ) {
            $diff_companys = array_diff( $c_code, $companys );

        }
        echo json_encode( $diff_companys );
    }

    public function neworder() {

        if($this->session->userdata('business_type') == "Carrier")
        {
            redirect('welcome/logout');
        }
        if ($this->session->userdata('user_role_id') == 5) {
            redirect('knopsorders');
        }
        if (checkAccessConditions('RELATED_2_SG_MY', $this->session->userdata('company_code'))) {
            redirect('smtcorders');
        }
        /*if (!checkUrlAccessForUser('ORDERS')) {
            redirect("Forbiddenaccess");
        }*/
        $chargecodes = [];
        $data         = $transport = array();
        $user_id      = $this->session->userdata( 'user_id' );
        $company_code = $this->session->userdata( 'company_code' );
        $branch_code  = $this->session->userdata( 'branch_code' );
        
        $data['currencys'] = $this->session->userdata("usr_tzone")['currency'];
        $res = $this->common->gettbldata(array('status' => '1'),"currency","tbl_country_master",0,0);
        if(!empty($res)){
            foreach ($res as $result) {
                $data['currencies'][] = $result['currency'];
            }
        }
        
        $transport = gettransportmode();
        $data['transport']    = $transport;
        $data['company_code'] = $company_code;
        $data['branch_code']  = $branch_code;
        $pickup_details       = array();
        $custid               = $this->session->userdata( 'cust_id' );
        $ordertypes           = array();
        if ( $custid != "" ) {
            $getpickupdetails = $this->Order->getpickupdetails( $custid );
            if ( $getpickupdetails->num_rows() > 0 ) {
                $pickup_details = array( 'id' => $getpickupdetails->row()->id, 'name' => $getpickupdetails->row()->name, 'party_id' => $getpickupdetails->row()->code, 'address' => $getpickupdetails->row()->address, 'pincode' => $getpickupdetails->row()->pincode, 'country' => $getpickupdetails->row()->country );
            }
            $getorders = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_order_types", array( 'customer_id' => $custid, 'company_code' => $company_code, 'status' => '1' ) );
            if ( $getorders->num_rows() > 0 ) {
                foreach ( $getorders->result() as $res ) {
                    $ordertypes[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                }
            } else {
                $getorders = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_order_types", array( 'company_code' => $company_code, "status" => '1' ) );
                if ( $getorders->num_rows() > 0 ) {
                    foreach ( $getorders->result() as $res ) {
                        $ordertypes[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                    }
                } else {
                    $getorders = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_order_types", array( 'company_code' => "SGKN", "status" => '1' ) );
                    if ( $getorders->num_rows() > 0 ) {
                        foreach ( $getorders->result() as $res ) {
                            $ordertypes[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                        }
                    }
                }
            }
        } else {

            $getbranchdetail = $this->db->query("SELECT branch_code FROM tb_order_types WHERE status='1' AND branch_code='" . $branch_code . "' AND company_code='" . $company_code . "'");
            if ($getbranchdetail->num_rows() > 0) {
                $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND ((company_code= '" . $company_code . "' AND (branch_code='" . $branch_code . "' OR (branch_code= '' OR branch_code IS NULL))) OR ((company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL)))");
                if ($getorders->num_rows() > 0) {
                    foreach ($getorders->result() as $res) {
                        $ordertypes[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                    }
                }
            }else{
                $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND (company_code= '" . $company_code . "' OR (company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL))");
                if ($getorders->num_rows() > 0) {
                    foreach ($getorders->result() as $res) {
                        $ordertypes[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                    }
                }
            }

        }
        $roles = array();
        $qyery = $this->db->query( "SELECT id,name FROM tbl_party_types WHERE user_id= '" . $user_id . "' AND status=1 GROUP BY name" );
        if ( $qyery->num_rows() > 0 ) {
            foreach ( $qyery->result() as $res ) {
                $roles[] = array( 'id' => $res->id, 'name' => $res->name );
            }
        }
        $getchargecodes = $this->db->select( "id,charge_code" )->get_where( "tb_charge_codes", array( 'status' => '1' ) );
        if ( $getchargecodes->num_rows() > 0 ) {
            foreach ( $getchargecodes->result() as $res ) {
                $chargecodes[] = array( 'charge_id' => $res->id, 'charge_code' => $res->charge_code );
            }
        }
        $data['vatcategory'] = array();
        $getvatcategory = $this->common->gettbldata(array('company_code'=>$company_code,'status' => '1'),"id,description,vat_category,vat_percentage","tb_vat_category",0,0);
        if (!empty($getvatcategory)) {
            foreach ($getvatcategory as $res) {
                $val = $res['id']."_".$res['vat_category'];
                $desc = $res['description']." (".$res['vat_category']."-".$res['vat_percentage'].")";
                $data['vatcategory'][] = array('id' => $res['id'],'val'=>$val, 'desc'=>$desc);
            }
        }
        
        $arrCostCenter = [];
        if($company_code == 'NZPG' ){
            $getCostCenter = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_cost_center", array( 'company_code' => $company_code, "status" => '1' ) );
            if ( $getCostCenter->num_rows() > 0 ) {
                foreach ( $getCostCenter->result() as $res ) {
                    $arrCostCenter[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                }
            }
        }

        $data['chargecodes']    = $chargecodes;
        $data['pickup_details'] = $pickup_details;
        $data['ordertypes']     = $ordertypes;
        $data['costcenter']     = $arrCostCenter;
        $data['roles']          = $roles;
        $data['marks_numbers_column'] = checkAccessConditions('MARKS_AND_NUMBERS_OPTION', $company_code);       
        $this->load->view('orders/neworder', $data);
    }

    public function getdeliverytermvalue() {
        $incoterm = $this->input->post( 'incoterm' );
        $terms    = array();
        $terms    = getDeliverytermsbyIncoterm( $incoterm );

        echo json_encode( $terms );
    }

    public function copyorder( $id = NULL ) {

        if ($this->session->userdata('user_role_id') == 5) {
            redirect('knopsorders');
        }
        if (checkAccessConditions('RELATED_2_SG_MY', $this->session->userdata('company_code'))) {
            redirect('smtcorders');
        }
        /*if (!checkUrlAccessForUser('ORDERS')) {
            redirect("Forbiddenaccess");
        }*/
        $data = $order_types = [];
        $order_details = $shipper_details = $drop_details = $pickup_details = $delivery_array = $chargecodes = [];
        
        $data['currencys'] = $this->session->userdata("usr_tzone")['currency'];
        $res = $this->common->gettbldata(array('status' => '1'),"currency","tbl_country_master",0,0);
        if(!empty($res)){
            foreach ($res as $result) {
                $data['currencies'][] = $result['currency'];
            }
        }
        
        $order_details['type_name'] = $order_details['ordtype_code'] = "";
        if ( $id != "" ) {
            $chkorder = $this->Order->getordertoedit( $id );
            if ( $chkorder->num_rows() > 0 ) {
                $incoterm    = $chkorder->row()->incoterm;
                $shipment_id = $pickup_inst = $delivery_inst = $container_no = $purchase_order = "";
                $getdnote    = $this->db->query( "SELECT reference_id,ref_value FROM tb_order_references WHERE order_id ='" . $id . "' AND reference_id IN ('DQ','PO','ORD_DLVINST','ORD_PIKINST','CTR')" );
                if ( $getdnote->num_rows() > 0 ) {
                    foreach ( $getdnote->result() as $ref ) {
                        $ref_id = $ref->reference_id;
                        if ( $ref_id == 'DQ' ) {
                            $shipment_id = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_DLVINST' ) {
                            $delivery_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_PIKINST' ) {
                            $pickup_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'CTR' ) {
                            $container_no = $ref->ref_value;
                        }
                        if ( $ref_id == 'PO' ) {
                            $purchase_order = $ref->ref_value;
                        }

                    }
                }
                $pickup_custid          = $chkorder->row()->pickup_custid;
                $status                 = $chkorder->row()->status;
                $trip_id                = $chkorder->row()->trip_id;
                $trip_sts               = $chkorder->row()->trip_sts;
                $docs_received_datetime = $chkorder->row()->docs_received_datetime;
                $docs_sent_datetime     = $chkorder->row()->docs_sent_datetime;
                $order_status           = "PENDING";
                /*if($trip_id != 0 && $trip_sts == 0){
                $order_status = 'ACTIVE';
            }
            if($trip_id != 0 && $trip_sts == 1){
                $order_status = 'CLOSED';
            }*/
                $chkdate      = '2020-07-01 00:00:00';
                $createdon    = $chkorder->row()->createdon;
                $order_str    = strtotime( $createdon );
                $chk_str      = strtotime( $chkdate );
                $early_pickup = $chkorder->row()->pickup_datetime;

                $early_delivery = $chkorder->row()->delivery_datetime;
                $late_pickup    = $chkorder->row()->pickup_endtime;
                $late_delivery  = $chkorder->row()->drop_endtime;
                $curtz          = $this->session->userdata( "usr_tzone" )['timezone'];
                if ( $order_str > $chk_str ) {
                    if ( $early_pickup != "" && $early_pickup != "0000-00-00 00:00:00" ) {
                        $epickup      = getdatetimebytimezone( $curtz, $early_pickup, DFLT_TZ );
                        $early_pickup = $epickup['datetime'];
                    }
                    if ( $early_delivery != "" && $early_delivery != "0000-00-00 00:00:00" ) {
                        $edelivery      = getdatetimebytimezone( $curtz, $early_delivery, DFLT_TZ );
                        $early_delivery = $edelivery['datetime'];
                    }
                    if ( $late_pickup != "" && $late_pickup != "0000-00-00 00:00:00" ) {
                        $lpickup     = getdatetimebytimezone( $curtz, $late_pickup, DFLT_TZ );
                        $late_pickup = $lpickup['datetime'];
                    }
                    if ( $late_delivery != "" && $late_delivery != "0000-00-00 00:00:00" ) {
                        $ldelivery     = getdatetimebytimezone( $curtz, $late_delivery, DFLT_TZ );
                        $late_delivery = $ldelivery['datetime'];
                    }

                }
                if ( $docs_sent_datetime != "" && $docs_sent_datetime != "0000-00-00 00:00:00" ) {
                    $docsent            = getdatetimebytimezone( $curtz, $docs_sent_datetime, DFLT_TZ );
                    $docs_sent_datetime = $docsent['datetime'];
                }
                if ( $docs_received_datetime != "" && $docs_received_datetime != "0000-00-00 00:00:00" ) {
                    $docrec                 = getdatetimebytimezone( $curtz, $docs_received_datetime, DFLT_TZ );
                    $docs_received_datetime = $docrec['datetime'];
                }
                $order_details = [
                    'id' => $chkorder->row()->id,
                    'order_id' => $chkorder->row()->order_id,
                    'shipment_id' => $shipment_id,
                    'early_pickup' => $early_pickup,
                    'early_delivery' => $early_delivery,
                    'late_pickup' => $late_pickup,
                    'late_delivery' => $late_delivery,
                    'product' => $chkorder->row()->product,
                    'service' => $chkorder->row()->service,
                    'delivery_term' => $chkorder->row()->delivery_term,
                    'incoterm' => $chkorder->row()->incoterm,
                    'delivery_note' => $chkorder->row()->delivery_note,
                    'purchase_order' => $purchase_order,
                    'notify_party' => $chkorder->row()->notify_party,
                    'goods_value' => $chkorder->row()->goods_value,
                    'currency' => $chkorder->row()->currency,
                    'lane_reference' => $chkorder->row()->lane_reference,
                    'distance' => $chkorder->row()->distance,
                    'customs_required' => $chkorder->row()->customs_required,
                    'high_cargo_value' => $chkorder->row()->high_cargo_value,
                    'valorance_insurance' => $chkorder->row()->valorance_insurance,
                    'temperature_control' => $chkorder->row()->temperature_control,
                    'company_code' => $chkorder->row()->company_code,
                    'branch_code' => $chkorder->row()->branch_code,
                    'department_code' => $chkorder->row()->department_code,
                    'createdon' => $chkorder->row()->createdon,
                    'order_type' => $chkorder->row()->order_type,
                    'cost_center' => $chkorder->row()->cost_center_id,
                    'transport_mode' => $chkorder->row()->transport_mode,
                    'plat' => $chkorder->row()->plat,
                    'plng' => $chkorder->row()->plng,
                    'dlat' => $chkorder->row()->dlat,
                    'dlng' => $chkorder->row()->dlng,
                    'pickup_inst' => $pickup_inst,
                    'delivery_inst' => $delivery_inst,
                    'container_no' => $container_no,
                    'docs_received_datetime' => $docs_received_datetime,
                    'docs_sent_datetime' => $docs_sent_datetime
                ];
                $order_details['order_status'] = $order_status;
                if ( $incoterm != '' ) {
                    $delivery_array = getDeliverytermsbyIncoterm( $incoterm );
                }
                $pickup_id    = $chkorder->row()->customer_id;
                $company_code = $this->session->userdata( 'company_code' );
                if ( $company_code != "" ) {
                    $company_code = $chkorder->row()->company_code;
                }
                $getorders = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_order_types", array( 'customer_id' => $pickup_id, 'company_code' => $company_code, 'status' => '1' ) );
                if ( $getorders->num_rows() > 0 ) {
                    foreach ( $getorders->result() as $res ) {
                        $order_types[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                    }
                } else {
                    $ordate ='2021-03-19 00:00:00';
                    if($createdon<$ordate){
                        $getorder_types = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types", array('company_code' => $company_code, 'status' => 1));
                        if ($getorder_types->num_rows() > 0) {
                            foreach ($getorder_types->result() as $res) {
                                $order_types[] = array('type_name' => $res->type_name, 'type_id' => $res->id);
                            }
                        }else{
                            $getorders = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types",array('company_code'=>"SGKN","status"=>1));
                            if($getorders->num_rows() >0){
                                foreach($getorders->result() as $res){
                                    $order_types[] = array('type_id'=>$res->id,'type_name'=>$res->type_name);
                                }
                            }
                        }
                    }else{
                        $branch_code = $this->session->userdata('branch_code');
                        $getbranchdetail = $this->db->query("SELECT branch_code FROM tb_order_types WHERE status='1' AND branch_code='" . $branch_code . "' AND company_code='" . $company_code . "'");
                        if ($getbranchdetail->num_rows() > 0) {
                            $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND ((company_code= '" . $company_code . "' AND (branch_code='" . $branch_code . "' OR (branch_code= '' OR branch_code IS NULL))) OR ((company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL)))");
                            if ($getorders->num_rows() > 0) {
                                foreach ($getorders->result() as $res) {
                                    $order_types[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                                }
                            }
                        }else{
                            $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND (company_code= '" . $company_code . "' OR (company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL))");
                            if ($getorders->num_rows() > 0) {
                                foreach ($getorders->result() as $res) {
                                    $order_types[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                                }
                            }
                        }
                    }
                }
                $getpickupdetails = $this->Order->getpickupdetails( $pickup_id );
                if ( $getpickupdetails->num_rows() > 0 ) {
                    $pickup_details = array( 'id' => $getpickupdetails->row()->id, 'name' => $getpickupdetails->row()->name, 'party_id' => $getpickupdetails->row()->code, 'address' => $getpickupdetails->row()->address, 'pincode' => $getpickupdetails->row()->pincode, 'country' => $getpickupdetails->row()->country );
                }
                $drop_id       = $chkorder->row()->drop_custid;
                $drop_row_id   = 0;
                $party_row_ids = array();
                $chekparty     = $this->db->query( "SELECT p.id,p.party_type_id, p.name, p.mobile, p.email,p.code,p.fax,o.party_type FROM tbl_party_master p INNER JOIN tb_order_parties o ON p.id=o.party_id AND o.status=1  WHERE p.status=1 AND o.order_id='$id' GROUP BY o.party_type" );
                if ( $chekparty->num_rows() > 0 ) {
                    foreach ( $chekparty->result() as $rr ) {

                        $ptype   = $rr->party_type;
                        $chktype = $this->db->select( "name" )->get_where( "tbl_party_types", array( "id" => $ptype ), 1, 0 );
                        if ( $chktype->num_rows() > 0 ) {
                            if ($chktype->row()->name == "Consignee") {
                                $drop_details = ['id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code];
                            } elseif ($chktype->row()->name == "Shipper") {
                                $shipper_details = ['id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code];
                            } elseif (!in_array(strtoupper($chktype->row()->name), ["CARRIER", "CUSTOMER"])) {
                                $party_row_ids[] = $rr->id;
                            }
                        }
                    }
                }
                $shipper_details['name']    = $chkorder->row()->pickup;
                $shipper_details['street']  = $chkorder->row()->pickup_address1;
                $shipper_details['state']   = $chkorder->row()->pickup_address2;
                $shipper_details['city']    = $chkorder->row()->pickup_city;
                $shipper_details['country'] = $chkorder->row()->pickup_country;
                $shipper_details['pincode'] = $chkorder->row()->pickup_pincode;

                $drop_details['name']    = $chkorder->row()->delivery;
                $drop_details['street']  = $chkorder->row()->delivery_address1;
                $drop_details['state']   = $chkorder->row()->delivery_address2;
                $drop_details['city']    = $chkorder->row()->delivery_city;
                $drop_details['country'] = $chkorder->row()->delivery_country;
                $drop_details['pincode'] = $chkorder->row()->delivery_pincode;
                $drop_id                 = $chkorder->row()->drop_custid;
            }

            $user_id = $this->session->userdata( 'user_id' );
            $roles   = array();
            $qyery   = $this->db->query( "SELECT id,name FROM tbl_party_types WHERE user_id= '" . $user_id . "' AND status=1 GROUP BY name" );
            if ( $qyery->num_rows() > 0 ) {
                foreach ( $qyery->result() as $res ) {
                    $roles[] = array( 'id' => $res->id, 'name' => $res->name );
                }
            }
            $getchargecodes = $this->db->select( "id,charge_code" )->get_where( "tb_charge_codes", array( 'status' => '1' ) );
            if ( $getchargecodes->num_rows() > 0 ) {
                foreach ( $getchargecodes->result() as $res ) {
                    $chargecodes[] = array( 'charge_id' => $res->id, 'charge_code' => $res->charge_code );
                }
            }
            $cdate         = date( 'Y-m-d H:i:s' );
            $cargo_row_ids = array();
            $qry           = $this->db->query( "SELECT c.*,o.id as orderCargoId FROM tb_cargo_details c,tb_order_cargodetails o WHERE o.order_id ='" . $id . "' AND o.cargo_id=c.id AND o.status=1 GROUP BY c.id ORDER BY c.id DESC" );
            if ( $qry->num_rows() > 0 ) {
                foreach ( $qry->result() as $res ) {
                    $cargo_ins = [
                        'cargo_type' => $res->cargo_type,
                        'goods_description' => $res->goods_description,
                        'quantity' => $res->quantity,
                        'length' => $res->length,
                        'length_unit' => $res->length_unit,
                        'width' => $res->width,
                        'width_unit' => $res->width_unit,
                        'height' => $res->height,
                        'height_unit' => $res->height_unit,
                        'weight' => $res->weight,
                        'weight_unit' => $res->weight_unit,
                        'volume' => $res->volume,
                        'volume_unit' => $res->volume_unit,
                        'stackable' => $res->stackable,
                        'grounded' => $res->grounded,
                        'splittable' => $res->splittable,
                        'createdby' => $user_id,
                        'volumetric_weight' => $res->volumetric_weight,
                        'volweight_uom' => $res->volweight_uom,
                        'createdon' => $cdate,
                        'ldm' => $res->ldm,
                        'second_weight' => $res->second_weight,
                        'secondweight_uom' => $res->secondweight_uom,
                        'second_volume' => $res->second_volume,
                        'secondvolume_uom' => $res->secondvolume_uom,
                        'marks_numbers' => $res->marks_numbers,
                        'dg_goods' => $res->dg_goods,
                    ];
                    $cargo_row_ids[] = $cargoRowId = $this->common->insertTableData("tb_cargo_details", $cargo_ins);
                    if ($res->dg_goods > 0) {
                        $checkDgGoods = $this->common->gettbldata(['order_cargo_id' => $res->orderCargoId, 'status' => '1'], "*", "tb_order_dg_goods", 0, 0);
                        foreach ($checkDgGoods as $eachRow) {
                            $this->common->insertTableData("tb_order_dg_goods", [
                                'order_id' => 0,
                                'order_cargo_id' => $cargoRowId,
                                'num_pkgs' => $eachRow['num_pkgs'],
                                'pkg_qty_type' => $eachRow['pkg_qty_type'],
                                'quantity' => $eachRow['quantity'],
                                'quantity_type' => $eachRow['quantity_type'],
                                'org_number' => $eachRow['org_number'],
                                'org_name' => $eachRow['org_name'],
                                'org_num_varient' => $eachRow['org_num_varient'],
                                'db_class' => $eachRow['db_class'],
                                'mainrisk' => $eachRow['mainrisk'],
                                'description' => $eachRow['description'],
                                'limitqty_flag' => $eachRow['limitqty_flag'],
                                'exceptqty_flag' => $eachRow['exceptqty_flag'],
                                'limited_quantity' => $eachRow['limited_quantity'],
                                'excepted_quantity' => $eachRow['excepted_quantity'],
                                'tunnel_restriction_code' => $eachRow['tunnel_restriction_code'],
                                'transport_category' => $eachRow['transport_category'],
                                'environment_hazardous' => $eachRow['environment_hazardous'],
                                'nos' => $eachRow['nos'],
                                'adr_multiplicator' => $eachRow['adr_multiplicator'],
                                'total_adr_points' => $eachRow['total_adr_points'],
                                'adr_version' => $eachRow['adr_version'],
                                'subsidiary_risks' => $eachRow['subsidiary_risks'],
                                'packing_group' => $eachRow['packing_group'],
                                'gross_weight' => $eachRow['gross_weight'],
                                'net_weight' => $eachRow['net_weight'],
                                'netexplosive_mass' => $eachRow['netexplosive_mass'],
                                'liters' => $eachRow['liters'],
                                'fire_works' => $eachRow['fire_works']
                            ]);
                        }
                    }
                }
            }
        }
        $transport = array();
        $order_date=$createdon;
        $less_date ='2021-03-19 00:00:00';
        $transport = gettransportmode($order_date,$less_date);
        $cargo_id = "";
        if ( ! empty( $cargo_row_ids ) ) {
            $cargo_id = implode( ',', $cargo_row_ids );
        }
        $party_id = "";
        if ( ! empty( $party_row_ids ) ) {
            $party_id = implode( ',', $party_row_ids );
        }
        
        $arrCostCenter = [];
        if($company_code == 'NZPG' ){
            $getCostCenter = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_cost_center", array( 'company_code' => $company_code, "status" => '1' ) );
            if ($getCostCenter->num_rows() > 0 ) {
                foreach ( $getCostCenter->result() as $res ) {
                    $arrCostCenter[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                }
            }
        }

        $order_details['cargo_id'] = $cargo_id;
        $order_details['party_id'] = $party_id;
        $data['transport']         = $transport;
        $data['order_details']     = $order_details;
        $data['pickup_details']    = $pickup_details;
        $data['drop_details']      = $drop_details;
        $data['shipper_details']   = $shipper_details;
        $data['order_types']       = $order_types;
        $data['cost_center']       = $arrCostCenter;
        $data['delivery_array']    = $delivery_array;
        $data['chargecodes']       = $chargecodes;
        $data['roles']             = $roles;
        $data['marks_numbers_column'] = checkAccessConditions('MARKS_AND_NUMBERS_OPTION', $company_code);

        $this->newtemplate->dashboard( 'orders/copyorder', $data );
    }

    public function reverseorder( $id = NULL ) {

        if ($this->session->userdata('user_role_id') == 5) {
            redirect('knopsorders');
        }
        if (checkAccessConditions('RELATED_2_SG_MY', $this->session->userdata('company_code'))) {
            redirect('smtcorders');
        }
        /*if (!checkUrlAccessForUser('ORDERS')) {
            redirect("Forbiddenaccess");
        }*/
        $data = $order_types = [];
        $order_details = $shipper_details = $drop_details = $pickup_details = $delivery_array = $chargecodes = [];

        $order_details['type_name'] = $order_details['ordtype_code'] = "";
        if ( $id != "" ) {
            $chkorder = $this->Order->getordertoedit( $id );
            if ( $chkorder->num_rows() > 0 ) {
                $incoterm    = $chkorder->row()->incoterm;
                $shipment_id = $pickup_inst = $delivery_inst = $container_no = $purchase_order = "";
                $getdnote    = $this->db->query( "SELECT reference_id,ref_value FROM tb_order_references WHERE order_id ='" . $id . "' AND reference_id IN ('DQ','PO','ORD_DLVINST','ORD_PIKINST','CTR')" );
                if ( $getdnote->num_rows() > 0 ) {
                    foreach ( $getdnote->result() as $ref ) {
                        $ref_id = $ref->reference_id;
                        if ( $ref_id == 'DQ' ) {
                            $shipment_id = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_DLVINST' ) {
                            $delivery_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_PIKINST' ) {
                            $pickup_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'CTR' ) {
                            $container_no = $ref->ref_value;
                        }
                        if ( $ref_id == 'PO' ) {
                            $purchase_order = $ref->ref_value;
                        }

                    }
                }
                $pickup_custid = $chkorder->row()->pickup_custid;
                $status        = $chkorder->row()->status;
                $trip_id       = $chkorder->row()->trip_id;
                $trip_sts      = $chkorder->row()->trip_sts;
                $order_status  = "PENDING";
                $chkdate                = '2020-07-01 00:00:00';
                $createdon              = $chkorder->row()->createdon;
                $order_str              = strtotime( $createdon );
                $chk_str                = strtotime( $chkdate );
                $early_pickup           = $chkorder->row()->pickup_datetime;
                $docs_received_datetime = $chkorder->row()->docs_received_datetime;
                $docs_sent_datetime     = $chkorder->row()->docs_sent_datetime;
                $early_delivery         = $chkorder->row()->delivery_datetime;
                $late_pickup            = $chkorder->row()->pickup_endtime;
                $late_delivery          = $chkorder->row()->drop_endtime;
                $curtz                  = $this->session->userdata( "usr_tzone" )['timezone'];
                if ( $order_str > $chk_str ) {
                    if ( $early_pickup != "" && $early_pickup != "0000-00-00 00:00:00" ) {
                        $epickup      = getdatetimebytimezone( $curtz, $early_pickup, DFLT_TZ );
                        $early_pickup = $epickup['datetime'];
                    }
                    if ( $early_delivery != "" && $early_delivery != "0000-00-00 00:00:00" ) {
                        $edelivery      = getdatetimebytimezone( $curtz, $early_delivery, DFLT_TZ );
                        $early_delivery = $edelivery['datetime'];
                    }
                    if ( $late_pickup != "" && $late_pickup != "0000-00-00 00:00:00" ) {
                        $lpickup     = getdatetimebytimezone( $curtz, $late_pickup, DFLT_TZ );
                        $late_pickup = $lpickup['datetime'];
                    }
                    if ( $late_delivery != "" && $late_delivery !== "0000-00-00 00:00:00" ) {
                        $ldelivery     = getdatetimebytimezone( $curtz, $late_delivery, DFLT_TZ );
                        $late_delivery = $ldelivery['datetime'];
                    }

                }
                if ( $docs_sent_datetime != "" && $docs_sent_datetime != "0000-00-00 00:00:00" ) {
                    $docsent            = getdatetimebytimezone( $curtz, $docs_sent_datetime, DFLT_TZ );
                    $docs_sent_datetime = $docsent['datetime'];
                }
                if ( $docs_received_datetime != "" && $docs_received_datetime != "0000-00-00 00:00:00" ) {
                    $docrec                 = getdatetimebytimezone( $curtz, $docs_received_datetime, DFLT_TZ );
                    $docs_received_datetime = $docrec['datetime'];
                }
                $order_details                 = array(
                    'id'                     => $chkorder->row()->id,
                    'order_id'               => $chkorder->row()->order_id,
                    'shipment_id'            => $shipment_id,
                    'early_pickup'           => $early_pickup,
                    'early_delivery'         => $early_delivery,
                    'late_pickup'            => $late_pickup,
                    'late_delivery'          => $late_delivery,
                    'product'                => $chkorder->row()->product,
                    'service'                => $chkorder->row()->service,
                    'delivery_term'          => $chkorder->row()->delivery_term,
                    'incoterm'               => $chkorder->row()->incoterm,
                    'delivery_note'          => $chkorder->row()->delivery_note,
                    'purchase_order'         => $purchase_order,
                    'notify_party'           => $chkorder->row()->notify_party,
                    'goods_value'            => $chkorder->row()->goods_value,
                    'currency'           	 => $chkorder->row()->currency,
                    'lane_reference'         => $chkorder->row()->lane_reference,
                    'distance'               => $chkorder->row()->distance,
                    'customs_required'       => $chkorder->row()->customs_required,
                    'high_cargo_value'       => $chkorder->row()->high_cargo_value,
                    'valorance_insurance'    => $chkorder->row()->valorance_insurance,
                    'temperature_control'    => $chkorder->row()->temperature_control,
                    'company_code'           => $chkorder->row()->company_code,
                    'branch_code'            => $chkorder->row()->branch_code,
                    'department_code'        => $chkorder->row()->department_code,
                    'createdon'              => $chkorder->row()->createdon,
                    'order_type'             => $chkorder->row()->order_type,
                    'cost_center'             => $chkorder->row()->cost_center_id,
                    'transport_mode'         => $chkorder->row()->transport_mode,
                    'pickup_inst'            => $pickup_inst,
                    'delivery_inst'          => $delivery_inst,
                    'container_no'           => $container_no,
                    'docs_received_datetime' => $docs_received_datetime,
                    'docs_sent_datetime'     => $docs_sent_datetime
                );
                $order_details['order_status'] = $order_status;
                if ( $incoterm != '' ) {
                    $delivery_array = getDeliverytermsbyIncoterm( $incoterm );
                }
                $pickup_id    = $chkorder->row()->customer_id;
                $company_code = $this->session->userdata( 'company_code' );
                if ( $company_code != "" ) {
                    $company_code = $chkorder->row()->company_code;
                }
                $ordate ='2021-03-19 00:00:00';
                if($createdon<$ordate){
                    $getorder_types = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types", array('company_code' => $company_code, 'status' => 1));
                    if ($getorder_types->num_rows() > 0) {
                        foreach ($getorder_types->result() as $res) {
                            $order_types[] = array('type_name' => $res->type_name, 'type_id' => $res->id);
                        }
                    }else{
                        $getorders = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types",array('company_code'=>"SGKN","status"=>1));
                        if($getorders->num_rows() >0){
                            foreach($getorders->result() as $res){
                                $order_types[] = array('type_id'=>$res->id,'type_name'=>$res->type_name);
                            }
                        }
                    }
                }else{
                    $branch_code = $this->session->userdata('branch_code');
                    $getbranchdetail = $this->db->query("SELECT branch_code FROM tb_order_types WHERE status='1' AND branch_code='" . $branch_code . "' AND company_code='" . $company_code . "'");
                    if ($getbranchdetail->num_rows() > 0) {
                        $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND ((company_code= '" . $company_code . "' AND (branch_code='" . $branch_code . "' OR (branch_code= '' OR branch_code IS NULL))) OR ((company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL)))");
                        if ($getorders->num_rows() > 0) {
                            foreach ($getorders->result() as $res) {
                                $order_types[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                            }
                        }
                    }else{
                        $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND (company_code= '" . $company_code . "' OR (company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL))");
                        if ($getorders->num_rows() > 0) {
                            foreach ($getorders->result() as $res) {
                                $order_types[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                            }
                        }
                    }
                }
                $getpickupdetails = $this->Order->getpickupdetails( $pickup_id );
                if ( $getpickupdetails->num_rows() > 0 ) {
                    $pickup_details = array( 'id' => $getpickupdetails->row()->id, 'name' => $getpickupdetails->row()->name, 'party_id' => $getpickupdetails->row()->code, 'address' => $getpickupdetails->row()->address, 'pincode' => $getpickupdetails->row()->pincode, 'country' => $getpickupdetails->row()->country );
                }
                $drop_id       = $chkorder->row()->drop_custid;
                $drop_row_id   = 0;
                $party_row_ids = array();
                $chekparty     = $this->db->query( "SELECT p.id,p.party_type_id, p.name, p.mobile, p.email,p.code,p.fax,o.party_type FROM tbl_party_master p INNER JOIN tb_order_parties o ON p.id=o.party_id AND o.status=1  WHERE p.status=1 AND o.order_id='$id' GROUP BY o.party_type" );
                if ( $chekparty->num_rows() > 0 ) {
                    foreach ( $chekparty->result() as $rr ) {

                        $ptype   = $rr->party_type;
                        $chktype = $this->db->select( "name" )->get_where( "tbl_party_types", array( "id" => $ptype ), 1, 0 );
                        if ( $chktype->num_rows() > 0 ) {
                            if ($chktype->row()->name == "Consignee") {
                                $shipper_details = ['id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code];
                            } elseif ($chktype->row()->name == "Shipper") {
                                $drop_details = ['id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code];
                            } elseif (!in_array(strtoupper($chktype->row()->name), ["CARRIER", "CUSTOMER"])) {
                                $party_row_ids[] = $rr->id;
                            }
                        }
                    }
                }
                $drop_details['name']    = $chkorder->row()->pickup;
                $drop_details['street']  = $chkorder->row()->pickup_address1;
                $drop_details['state']   = $chkorder->row()->pickup_address2;
                $drop_details['city']    = $chkorder->row()->pickup_city;
                $drop_details['country'] = $chkorder->row()->pickup_country;
                $drop_details['pincode'] = $chkorder->row()->pickup_pincode;

                $shipper_details['name']    = $chkorder->row()->delivery;
                $shipper_details['street']  = $chkorder->row()->delivery_address1;
                $shipper_details['state']   = $chkorder->row()->delivery_address2;
                $shipper_details['city']    = $chkorder->row()->delivery_city;
                $shipper_details['country'] = $chkorder->row()->delivery_country;
                $shipper_details['pincode'] = $chkorder->row()->delivery_pincode;
                $drop_id                    = $chkorder->row()->drop_custid;
            }

            $user_id = $this->session->userdata( 'user_id' );
            $roles   = array();
            $qyery   = $this->db->query( "SELECT id,name FROM tbl_party_types WHERE user_id= '" . $user_id . "' AND status=1 GROUP BY name" );
            if ( $qyery->num_rows() > 0 ) {
                foreach ( $qyery->result() as $res ) {
                    $roles[] = array( 'id' => $res->id, 'name' => $res->name );
                }
            }
            $getchargecodes = $this->db->select( "id,charge_code" )->get_where( "tb_charge_codes", array( 'status' => '1' ) );
            if ( $getchargecodes->num_rows() > 0 ) {
                foreach ( $getchargecodes->result() as $res ) {
                    $chargecodes[] = array( 'charge_id' => $res->id, 'charge_code' => $res->charge_code );
                }
            }
            $cdate         = date( 'Y-m-d H:i:s' );
            $cargo_row_ids = array();
            $qry           = $this->db->query( "SELECT c.* FROM tb_cargo_details c,tb_order_cargodetails o WHERE o.order_id ='" . $id . "' AND o.cargo_id=c.id AND o.status=1 GROUP BY c.id ORDER BY c.id DESC" );
            if ( $qry->num_rows() > 0 ) {
                foreach ( $qry->result() as $res ) {

                    $cargo_ins       = array(
                        'cargo_type'        => $res->cargo_type,
                        'goods_description' => $res->goods_description,
                        'quantity'          => $res->quantity,
                        'length'            => $res->length,
                        'length_unit'       => $res->length_unit,
                        'width'             => $res->width,
                        'width_unit'        => $res->width_unit,
                        'height'            => $res->height,
                        'height_unit'       => $res->height_unit,
                        'weight'            => $res->weight,
                        'weight_unit'       => $res->weight_unit,
                        'volume'            => $res->volume,
                        'volume_unit'       => $res->volume_unit,
                        'stackable'         => $res->stackable,
                        'grounded'          => $res->grounded,
                        'splittable'        => $res->splittable,
                        'volumetric_weight' => $res->volumetric_weight,
                        'volweight_uom'     => $res->volweight_uom,
                        'createdby'         => $user_id,
                        'createdon'         => $cdate,
                        'ldm'               => $res->ldm
                    );
                    $ins_cargo       = $this->db->insert( "tb_cargo_details", $cargo_ins );
                    $cargo_row_ids[] = $this->db->insert_id();
                    /*   array_push($ids,$cargo_row_id);*/
                }
            }

        }
        
        $transport = array();
        $order_date=$createdon;
        $less_date ='2021-03-19 00:00:00';
        $transport = gettransportmode($order_date,$less_date);
        $cargo_id = "";
        if ( ! empty( $cargo_row_ids ) ) {
            $cargo_id = implode( ',', $cargo_row_ids );
        }
        $party_id = "";
        if ( ! empty( $party_row_ids ) ) {
            $party_id = implode( ',', $party_row_ids );
        }
        /* cost center*/
        $arrCostCenter=[];
        if($company_code == 'NZPG'){
            $getCostCost = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_cost_center", array('company_code' => $company_code, 'status' => 1));
            if ($getCostCost->num_rows() > 0) {
                foreach ($getCostCost->result() as $res) {
                    $arrCostCenter[] = array('type_name' => $res->type_name, 'type_id' => $res->id);
                }
            }
        }
        $order_details['cargo_id'] = $cargo_id;
        $order_details['party_id'] = $party_id;
        $data['transport']         = $transport;
        $data['order_details']     = $order_details;
        $data['pickup_details']    = $pickup_details;
        $data['drop_details']      = $drop_details;
        $data['shipper_details']   = $shipper_details;
        $data['order_types']       = $order_types;
        $data['cost_center']       = $arrCostCenter;
        $data['delivery_array']    = $delivery_array;
        $data['chargecodes']       = $chargecodes;
        $data['roles']             = $roles;
        $data['marks_numbers_column'] = checkAccessConditions('MARKS_AND_NUMBERS_OPTION', $company_code);
        $this->newtemplate->dashboard( 'orders/copyorder', $data );
    }


    public function editorder( $id = NULL ) {

        if($this->session->userdata('business_type') == "Carrier")
        {
            redirect('welcome/logout');
        }
        if ($this->session->userdata('user_role_id') == 5) {
            redirect('knopsorders');
        }
        if (checkAccessConditions('RELATED_2_SG_MY', $this->session->userdata('company_code'))) {
            redirect('smtcorders');
        }
        /*if (!checkUrlAccessForUser('ORDERS')) {
            redirect("Forbiddenaccess");
        }*/
        $data = $order_types = [];
        $order_details = $shipper_details = $drop_details = $pickup_details = $delivery_array = $chargecodes = [];
        
        $data['currencys'] = $this->session->userdata("usr_tzone")['currency'];
        $res = $this->common->gettbldata(array('status' => '1'),"currency","tbl_country_master",0,0);
        if(!empty($res)){
            foreach ($res as $result) {
                $data['currencies'][] = $result['currency'];
            }
        }
        
        $cargores = $this->common->gettbldata(array('status' => '1','order_id'=>$id),"cargo_id","tb_order_cargodetails",1,0);
        if(!empty($cargores)){
            $data['order_cargo_id'] = $cargores[0]['cargo_id'];
        }else{
            $data['order_cargo_id'] = '';
        }

        $order_details['type_name'] = $order_details['ordtype_code'] = "";
        if ( $id != "" ) {
            $chkorder = $this->Order->getordertoedit( $id );
            if ( $chkorder->num_rows() > 0 ) {
                $incoterm    = $chkorder->row()->incoterm;
                $shipment_id = $pickup_inst = $delivery_inst = $container_no = $purchase_order = $multiple_marks_numbers = "";
                $getdnote    = $this->db->query( "SELECT reference_id,ref_value FROM tb_order_references WHERE order_id ='" . $id . "' AND reference_id IN ('DQ','PO','ORD_DLVINST','ORD_PIKINST','CTR','MARKS_NUMBERS')" );
                if ( $getdnote->num_rows() > 0 ) {
                    foreach ( $getdnote->result() as $ref ) {
                        $ref_id = $ref->reference_id;
                        if ( $ref_id == 'DQ' ) {
                            $shipment_id = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_DLVINST' ) {
                            $delivery_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_PIKINST' ) {
                            $pickup_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'CTR' ) {
                            $container_no = $ref->ref_value;
                        }
                        if ( $ref_id == 'PO' ) {
                            $purchase_order = $ref->ref_value;
                        }
                        if ( $ref_id == 'MARKS_NUMBERS' ) {
                            $multiple_marks_numbers = $ref->ref_value;
                        }
                    }
                }
                $pickup_custid = $chkorder->row()->pickup_custid;
                $status        = $chkorder->row()->status;
                $trip_id       = $chkorder->row()->trip_id;
                $trip_sts      = $chkorder->row()->trip_sts;
                if ($status == 3) {
                    redirect("Forbiddenaccess");
                }
                $order_status  = "PENDING";
                if ( $trip_id != 0 && $trip_sts == 0 ) {
                    $order_status = 'ACTIVE';
                }
                if ( $trip_id != 0 && $trip_sts == 1 ) {
                    $order_status = 'CLOSED';
                }
                $chkdate      = '2020-07-01 00:00:00';
                $createdon    = $chkorder->row()->createdon;
                $order_str    = strtotime( $createdon );
                $chk_str      = strtotime( $chkdate );
                $early_pickup = $chkorder->row()->pickup_datetime;

                $early_delivery         = $chkorder->row()->delivery_datetime;
                $late_pickup            = $chkorder->row()->pickup_endtime;
                $late_delivery          = $chkorder->row()->drop_endtime;
                $docs_received_datetime = $chkorder->row()->docs_received_datetime;
                $docs_sent_datetime     = $chkorder->row()->docs_sent_datetime;
                $curtz                  = $this->session->userdata( "usr_tzone" )['timezone'];
                if ( $order_str > $chk_str ) {
                    if ( $early_pickup != "" && $early_pickup != "0000-00-00 00:00:00" ) {
                        $epickup      = getdatetimebytimezone( $curtz, $early_pickup, DFLT_TZ );
                        $early_pickup = $epickup['datetime'];
                    }
                    if ( $early_delivery != "" && $early_delivery != "0000-00-00 00:00:00" ) {
                        $edelivery      = getdatetimebytimezone( $curtz, $early_delivery, DFLT_TZ );
                        $early_delivery = $edelivery['datetime'];
                    }
                    if ( $late_pickup != "" && $late_pickup != "0000-00-00 00:00:00" ) {
                        $lpickup     = getdatetimebytimezone( $curtz, $late_pickup, DFLT_TZ );
                        $late_pickup = $lpickup['datetime'];
                    }
                    if ( $late_delivery != "" && $late_delivery != "0000-00-00 00:00:00" ) {
                        $ldelivery     = getdatetimebytimezone( $curtz, $late_delivery, DFLT_TZ );
                        $late_delivery = $ldelivery['datetime'];
                    }

                }
                if ( $docs_sent_datetime != "" && $docs_sent_datetime != "0000-00-00 00:00:00" ) {
                    $docsent            = getdatetimebytimezone( $curtz, $docs_sent_datetime, DFLT_TZ );
                    $docs_sent_datetime = $docsent['datetime'];
                }
                if ( $docs_received_datetime != "" && $docs_received_datetime != "0000-00-00 00:00:00" ) {
                    $docrec                 = getdatetimebytimezone( $curtz, $docs_received_datetime, DFLT_TZ );
                    $docs_received_datetime = $docrec['datetime'];
                }

                $order_details                 = array(
                    'id'                     => $chkorder->row()->id,
                    'order_id'               => $chkorder->row()->order_id,
                    'shipment_id'            => $shipment_id,
                    'early_pickup'           => $early_pickup,
                    'early_delivery'         => $early_delivery,
                    'late_pickup'            => $late_pickup,
                    'late_delivery'          => $late_delivery,
                    'product'                => $chkorder->row()->product,
                    'service'                => $chkorder->row()->service,
                    'delivery_term'          => $chkorder->row()->delivery_term,
                    'incoterm'               => $chkorder->row()->incoterm,
                    'delivery_note'          => $chkorder->row()->delivery_note,
                    'purchase_order'         => $purchase_order,
                    'multiple_marks_numbers' => $multiple_marks_numbers,
                    'notify_party'           => $chkorder->row()->notify_party,
                    'goods_value'            => $chkorder->row()->goods_value,
                    'currency'	             => $chkorder->row()->currency,
                    'lane_reference'         => $chkorder->row()->lane_reference,
                    'distance'               => $chkorder->row()->distance,
                    'customs_required'       => $chkorder->row()->customs_required,
                    'high_cargo_value'       => $chkorder->row()->high_cargo_value,
                    'valorance_insurance'    => $chkorder->row()->valorance_insurance,
                    'temperature_control'    => $chkorder->row()->temperature_control,
                    'company_code'           => $chkorder->row()->company_code,
                    'branch_code'            => $chkorder->row()->branch_code,
                    'department_code'        => $chkorder->row()->department_code,
                    'createdon'              => $chkorder->row()->createdon,
                    'order_type'             => $chkorder->row()->order_type,
                    'cost_center'            => $chkorder->row()->cost_center_id,
                    'transport_mode'         => $chkorder->row()->transport_mode,
                    'pickup_inst'            => $pickup_inst,
                    'delivery_inst'          => $delivery_inst,
                    'container_no'           => $container_no,
                    'docs_received_datetime' => $docs_received_datetime,
                    'docs_sent_datetime'     => $docs_sent_datetime,
                    'external_order_id'      => $chkorder->row()->external_order_id ?? ''
                );
                $order_details['order_status'] = $order_status;
                if ( $incoterm != '' ) {
                    $delivery_array = getDeliverytermsbyIncoterm( $incoterm );
                }
                $pickup_id            = $chkorder->row()->customer_id;
                $vendor_id            = $chkorder->row()->vendor_id;
                $user_id              = $this->session->userdata( 'user_id' );
                $pickup_location      = array( 'country' => $chkorder->row()->pickup_country, 'zipcode' => $chkorder->row()->pickup_pincode, 'user_id' => $user_id, 'city' => $chkorder->row()->pickup_city );
                $delivery_location    = array( 'country' => $chkorder->row()->delivery_country, 'zipcode' => $chkorder->row()->delivery_pincode, 'user_id' => $user_id, 'city' => $chkorder->row()->delivery_city );
                $info                 = array( 'order_id' => $id, 'product' => $chkorder->row()->product );
                $data['rates']        = $this->ratemanagement->getcustomerprofiledetailsbyid( $pickup_id, $chkorder->row()->service, $pickup_location, $delivery_location, $info );
                $data['vendor_rates'] = $this->ratemanagement->getvendorprofiledetailsbyid( $vendor_id, $chkorder->row()->service, $info );
                $company_code         = $this->session->userdata( 'company_code' );
                if ( $company_code == "" ) {
                    $company_code = $chkorder->row()->company_code;
                }
                $cust_id = $this->session->userdata('cust_id');
                if ($cust_id == '') {
                    $getorders = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types", ['company_code' => $company_code, 'status' => '1']);
                } else {
                    $getorders = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types", ['customer_id' => $pickup_id, 'company_code' => $company_code, 'status' => '1']);
                }
                if ( $getorders->num_rows() > 0 ) {
                    foreach ( $getorders->result() as $res ) {
                        $order_types[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                    }
                }
                
                else {
                    $ordate ='2021-03-19 00:00:00';
                    if($createdon<$ordate){
                        $getorder_types = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types", array('company_code' => $company_code, 'status' => 1));
                        if ($getorder_types->num_rows() > 0) {
                            foreach ($getorder_types->result() as $res) {
                                $order_types[] = array('type_name' => $res->type_name, 'type_id' => $res->id);
                            }
                        }else{
                            $getorders = $this->db->select("id,type_name")->group_by("type_name")->get_where("tb_order_types",array('company_code'=>"SGKN","status"=>1));
                            if($getorders->num_rows() >0){
                                foreach($getorders->result() as $res){
                                    $order_types[] = array('type_id'=>$res->id,'type_name'=>$res->type_name);
                                }
                            }
                        }
                    }else{
                        $branch_code = $this->session->userdata('branch_code');
                        $getbranchdetail = $this->db->query("SELECT branch_code FROM tb_order_types WHERE status='1' AND branch_code='" . $branch_code . "' AND company_code='" . $company_code . "'");
                        if ($getbranchdetail->num_rows() > 0) {
                            $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND ((company_code= '" . $company_code . "' AND (branch_code='" . $branch_code . "' OR (branch_code= '' OR branch_code IS NULL))) OR ((company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL)))");
                            if ($getorders->num_rows() > 0) {
                                foreach ($getorders->result() as $res) {
                                    $order_types[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                                }
                            }
                        }else{
                            $getorders = $this->db->query("SELECT id,type_name FROM tb_order_types WHERE status ='1' AND (company_code= '" . $company_code . "' OR (company_code= '' OR company_code IS NULL) AND (branch_code= '' OR branch_code IS NULL))");
                            if ($getorders->num_rows() > 0) {
                                foreach ($getorders->result() as $res) {
                                    $order_types[] = array('type_id' => $res->id, 'type_name' => $res->type_name);
                                }
                            }
                        }
                    }

                }

                $getpickupdetails = $this->Order->getpickupdetails( $pickup_id );
                if ( $getpickupdetails->num_rows() > 0 ) {
                    $pickup_details = array( 'id' => $getpickupdetails->row()->id, 'name' => $getpickupdetails->row()->name, 'party_id' => $getpickupdetails->row()->code, 'address' => $getpickupdetails->row()->address, 'pincode' => $getpickupdetails->row()->pincode, 'country' => $getpickupdetails->row()->country );
                }
                $drop_id     = $chkorder->row()->drop_custid;
                $drop_row_id = 0;
                $chekparty   = $this->db->query( "SELECT p.id,p.party_type_id, p.name, p.mobile, p.email,p.code,p.fax,o.party_type FROM tbl_party_master p INNER JOIN tb_order_parties o ON p.id=o.party_id AND o.status=1  WHERE p.status=1 AND o.order_id='$id' GROUP BY o.party_type" );
                if ( $chekparty->num_rows() > 0 ) {
                    foreach ( $chekparty->result() as $rr ) {
                        $ptype   = $rr->party_type;
                        $chktype = $this->db->select( "name" )->get_where( "tbl_party_types", array( "id" => $ptype ), 1, 0 );
                        if ( $chktype->num_rows() > 0 ) {
                            if ( $chktype->row()->name == "Consignee" ) {
                                $drop_details = array( 'id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code );
                            } else if ( $chktype->row()->name == "Shipper" ) {
                                $shipper_details = array( 'id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code );
                            }
                        }
                    }
                }
                $shipper_details['name']    = $chkorder->row()->pickup;
                $shipper_details['street']  = $chkorder->row()->pickup_address1;
                $shipper_details['state']   = $chkorder->row()->pickup_address2;
                $shipper_details['city']    = $chkorder->row()->pickup_city;
                $shipper_details['country'] = $chkorder->row()->pickup_country;
                $shipper_details['pincode'] = $chkorder->row()->pickup_pincode;

                $drop_details['name']    = $chkorder->row()->delivery;
                $drop_details['street']  = $chkorder->row()->delivery_address1;
                $drop_details['state']   = $chkorder->row()->delivery_address2;
                $drop_details['city']    = $chkorder->row()->delivery_city;
                $drop_details['country'] = $chkorder->row()->delivery_country;
                $drop_details['pincode'] = $chkorder->row()->delivery_pincode;
                $drop_id                 = $chkorder->row()->drop_custid;
            }

            $roles = array();
            $qyery = $this->db->query( "SELECT id,name FROM tbl_party_types WHERE user_id= '" . $user_id . "' AND status=1 GROUP BY name" );
            if ( $qyery->num_rows() > 0 ) {
                foreach ( $qyery->result() as $res ) {
                    $roles[] = array( 'id' => $res->id, 'name' => $res->name );
                }
            }
            $getchargecodes = $this->db->select( "id,charge_code" )->get_where( "tb_charge_codes", array( 'status' => '1' ) );
            if ( $getchargecodes->num_rows() > 0 ) {
                foreach ( $getchargecodes->result() as $res ) {
                    $chargecodes[] = array( 'charge_id' => $res->id, 'charge_code' => $res->charge_code );
                }
            }
        }
        $vas_ids = array();
        if ( $company_code == 'RUKN' ) {
            $getvas_ids = $this->db->select( "id,vas_id,vas_name" )->get_where( "tb_vas_master", array( 'company_code' => $company_code, 'status' => '1' ) );
        } else {
            $getvas_ids = $this->db->select( "id,vas_id,vas_name" )->get_where( "tb_vas_master", array( 'status' => '1', 'company_code!=' => 'RUKN' ) );
        }
        if ( $getvas_ids->num_rows() > 0 ) {
            foreach ( $getvas_ids->result() as $res ) {
                $vas_ids[] = array( 'vas_row_id' => $res->id, 'vas_id' => $res->vas_id . "-" . $res->vas_name );
            }
        }
        $transport = array();
        $order_date=$createdon;
        $less_date ='2021-03-19 00:00:00';
        $transport = gettransportmode($order_date,$less_date);
        $data['stoppagecodes'] = $data['resolutioncodes'] = array();
        $select                = "id,code";
        $getstoppage           = $this->Order->getmasters( 'tbl_stoppage_master', $select );
        if ( $getstoppage->num_rows() > 0 ) {
            foreach ( $getstoppage->result() as $res ) {
                $data['stoppagecodes'][] = array( 'id' => $res->id, 'code' => $res->code );
            }
        }
        $select        = "id,name";
        $getresolution = $this->Order->getmasters( 'tbl_resolution_master', $select );
        if ( $getresolution->num_rows() > 0 ) {
            foreach ( $getresolution->result() as $res ) {
                $data['resolutioncodes'][] = array( 'id' => $res->id, 'name' => $res->name );
            }
        }
        if ( $company_code == 'VNKN' ) {
            $this->load->helper( 'generic' );
            $data['vn_currencies'] = getVNCurrencies(); //this was view-tb in DB side
        }
        $data['vatcategory'] = array();
        $getvatcategory = $this->common->gettbldata(array('company_code'=>$company_code,'status' => '1'),"id,description,vat_category,vat_percentage","tb_vat_category",0,0);
        if (!empty($getvatcategory)) {
            foreach ($getvatcategory as $res) {
                $val = $res['id']."_".$res['vat_category'];
                $desc = $res['description']." (".$res['vat_category']."-".$res['vat_percentage'].")";
                $data['vatcategory'][] = array('id' => $res['id'],'val'=>$val, 'desc'=>$desc);
            }
        }
        $data['spotondata'] = array();
        $data['spoton_lr_exist']=0;
        $getspotondata = $this->common->gettbldata(array('order_id'=>$id,'reference_id' => 'BN'),"ref_value,updatedon","tb_order_references",0,0);
        if (!empty($getspotondata)) {
            $data['spotondata']=$getspotondata;
            $data['spoton_lr_exist']=1;
        }
       
        $arrCostCenter = [];
        if($company_code == 'NZPG' ){
            $getCostCenter = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_cost_center", array( 'company_code' => $company_code, "status" => '1' ) );
            if ( $getCostCenter->num_rows() > 0 ) {
                foreach ( $getCostCenter->result() as $res ) {
                    $arrCostCenter[] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                }
            }
        }

        $data['transport']       = $transport;
        $data['order_details']   = $order_details;
        $data['pickup_details']  = $pickup_details;
        $data['drop_details']    = $drop_details;
        $data['shipper_details'] = $shipper_details;
        $data['order_types']     = $order_types;
        $data['cost_center']     = $arrCostCenter;
        $data['delivery_array']  = $delivery_array;
        $data['chargecodes']     = $chargecodes;
        $data['roles']           = $roles;
        $data['vas_ids']         = $vas_ids;
        $data['marks_numbers_column'] = checkAccessConditions('MARKS_AND_NUMBERS_OPTION', $company_code);
        $this->load->view('orders/editorder', $data);
    }
    
    public function viewroletypelist() {
        $data = array();
        $post = $this->input->post(NULL, TRUE);
        $type = isset( $post['type'] ) ? $post['type'] : "";
        $screen_type = isset( $post['screen_type'] ) ? $post['screen_type'] : "";
        if ( $type != "" ) {
            $user_id = $this->session->userdata( 'user_id' );
            if ( $user_id != '0' ) {
                if ( $type == "Vendor" ) {
                    $type = "Carrier";
                }
 
                $user_whr = "m.user_id ='" . $user_id . "'";
                $company_code = $this->session->userdata('company_code');
                $permission = checkuserpermissions();
                if(in_array("businesspartners", $permission)){
                    $user_whr = "m.company_code LIKE '" . $company_code . "'";
                } else {
                    $user_whr = "m.user_id ='" . $user_id . "'";
                }
                
                $this->db->select( "m.id,m.name,m.email,m.code,m.company_code,m.branch_code,m.country,m.location_id,m.street" );
                $this->db->from( "tbl_party_master m" );
                $this->db->join( "tbl_party_types p", "p.id=m.party_type_id", "LEFT" );
                if ( $type == "Overseas OL" ) {
                    $this->db->where( 'm.category_type', 'Overseas OL' );
                } else if ( $type == "Internal BU" ) {
                    $this->db->where( 'm.category_type', 'KN Office' );
                } else {
                    $this->db->like( "p.name", $type );
                }
                $this->db->where( $user_whr );
                $where = "m.acon_debitor_code is  NOT NULL";
                $this->db->where( $where );
                $getroles = $this->db->get();
                if ( $getroles->num_rows() > 0 ) {
                    if($screen_type != "charges_distribution"){
                        foreach ( $getroles->result() as $res ) {
                            $check = "";
                            if ( $type == "Customer" ) {
                                $check = "<input class='rolelist' type='radio' name='selectrole' id='rolelist_" . $res->id . "' value='" . $res->code . "' onchange=selectrolebyid(" . $res->id . ")>";
                            }
                            if ( $type == "Carrier" ) {
                                $check = "<input class='vendorlist' type='radio' name='selectvendor' id='vendorlist_" . $res->id . "' value='" . $res->code . "' onchange=selectvendorbyid(" . $res->id . ")>";
                            }
                            if ( $type == "Overseas OL" || $type == "Internal BU" ) {
                                $check = "<input class='twopartieslist' type='radio' name='selectparties' id='twopartieslist_" . $res->id . "' value='" . $res->code . "' onchange=selectpartiesbyid(" . $res->id . ")>";
                            }
                            $data[] = array( 'check' => $check, 'id' => $res->id, 'code' => $res->code, 'name' => $res->name, 'email_id' => $res->email, 'company_code' => $res->company_code, 'branch_code' => $res->branch_code, 'country' => $res->country, 'street' => $res->street, 'city' => $res->location_id );
                        }
                    }else{
                        foreach ( $getroles->result() as $res ) {
                            $check = "";
                            if ( $type == "Customer" || $type == "Carrier" ) {
                                $check = "<input class='rolelist' type='radio' name='selectrole' id='rolelist_" . $res->id . "' value='" . $res->code . "' onchange=selectrolecode(" . $res->id . ")>";
                            }
                            $data[] = array( 'check' => $check, 'id' => $res->id, 'code' => $res->code, 'name' => $res->name, 'email_id' => $res->email, 'company_code' => $res->company_code, 'branch_code' => $res->branch_code, 'country' => $res->country, 'street' => $res->street, 'city' => $res->location_id );
                        }
                    }
                }

            }
        }
        echo json_encode( $data );
    }

    public function getorderstatusdetails()
    {
        $status = $statusCodes = $remainingStatusCodes = [];
        $currentTimeZone = $this->session->userdata("usr_tzone")['timezone'];
        $orderId = $this->input->post('order_id', true);
        if ($orderId > 0) {
            $getOrderDetails = $this->common->gettblrowdata(['id' => $orderId], "shift_id,company_code,CONCAT(`pickup_address1`,',',`pickup_city`,',',`pickup_address2`,',',`pickup_country`,',',`pickup_pincode`) AS pickupaddress,
CONCAT(`delivery_address1`,',',`delivery_address2`,',',`delivery_city`,',',`delivery_country`,',',`delivery_pincode`) AS deliveryaddress ", "tb_orders", 0, 0);
            if (!empty($getOrderDetails)) {
                $orderCompanyCode = $getOrderDetails['company_code'];
                $orderStatus = $this->common->getjointbldata("tb_order_status o", "tb_status_master s", "o.status_id = s.id", ['o.order_id' => $orderId, 'o.status' => '1'], "o.id,o.latitude,o.longitude,o.status_code,convertToClientTZ(o.status_date, '" . $currentTimeZone . "') as status_date,o.createdon,s.status_name,o.status_reason,o.comment", 0, 0);
                Log_message("error","orderStatusQry:".$this->db->last_query());
                foreach ($orderStatus as $eachStatus) {
                    $locationName = getLocationName($eachStatus['latitude'], $eachStatus['longitude']);
                    $location = '"' . $locationName . '"';
                    $statusCode = '"' . $eachStatus['status_code'] . '"';
                    $createdon = $eachStatus['status_date'];
                    $date = '"' . $createdon . '"';
                    $stop_type = "P";
                    if (strtoupper($locationName) == "CHINA" and $orderCompanyCode == 'CNKN') {
                        if ($stop_type != "D") {
                            $locationName = $getOrderDetails['pickupaddress'];
                        } else {
                            $locationName = $getOrderDetails['deliveryaddress'];
                        }
                    }
                    $statusValue = '"' . $eachStatus['status_code'] . '_' . $stop_type . '_' . $eachStatus['status_name'] . '"';
                    $statusName = '"' . $stop_type . '-' . $eachStatus['status_name'] . '"';

                    $comments = '" "';
                    $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown-toggle' data-toggle='dropdown' href='#'><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAddstatus(this);'><span class='glyphicon glyphicon-plus' > </span>Add Status</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowEditStatus(this," . $eachStatus['id'] . "," . $statusCode . "," . $location . "," . $date . "," . $statusValue . "," . $statusName . "," . $comments . ");'><span class='glyphicon glyphicon - pencil' > </span>Edit</a></li></ul></li></ul>";
                    $status[] = [
                        'id' => $eachStatus['id'],
                        'status_name' => $eachStatus['status_name'],
                        'date' => $createdon,
                        'action' => $action,
                        'stop_id' => $eachStatus['status_code'],
                        'status_type' => $stop_type. " ( " . $eachStatus['status_reason'] . " )",
                        'location' => $locationName,
                        'comment' => $eachStatus['comment'],
                    ];
                }
                $orderShiftId = $getOrderDetails['shift_id'];

                $stopStatus = $this->smtcorder->getStopStatusForOrder(['orderId' => $orderId, 'timeZone' => $currentTimeZone, 'orderCompanyCode' => $orderCompanyCode]);
                Log_message("error","stopStatusQry:".$this->db->last_query());
                foreach ($stopStatus as $eachStatus) {
                    $statusCodes[] = $eachStatus['status_code'];
                }
                if($orderShiftId >0) {
                    if (!in_array('0212', $statusCodes)) {
                        $remainingStatusCodes[] = '0212';
                    }
                    if (!in_array('0100', $statusCodes)) {
                        $remainingStatusCodes[] = '0100';
                    }
                    if (!empty($remainingStatusCodes)) {
                        $getDriverAcceptence = $this->common->gettbldata("status_code IN (" . implode(',', $remainingStatusCodes) . ") and shipment_id ='" . $orderShiftId . "' AND status =1", "id,latitude,longitude,loc_name,stop_id,stop_type,status_code,convertToClientTZ(createdon,'" . $currentTimeZone . "') as createdon,reason,comment", "tb_stop_status", 0, 0);
                        foreach ($getDriverAcceptence as $eachRow) {
                            if ($eachRow['status_code'] == '0100') {
                                $eachRow['status_name'] = "Booked by Supplier";
                            } else {
                                $eachRow['status_name'] = "Accepted by Driver";
                            }
                            $stopStatus[] = $eachRow;
                        }
                    }
                }
                
                foreach ($stopStatus as $eachStatus) {
                    $locationName = $eachStatus['loc_name'];
                    if ($locationName == "") {
                        $locationName = getLocationName($eachStatus['latitude'], $eachStatus['longitude']);
                    }
                    $location = '"' . $locationName . '"';
                    $statusCode = '"' . $eachStatus['status_code'] . '"';
                    $comment = '"' . $eachStatus['comment'] . '"';
                    $stopType = $eachStatus['stop_type'];
                    if ($stopType == "") {
                        $stopType = "P";
                    }
                    if ($statusCode == 'KN007') {
                        $name = 'PickUp';
                    } else {
                        $name = $eachStatus['status_name'];
                    }
                    if (strtoupper($locationName) == "CHINA" and $orderCompanyCode == 'CNKN') {
                        if ($stopType != "D") {
                            $locationName = $getOrderDetails['pickupaddress'];
                        } else {
                            $locationName = $getOrderDetails['deliveryaddress'];
                        }
                    }
                    $finalStatusName = $eachStatus['status_name'];
                    if ($orderCompanyCode == "RUKN") {
                        if ($eachStatus['status_code'] == "0500") {
                            $name = $finalStatusName = 'Actual Pick Up';
                        }
                        if ($eachStatus['status_code'] == "3000") {
                            $name = $finalStatusName = 'Delivery To Consignee';
                        }
                        if ($eachStatus['status_code'] == "2300") {
                            $sts_finalname = 'Arrival at Delivery Point';
                        }
                    }
                    $statusValue = '"' . $eachStatus['status_code'] . '_' . $stopType . '_' . $name . '"';
                    $date = '"' . $eachStatus['createdon'] . '"';
                    $statusName = '"' . $stopType . '-' . $name . '"';
                    if(in_array($eachStatus['status_code'],['1500','1600'])){
                        $stopType = "";
                    }
                    $action = "<ul class='nav nav - tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown - toggle' data-toggle='dropdown' href='#'><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAddstatus(this);'><span class='glyphicon glyphicon-plus' > </span>Add Status</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowEditStatus(this," . $eachStatus['id'] . "," . $statusCode . "," . $location . "," . $date . "," . $statusValue . "," . $statusName . "," . $comment . ");'><span class='glyphicon glyphicon-pencil' > </span>Edit</a></li></ul></li></ul>";
                    $status[] = [
                        'id' => $eachStatus['id'],
                        'lattitude' => $eachStatus['latitude'],
                        'longitude' => $eachStatus['longitude'],
                        'stop_id' => $eachStatus['status_code'],
                        'status_name' => $finalStatusName,
                        'date' => $eachStatus['createdon'],
                        'action' => $action,
                        'location' => $locationName,
                        'status_type' => $stopType . " ( " . $eachStatus['reason'] . " )",
                        'comment' => $eachStatus['comment'],
                    ];
                }
            }
        }
        echo json_encode($status);
    }
    public function orddocsdetails() {
        $status   = array();
        $order_id = $this->input->post( 'order_id' );
        if ( $order_id != "" ) {
            $curtz = $this->session->userdata( "usr_tzone" )['timezone'];
            $sql1  = $this->db->query( "SELECT ts.id,ts.latitude,ts.longitude,ts.stop_id,ts.stop_type,dt.type_name,ts.createdby,convertToClientTZ(ts.createdon,'" . $curtz . "') as createdon,ts.imgpath,ts.user_id  from tb_pod_uploads ts LEFT JOIN tb_document_types dt ON dt.id=ts.doc_type WHERE ts.order_id = $order_id AND ts.status='1' GROUP BY ts.id" );
            if ($sql1->num_rows() > 0 ) {
                foreach ( $sql1->result() as $res ) {
                    if($res->latitude!="" && $res->longitude!="" ){
                        $location_name = getLocationName($res->latitude, $res->longitude);
                    }else{
                        $location_name='';
                    }


                    if($location_name==''){
                        $where = array("id"=>$order_id);
                        $getlocationorder=$this->db->select("order_id")->get_where("tb_orders",$where,1,0);
                        if($getlocationorder->num_rows()>0){
                            $getorderrid=$getlocationorder->row()->order_id;
                            $where = array("order_id"=>$getorderrid);
                            $getlocation=$this->db->select(" `pickup`,`drop`")->get_where("tb_employee",$where,1,0);
                            if($getlocation->num_rows()>0){
                                if($res->stop_type=='P'){
                                    $location_name = $getlocation->row()->pickup;
                                }
                                if($res->stop_type=='D'){
                                    $location_name = $getlocation->row()->drop;
                                }
                            }

                        }
                    }

                    $imgpath       = "";
                    $allowed       = array( 'pdf' );
                    if ( $res->imgpath != "" ) {
                        $base64DocumentData = getBase64DocumentData($res->imgpath);
                        $extention = $base64DocumentData['extention'];
                        $stringData = "'".$base64DocumentData['file_content']."',"."'".$extention."'";
                        if ($extention!= "") {
                            if (in_array($extention, $allowed)) {
                                $path = '<a onclick="return downloadDocument(' . $stringData . ')"> <img src="' . base_url('assets/img/docstore.png') . '" class="img-responsive" style="width: 10%;" type="application/pdf"></a>';
                            } else {
                                $path = '<a onclick="return downloadDocument(' . $stringData . ')"><img src="' . $base64DocumentData['file_content'] . '" class="img-responsive" style="width: 10%;"></a>';
                            }
                        }
                        $driver   = getDrivernameById( $res->createdby )["name"];
                        if($driver==""){
                            if($res->user_id!=0){
                                $where = array("id"=>$res->user_id);
                                $getuser=$this->db->select("name")->get_where("tb_users",$where,1,0);
                                if($getuser->num_rows()>0){
                                    $driver = $getuser->row()->name;

                                }
                            } else {
                                $where = array("id" => $this->session->userdata("user_id"));
                                $getuser = $this->db->select("name")->get_where("tb_users", $where, 1, 0);
                                if ($getuser->num_rows() > 0) {
                                    $driver = $getuser->row()->name;
                                }
                            }
                        }
                        $action = "";
                        $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft '> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowdocAdd(this," . $order_id . ")'><span class='glyphicon glyphicon-plus' > </span>Add Doc</a></li></li></ul>";
                        $status[] = array(
                            'id' => $res->id,
                            'type_name' => $res->type_name,
                            'imgpath' => $path ?? 'N/A',
                            'stop_id' => $res->stop_id,
                            'stop_type' => $res->stop_type,
                            'date' => date("d M,y h:i A", strtotime($res->createdon)),
                            'action' => $action,
                            'location' => $location_name,
                            'driver' => $driver
                        );
                    }

                }
            }
        }
        echo json_encode( $status );
    }

    public function addorderdoc() {
        $order_id             = isset( $_POST['order_id'] ) ? $_POST['order_id'] : "0";
        $data['stops']        = $data['document_types'] = array();
        $data['booking_id']   = $data['shift_id'] = $data['trip_id'] = $booking_id = 0;
        $data['company_code'] = $data['branch_code'] = "";
        if ( $order_id != "" && $order_id != '0' ) {
            $ord             = $order_id;
            $getorderdetails = $this->db->select( "id,order_id,company_code,branch_code,shift_id,trip_id" )->get_where( "tb_orders", array( 'id' => $order_id ) );
            if ( $getorderdetails->num_rows() > 0 ) {
                $data['order_row_id'] = $getorderdetails->row()->id;
                $data['booking_id']   = $booking_id = $getorderdetails->row()->order_id;
                $data['company_code'] = $getorderdetails->row()->company_code;
                $data['branch_code']  = $getorderdetails->row()->branch_code;
                $data['shift_id']     = $getorderdetails->row()->shift_id;
                $data['trip_id']      = $getorderdetails->row()->trip_id;
            }
            $sql   = "SELECT o.id,o.stopname FROM tb_shiporder_stops o,tb_employee e WHERE o.shipment_id=e.shift_id AND e.order_id='" . $booking_id . "' AND o.status=1 AND e.status=1 ORDER BY o.ordernumber ASC";
            $stops = $this->db->query( $sql );
            if ( $stops->num_rows() > 0 ) {
                $data['stops']          = $stops->result_array();
                $data['document_types'] = $this->db->select( "id,type_name" )->get_where( "tb_document_types", array( "status" => 1 ) )->result_array();
            } else {
                $data['document_types'] = $this->db->select( "id,type_name" )->get_where( "tb_document_types", array( "status" => 1, "type_name" => 'Others' ) )->result_array();
            }
        }
        echo json_encode( $data );
    }

    public function checktripfororder(): void
    {
        $orderId = $this->input->post('order_id', true);
        $response = $this->tripcreatefromorders->buildOrderStatusesSelect($orderId);
        echo json_encode($response);
    }

    public function addstatus( $id = NULL ) {
        $curtz = $this->session->userdata("usr_tzone")['timezone'];
        $logdate = date('Y-m-d H:i:s');
        $getactual = getdatetimebytimezone(DFLT_TZ, $logdate, $curtz);
        $curdt = $getactual['datetime'];
        $hrs = $this->session->userdata("usr_tzone")['hrs'];
        $post = $this->input->post(null, true);
        $order_id = $post['order_status_id'] ?? 0;
        if ( $order_id != "0" ) {
            $user_id = $this->session->userdata('user_id');
            $getOrderDetails = $this->completedordersmodel->getOrderDetailsWithLatLngs($order_id);
            $createdsource = $getOrderDetails['createdSource'];
            $booking_id = $getOrderDetails['bookingId'];
            $shift_id = $getOrderDetails['shiftId'];
            $trip_id = $getOrderDetails['tripId'];
            $plat = $getOrderDetails['plat'];
            $plng = $getOrderDetails['plng'];
            $dlat = $getOrderDetails['dlat'];
            $dlng = $getOrderDetails['dlng'];
            $ord_id = $order_id;
            $status_code = $post['status_code'] ?? "";
            $status_date = $post['status_date'] ?? date('Y-m-d H:i:s');
            $genstatustime = getdatetimebytimezone(DFLT_TZ, $status_date, $curtz);
            $status_date = $genstatustime['datetime'];
            $pshipid = $post['pshipid'] ?? "0";
            $dshipid = $post['dshipid'] ?? "0";
            $pstopdetailsid = $post['pstopdetailsid'] ?? "0";
            $dstopdetailsid = $post['dstopdetailsid'] ?? "0";
            $sname = $post['status_name'] ?? "";
            if ($sname != "") {
                $sts = explode('_', $sname);
            }
            $stop_type = $sts[1] ?? "P";
            $status_name = $sts[2] ?? "";
            $lattitude = $stop_type == "P" ? $plat : $dlat;
            $longitude = $stop_type == "P" ? $plng : $dlng;
            if ($this->session->userdata('user_role_id') === "5") {
                $statusReason = "From KNOps";
            } else {
                $statusReason = "From Admin";
            }
            $status_id = 0;
            if ( $status_code == "0420" ) {
                $status_id = "2";
            }
            if ( $status_code == "0500" ) {
                $status_id = "1";
            }
            if ( $status_code == "0191" ) {
                $status_id = "3";
            }
            if ( $status_code == "1550" ) {
                $status_id = "4";
            }
            if ( $status_code == "0192" ) {
                $status_id = "2";
            }
            if ( $status_code == "2300" ) {
                $status_id = "1";
            }
            if ( $status_code == "3000" ) {
                $status_id = "3";
            }

            if ($this->session->userdata('company_code') == 'UKKN-CG' && $status_code === '0212') {
                $this->openboxstatusaccept->pushStatusXml($trip_id);
            }

            if ($this->session->userdata('company_code') == 'UKKN-CG' && $status_code !== '0212') {
                $this->openbox_status_execution->pushStatusExecutionXml(["status" => $status_code, "order_row_id" => $order_id, "trip_id" => $trip_id, "date_time" => $status_date, "lat" => $lattitude, "long" => $longitude]);
            }

            if ( $status_id == 0 ) {
                $getstatusid = $this->db->select( "id" )->get_where( "tb_status_master", array( 'status_code' => $status_code ) );
                if ( $getstatusid->num_rows() > 0 ) {
                    $status_id = $getstatusid->row()->id;
                }
            }
            if ( $this->session->userdata( 'company_code' ) == "UKKN" || $this->session->userdata( 'company_code' ) == "AUKN" ) {
                if ( $status_code != "TL" && $status_code != "CL" && $status_code != "LY" ) {
                    if ( $id == "" ) {
                        $lattitude = $plat;
                        $longitude = $plng;
                        $status_ar = array( 'order_id' => $order_id, 'status_id' => $status_id, 'latitude' => $lattitude, 'longitude' => $longitude, 'status_code' => $status_code, 'status' => '1', 'status_date' => $status_date, 'createdon' => $status_date );
                        /*$chksts = $this->db->select("id")->get_where("tb_order_status",array('order_id'=>$order_id,'status_id'=>$status_id,'status_code'=>$status_code));
                    if($chksts->num_rows() == 0){*/
                        $ins = $this->db->insert( "tb_order_status", $status_ar );
                        if ( $ins ) {
                            /*send status xml to amazon*/
                            $this->load->library( "amazonstatusintegration" );
                            $postdata = array(
                                "shipment_id" => $shift_id,
                                "trip_id"     => $trip_id,
                                "driver_id"   => 0,
                                "vehicle_id"  => 0,
                                "order_id"    => $booking_id,
                                "user_id"     => $user_id,
                                "stop_id"     => '',
                                "latitude"    => $lattitude,
                                "longitude"   => $longitude,
                                "curtz"       => $curtz,
                                "hrs"         => $hrs,
                                "web"         => $status_date,
                                "status_code" => $status_code,
                                "ord_id"      => $order_id
                            );
                            $sts      = $this->amazonstatusintegration->updateOrderStatus( $postdata );
                            echo "1";
                        }
                        /*}*/
                    } else {
                        $upd = $this->db->where( array( 'id' => $id ) )->update( "tb_order_status", array( 'status_date' => $status_date, 'createdon' => $status_date ) );
                        echo "1";
                    }
                }
            }
            if (in_array($status_code, ['1013', '1012', '1014'])) {
                if ($id == "") {
                    $insertedId = $this->common->insertTableData("tb_order_status", ['order_id' => $order_id, 'status_id' => $status_id, 'latitude' => $plat, 'longitude' => $plng, 'status_code' => $status_code, 'status' => '1', 'status_date' => $status_date, 'createdon' => $status_date]);
                    if ($insertedId) {
                        echo "1";
                    }
                } else {
                    $updatedId = $this->common->updatetbledata("tb_order_status", ['status_date' => $status_date, 'createdon' => $status_date], ['id' => $id]);
                    if($updatedId){
                        echo "1";
                    }
                }
            } elseif (in_array($status_code, ['1500', '1600','0200', '0220', '1065', '3400'])) {
                $comment = $this->input->post('comment',true);
                $location = $this->input->post('location',true);
                if ($id == "") {
                    $insertedId = $this->common->insertTableData("tb_stop_status", ['order_id' => $order_id, 'status_id' => $status_id, 'status_code' => $status_code, 'stop_type' => '', 'loc_name' => $location, 'comment' => $comment, 'status' => '1', 'reason' => $statusReason, 'createdon' => $status_date]);
                    if ($insertedId) {
                        echo "1";
                    }
                } else {
                    $updatedId = $this->common->updatetbledata("tb_stop_status", ['createdon' => $status_date, 'sentknlogin' => '0', 'loc_name' => $location, 'comment' => $comment], ['id' => $id]);
                    if($updatedId){
                        echo "1";
                    }
                }
                if ($createdsource == '5' && in_array($status_code, ['0200', '0220', '1065', '3400'])) {
                    $postdata['status_code'] = $status_code;
                    $postdata['ord_id'] = $ord_id;
                    $postdata['shipment_id'] = $postdata['trip_id'] = 0;
                    $this->statusintigration->salogshipmentstatus($postdata);
                }
            }  else {
                if ( $id == "" ) {
                    $vehicle_id  = 0;
                    $contact_num = "";
                    $driver_id   = 0;
                    $stop_id     = $stopdetailid = 0;
                    if ( $stop_type == 'P' ) {
                        $stop_id      = $pshipid;
                        $stopdetailid = $pstopdetailsid;
                    } else {
                        $stop_id      = $dshipid;
                        $stopdetailid = $dstopdetailsid;
                    }
                    /*       $gentime = getdatetimebytimezone(DFLT_TZ,$status_date,$curtz);
                    $stsdate = $gentime['datetime'];*/
                    $stsdate      = $status_date;
                    $getvehicleid = $this->db->select( "vehicle_id" )->get_where( "tb_shft_veh", array( 'shft_id' => $shift_id ) );
                    if ( $getvehicleid->num_rows() > 0 ) {
                        $vehicle_id = $getvehicleid->row()->vehicle_id;
                    }
                    $checktrip = $this->db->query( "SELECT id,vehicle_id,driver_id,start_imei FROM tb_trips WHERE shift_id=$shift_id AND status=1" );
                    if ( $checktrip->num_rows() > 0 ) {
                        $contact_num = $checktrip->row()->start_imei;
                        $trip_id     = $checktrip->row()->id;
                        $vehicle_id  = $checktrip->row()->vehicle_id;
                        $driver_id   = $checktrip->row()->driver_id;
                    }
                    if ( $trip_id == 0 && $vehicle_id != "" ) {
                        $checktrip1 = $this->db->query( "SELECT d.vehicle_id,d.driver_id,d.imei FROM tbl_assigned_drivers d WHERE d.vehicle_id=$vehicle_id AND d.status=1 LIMIT 1" );
                        if ( $checktrip1->num_rows() > 0 ) {
                            $vehicle_id  = $checktrip1->row()->vehicle_id;
                            $driver_id   = $checktrip1->row()->driver_id;
                            $contact_num = $checktrip1->row()->imei;
                        }
                    }
                    if ( $this->session->userdata( 'company_code' ) == "UKKN" || $this->session->userdata( 'company_code' ) == "AUKN" ) {
                        if ( $status_code == "TL" || $status_code == "CL" || $status_code == "LY" ) {
                            if ( $status_code == "TL" ) {
                                $chqry1 = $this->db->select( "id,trip_id" )->get_where( "tb_stop_status", array( 'order_id' => $order_id, 'shipment_id' => $shift_id, "status_id" => '10', "status" => 1 ), 1, 0 );
                                if ( $chqry1->num_rows() == 0 ) {
                                    if ( $shift_id != "" ) {
                                        $status_id = '10';
                                        $trip_id = '0';
                                    }
                                } else {
                                    $trip_id   = $chqry1->row()->trip_id;
                                    $status_id = 2;
                                    $stop_type = "P";
                                }
                            } else if ( $status_code == "CL" ) {
                                $chqry1 = $this->db->select( "id,trip_id" )->get_where( "tb_stop_status", array( 'order_id' => $order_id, 'shipment_id' => $shift_id, "status_id" => '2', "status" => 1 ), 1, 0 );
                                if ( $chqry1->num_rows() > 0 ) {
                                    $status_id = 1;
                                    $stop_type = "P";
                                }
                            } else if ( $status_code == "LY" ) {
                                $chqry1 = $this->db->select( "id,trip_id" )->get_where( "tb_stop_status", array( 'order_id' => $order_id, 'shipment_id' => $shift_id, "status_id" => '1', "status" => 1 ), 1, 0 );
                                if ( $chqry1->num_rows() > 0 ) {
                                    $status_id = 3;
                                    $stop_type = "P";
                                }
                            }
                        }
                    }
                    if ( $status_id == '10' && $trip_id == '0' ) {
                        $chqry = $this->db->select( "id" )->get_where( "tb_trips", array( 'shift_id' => $shift_id, 'vehicle_id' => $vehicle_id, 'driver_id' => $driver_id ), 1, 0 );
                        if ( $chqry->num_rows() == 0 ) {
                            if ( $contact_num == "" ) {
                                $newimei = $this->db->select( "imei" )->get_where( "tbl_assigned_drivers", array( 'vehicle_id' => $vehicle_id, 'driver_id' => $driver_id, 'status' => 1 ), 1, 0 );
                                if ( $newimei->num_rows() > 0 ) {
                                    $contact_num = $newimei->row()->imei;
                                }
                            }
                            $lattitude = $plat;
                            $longitude = $plng;
                            $triparr   = array(
                                'shift_id'       => $shift_id,
                                'vehicle_id'     => $vehicle_id,
                                'driver_id'      => $driver_id,
                                'stime'          => $stsdate,
                                'start_imei'     => $contact_num,
                                'splace'         => "",
                                'eplace'         => "",
                                'start_reading'  => 0,
                                'end_reading'    => 0,
                                'created_on'     => $stsdate,
                                'updated_on'     => $curdt,
                                'status'         => 1,
                                'trip_type'      => 0,
                                'transit_status' => 0
                            );
                            $trip_id   = $this->common->insertTableData( 'tb_trips', $triparr );
                            $insarry   = array(
                                'order_id'       => $order_id,
                                "shipment_id"    => $shift_id,
                                "stop_id"        => 0,
                                "stop_detail_id" => 0,
                                "stop_type"      => "",
                                "trip_id"        => $trip_id,
                                "status_id"      => $status_id,
                                "latitude"       => $lattitude,
                                "longitude"      => $longitude,
                                "status"         => 1,
                                "reason"         => $statusReason,
                                "vehicle_id"     => $vehicle_id,
                                "driver_id"      => $driver_id,
                                "status_code"    => $status_code,
                                "createdon"      => $stsdate
                            );
                            $ins       = $this->db->insert( "tb_stop_status", $insarry );
                            /* update orders table */
                            $ordwhr = array( "shift_id" => $shift_id );
                            $ordset = array( "trip_id" => $trip_id );
                            $upd    = $this->db->set( $ordset )->where( $ordwhr )->update( "tb_orders" );

                            $postdata = array(
                                "shipment_id" => $shift_id,
                                "trip_id"     => $trip_id,
                                "driver_id"   => $driver_id,
                                "vehicle_id"  => $vehicle_id,
                                "order_id"    => $booking_id,
                                "user_id"     => $user_id,
                                "stop_id"     => '',
                                "latitude"    => $lattitude,
                                "longitude"   => $longitude,
                                "curtz"       => $curtz,
                                "hrs"         => $hrs,
                                "web"         => '',
                                "status_code" => $status_code,
                                "ord_id"      => $order_id,

                            );
                            if ( $createdsource == "18" ) {
                                $sts = $this->statusintigration->roadlogshipmentconfirm($postdata);
                                $companyCode = $this->session->userdata('company_code');
                                $branchCode = $this->session->userdata('branch_code');
                                $userId = $this->session->userdata('user_id');
                                $edi_reference = $this->shippeostatusintigration->is_shippeo_order($ord_id, $companyCode, $branchCode);
                                if ($edi_reference != 0) {
                                    $sts = $this->shippeostatusintigration->shippeo_event_call($ord_id, $postdata, $curtz, $status_id, $stop_type, $vehicle_id, $edi_reference, $companyCode, $branchCode, $userId);
                                }
                            } else if ( $createdsource == '9' ) {
                                $postdata['status_code'] = '0212';
                                $sts                     = $this->etrucknowquote->getstatusresponse( $postdata );
                            } else if ( $createdsource == '13' ) {
                                $this->load->library( "amazonstatusintegration" );
                                $sts = $this->amazonstatusintegration->outboundTrailerASN( $postdata );
                            }
                        }
                        echo '1';
                    } else {
                        if ( $trip_id != "0" && $status_id != "11" ) {
                            $chqry = $this->db->select( "id" )->get_where( "tb_stop_status", array( "shipment_id" => $shift_id, "stop_id" => $stop_id, "stop_detail_id" => $stopdetailid, "stop_type" => $stop_type, "trip_id" => $trip_id, "status_id" => $status_id ), 1, 0 );
                            if ( $chqry->num_rows() == 0 ) {
                                if ( $status_id == "2" && $stop_type == "P" ) {
                                    $ttdata                  = array( "id" => $trip_id );
                                    $data2["updated_on"]     = $curdt;
                                    $data2["transit_status"] = '1';
                                    $res                     = $this->db->set( $data2 )->where( $ttdata )->update( "tb_trips" );
                                }
                                if ( $stop_type == "P" || $status_id == "4" ) {
                                    $lattitude = $plat;
                                    $longitude = $plng;
                                }
                                if ( $stop_type == "D" ) {
                                    $lattitude = $dlat;
                                    $longitude = $dlng;
                                }
                                $insarry = array(
                                    "shipment_id"    => $shift_id,
                                    'order_id'       => $order_id,
                                    "stop_id"        => $stop_id,
                                    "stop_detail_id" => $stopdetailid,
                                    "stop_type"      => $stop_type,
                                    "trip_id"        => $trip_id,
                                    "status_id"      => $status_id,
                                    "latitude"       => $lattitude,
                                    "longitude"      => $longitude,
                                    "status"         => 1,
                                    "reason"         => $statusReason,
                                    "vehicle_id"     => $vehicle_id,
                                    "driver_id"      => $driver_id,
                                    "status_code"    => $status_code,
                                    "createdon"      => $stsdate
                                );
                                $ins     = $this->db->insert( "tb_stop_status", $insarry );
                                /*}*/
                                $chqry1 = $this->db->select( "id" )->get_where( "tb_trip_employee", array( "employee_id" => $stopdetailid, "stop_id" => $stop_id, "trip_id" => $trip_id, "status" => 1 ), 1, 0 );
                                if ( $chqry1->num_rows() == 0 ) {
                                    $insarr = array( "employee_id" => $stopdetailid, "stop_id" => $stop_id, "trip_id" => $trip_id, "status" => 1, 'driver_late' => 0, 'emp_late' => 0, 'stime' => $curdt, 'check_in' => $curdt, 'absent_reason' => 'Closed', 'created_on' => $curdt, 'updated_on' => $curdt, 'pd_status' => 1 );
                                    $ins    = $this->db->insert( "tb_trip_employee", $insarr );
                                }

                                $postdata = array(
                                    "shipment_id" => $shift_id,
                                    "trip_id"     => $trip_id,
                                    "driver_id"   => $driver_id,
                                    "stop_id"     => $stop_id,
                                    "order_id"    => $booking_id,
                                    "inc_id"      => 0,
                                    "pod_type"    => '',
                                    "latitude"    => $lattitude,
                                    "longitude"   => $longitude,
                                    "stop_type"   => $stop_type,
                                    "vehicle_id"  => $vehicle_id,
                                    "curtz"       => $curtz,
                                    "hrs"         => $hrs,
                                    "web"         => '',
                                    "status_code" => $status_code,
                                    "ord_id"      => $order_id,
                                    "user_id"     => $user_id,
                                );
                                if ( $createdsource == "18" ) {
                                    $companyCode = $this->session->userdata( 'company_code' );
                                    $branchCode = $this->session->userdata( 'branch_code' );
                                    $userId = $this->session->userdata( 'user_id' );
                                    $edi_reference = $this->shippeostatusintigration->is_shippeo_order($ord_id, $companyCode, $branchCode);
                                    if ($edi_reference != 0) {
                                        $sts = $this->shippeostatusintigration->shippeo_event_call($ord_id, $postdata, $curtz, $status_id, $stop_type, $vehicle_id, $edi_reference, $companyCode, $branchCode, $userId);
                                    }
                                    if ( $status_id == "4" ) {
                                        /*$sts = $this->statusintigration->shipmentintransit($postdata);*/
                                        /*send to roadlog*/
                                        $sts = $this->statusintigration->roadlogshipmentintransit( $postdata );
                                    }
                                    if ( $status_id == "2" && $stop_type == "P" ) {
                                        /*$sts = $this->statusintigration->shipmentorderpicked($postdata);*/
                                        $sts = $this->statusintigration->roadlogshipmentpgatein( $postdata );
                                    }
                                    if ( $status_id == "1" && $stop_type == "P" ) {
                                        /*$sts = $this->statusintigration->shipmentorderpicked($postdata);*/
                                        $sts = $this->statusintigration->roadlogshipmentpicked( $postdata );
                                    }
                                    if ( $status_id == "3" && $stop_type == "P" ) {
                                        /*send to roadlog*/
                                        $sts = $this->statusintigration->roadlogshipmentpgateout( $postdata );
                                    }
                                    if ( $status_id == "2" && $stop_type == "D" ) {
                                        /*$sts = $this->statusintigration->shipmentorderpicked($postdata);*/
                                        $sts = $this->statusintigration->roadlogshipmentdgatein( $postdata );
                                    }
                                    if ( $status_id == "1" && $stop_type == "D" ) {
                                        /*$sts = $this->statusintigration->shipmentdelivered($postdata);*/
                                        /*send to roadlog*/
                                        $sts = $this->statusintigration->roadlogshipmentdelivered( $postdata );
                                    }
                                } else if ( $createdsource == "13" ) {
                                    $this->load->library( "amazonstatusintegration" );
                                    if ( $status_id == "2" && $stop_type == "P" ) {
                                        /*$sts = $this->statusintigration->shipmentorderpicked($postdata);*/
                                        $sts = $this->amazonstatusintegration->updateOrderStatus( $postdata );
                                    }
                                    if ( $status_id == "1" && $stop_type == "P" ) {
                                        /*$sts = $this->statusintigration->shipmentorderpicked($postdata);*/
                                        $sts = $this->amazonstatusintegration->updateOrderStatus( $postdata );
                                    }
                                    if ( $status_id == "3" && $stop_type == "P" ) {
                                        /*send to roadlog*/
                                        $sts = $this->amazonstatusintegration->updateOrderStatus( $postdata );
                                    }
                                    if ( $status_id == "2" && $stop_type == "D" ) {
                                        /*$sts = $this->statusintigration->shipmentorderpicked($postdata);*/
                                        $sts = $this->amazonstatusintegration->updateOrderStatus( $postdata );
                                    }
                                    if ( $status_id == "1" && $stop_type == "D" ) {
                                        /*$sts = $this->statusintigration->shipmentdelivered($postdata);*/
                                        /*send to roadlog*/
                                        $sts = $this->amazonstatusintegration->updateOrderStatus( $postdata );
                                    }
                                    if ( $status_id == "3" && $stop_type == "D" ) {
                                        /*send to roadlog*/
                                        $sts = $this->amazonstatusintegration->updateOrderStatus( $postdata );
                                    }
                                } else if ( $createdsource == '9' ) {
                                    if ( $status_id == '4' || ( $status_id == "1" && $stop_type == "P" ) || ( $status_id == "3" && $stop_type == "D" ) ) {
                                        $postdata['status_code'] = "";
                                        if ( $status_id == '4' ) {
                                            $postdata['status_code'] = '1550';
                                        }
                                        if ( $status_id == '1' && $stop_type == 'P' ) {
                                            $postdata['status_code'] = '0500';
                                        }
                                        if ( $status_id == '3' && $stop_type == 'D' ) {
                                            $postdata['status_code'] = '3000';
                                        }
                                        $sts = $this->etrucknowquote->getstatusresponse( $postdata );
                                    }
                                } else if ( $createdsource == '5' ) {
                                    $postdata['status_code'] = $postdata['ord_id'] = "";
                                    $postdata['status_code'] = $status_code;
                                    if ( $status_id == '1' && $stop_type == 'P' ) {
                                        $postdata['status_code'] = '0500';
                                    }
                                    if ( $status_id == '3' && $stop_type == 'D' ) {
                                        $postdata['status_code'] = '3000';
                                    }
                                    if ( $status_id == '1' && $stop_type == 'D' ) {
                                        $postdata['status_code'] = '2300';
                                    }
                                    if (in_array($postdata['status_code'], ['2300', '3000', '0500'])) {
                                        $postdata['ord_id'] = $ord_id;
                                        $sts                = $this->statusintigration->salogshipmentstatus( $postdata );
                                    }
                                } elseif ($createdsource == "11") {
                                    if ($postdata['status_code'] == "3000") {
                                        $this->statusintigration->sendPodToKnlogin(3, $ord_id);
                                    }
                                }
                            }
                        }
                        echo "1";
                    }
                    $companyCode = $this->session->userdata('company_code');
                    $checkStatus = "RELATED_2_" . $companyCode . "_CONSIGNEE_NOTIFICATION_STATUSES";
                    if (checkAccessConditions('RELATED_2_CONSIGNEE_NOTIFICATION', $companyCode) && checkAccessConditions($checkStatus, $postdata['status_code'])) {
                        $this->load->library('notifytrigger');
                        $this->notifytrigger->sendNotificationToConsignee($order_id, $postdata['status_code']);
                    }

                } else {
                    $this->db->where( array( 'id' => $id ) )->update( "tb_stop_status", array( 'createdon' => $status_date ) );
                    echo "1";
                }
            }

                try {
                    $statusPayload = [
                        "trip" => $trip_id,
                        "ship" => $shift_id,
                        "ord_id" => $order_id,
                        "orderid" => $booking_id,
                        "stop_id" => 0,
                        "stop_detail_id" => 0,
                        "vehicle_id" => $vehicle_id ?? 0,
                        "driver_id" => $driver_id ?? 0,
                        "stop_type" => "P",
                        "timezone" => $this->session->userdata("timezone"),
                        "sts_date" => $status_date,
                        "status_code" => $status_code
                    ];
                    $this->standard_status_execution->sendStandardXMLtoAltova($statusPayload);
                } catch (Exception $ex) {
                    log_message("error", "Some Problem occured!, While Sending Order Status to Altova " . $ex->getMessage());
                }

            if(checkAccessConditions('WECHAT_COUNTRY', $this->session->userdata('company_code')) && $status_code === '0212')
            {
                $this->load->library('Wechat');
                $this->wechat->orderId = $booking_id;
                $this->wechat->sendNotificationsToWeChat();
            }
        }
    }


    public function vieworder( $id = NULL ) {
        $this->codeigniterauthorization->isAuthorized(
            $this->session->userdata,
            Authorization::ENTITY_TYPE_ORDER,
            $id
        );
        if ($this->session->userdata('user_role_id') == 5) {
            redirect('knopsorders');
        }
        if (checkAccessConditions('RELATED_2_SG_MY', $this->session->userdata('company_code'))) {
            redirect('smtcorders');
        }
        /*if (!checkUrlAccessForUser('ORDERS')) {
            redirect("Forbiddenaccess");
        }*/
        $company_code = $this->session->userdata( 'company_code' );
        $data          = array();
        $order_details = $shipper_details = $drop_details = $pickup_details = array();
        
        $data['currency'] = $this->session->userdata("usr_tzone")['currency'];
        
        if ( $id != "" ) {
            $chkorder = $this->Order->getordertoedit( $id );
            if ( $chkorder->num_rows() > 0 ) {
                $transport      = $chkorder->row()->transport_mode;
                $transport_mode = "";
                if ( $transport != "" ) {

                    $getmode = $this->db->select( "name" )->get_where( "tb_transportmode", array( 'code' => $transport ) );
                    if ( $getmode->num_rows() > 0 ) {
                        $transport_mode = $getmode->row()->name;
                    }
                }
                $docs_received_datetime = $chkorder->row()->docs_received_datetime;
                $docs_sent_datetime     = $chkorder->row()->docs_sent_datetime;
                $shipment_id            = $pickup_inst = $delivery_inst = $container_no = $purchase_order = "";
                $getdnote               = $this->db->query( "SELECT reference_id,ref_value FROM tb_order_references WHERE order_id ='" . $id . "' AND reference_id IN ('DQ','PO','ORD_DLVINST','ORD_PIKINST','CTR')" );
                if ( $getdnote->num_rows() > 0 ) {
                    foreach ( $getdnote->result() as $ref ) {
                        $ref_id = $ref->reference_id;
                        if ( $ref_id == 'DQ' ) {
                            $shipment_id = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_DLVINST' ) {
                            $delivery_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'ORD_PIKINST' ) {
                            $pickup_inst = $ref->ref_value;
                        }
                        if ( $ref_id == 'CTR' ) {
                            $container_no = $ref->ref_value;
                        }
                        if ( $ref_id == 'PO' ) {
                            $purchase_order = $ref->ref_value;
                        }

                    }
                }
                $pickup_custid = $chkorder->row()->pickup_custid;
                $trip_id       = $chkorder->row()->trip_id;
                $trip_sts      = $chkorder->row()->trip_sts;
                $order_status  = "PENDING";
                if ( $trip_id != 0 && $trip_sts == 0 ) {
                    $order_status = 'ACTIVE';
                }
                if ( $trip_id != 0 && $trip_sts == 1 ) {
                    $order_status = 'CLOSED';
                }
                $chkdate      = '2020-07-01 00:00:00';
                $createdon    = $chkorder->row()->createdon;
                $order_str    = strtotime( $createdon );
                $chk_str      = strtotime( $chkdate );
                $early_pickup = $chkorder->row()->pickup_datetime;

                $early_delivery = $chkorder->row()->delivery_datetime;
                $late_pickup    = $chkorder->row()->pickup_endtime;
                $late_delivery  = $chkorder->row()->drop_endtime;
                $curtz          = $this->session->userdata( "usr_tzone" )['timezone'];
                if ( $order_str > $chk_str ) {
                    if ( $early_pickup != "" && $early_pickup != "0000-00-00 00:00:00" ) {
                        $epickup      = getdatetimebytimezone( $curtz, $early_pickup, DFLT_TZ );
                        $early_pickup = $epickup['datetime'];
                    }
                    if ( $early_delivery != "" && $early_delivery != "0000-00-00 00:00:00" ) {
                        $edelivery      = getdatetimebytimezone( $curtz, $early_delivery, DFLT_TZ );
                        $early_delivery = $edelivery['datetime'];
                    }
                    if ( $late_pickup != "" && $late_pickup != "0000-00-00 00:00:00" ) {
                        $lpickup     = getdatetimebytimezone( $curtz, $late_pickup, DFLT_TZ );
                        $late_pickup = $lpickup['datetime'];
                    }
                    if ( $late_delivery != "" && $late_delivery != "0000-00-00 00:00:00" ) {
                        $ldelivery     = getdatetimebytimezone( $curtz, $late_delivery, DFLT_TZ );
                        $late_delivery = $ldelivery['datetime'];
                    }

                }
                if ( $docs_sent_datetime != "" && $docs_sent_datetime != "0000-00-00 00:00:00" ) {
                    $docsent            = getdatetimebytimezone( $curtz, $docs_sent_datetime, DFLT_TZ );
                    $docs_sent_datetime = $docsent['datetime'];
                }
                if ( $docs_received_datetime != "" && $docs_received_datetime != "0000-00-00 00:00:00" ) {
                    $docrec                 = getdatetimebytimezone( $curtz, $docs_received_datetime, DFLT_TZ );
                    $docs_received_datetime = $docrec['datetime'];
                }
                $order_details = array(
                    'id' => $chkorder->row()->id,
                    'order_id' => $chkorder->row()->order_id,
                    'shipment_id' => $shipment_id,
                    'order_status' => $order_status,
                    'early_pickup' => $early_pickup,
                    'early_delivery' => $early_delivery,
                    'late_pickup' => $late_pickup,
                    'late_delivery' => $late_delivery,
                    'product' => $chkorder->row()->product,
                    'incoterm' => $chkorder->row()->incoterm,
                    'delivery_note' => $chkorder->row()->delivery_note,
                    'purchase_order' => $purchase_order,
                    'notify_party' => $chkorder->row()->notify_party,
                    'goods_value' => $chkorder->row()->goods_value,
                    'currency' => $chkorder->row()->currency,
                    'lane_reference' => $chkorder->row()->lane_reference,
                    'distance' => $chkorder->row()->distance,
                    'customs_required' => $chkorder->row()->customs_required,
                    'high_cargo_value' => $chkorder->row()->high_cargo_value,
                    'valorance_insurance' => $chkorder->row()->valorance_insurance,
                    'temperature_control' => $chkorder->row()->temperature_control,
                    'company_code' => $chkorder->row()->company_code,
                    'branch_code' => $chkorder->row()->branch_code,
                    'department_code' => $chkorder->row()->department_code,
                    'createdon' => $chkorder->row()->createdon,
                    'transport_mode' => $transport_mode,
                    'pickup_inst' => $pickup_inst,
                    'delivery_inst' => $delivery_inst,
                    'container_no' => $container_no,
                    'docs_received_datetime' => $docs_received_datetime,
                    'docs_sent_datetime' => $docs_sent_datetime,
                    'external_order_id' => $chkorder->row()->external_order_id
                );
                $delivery_term = "";
                $pickup_id = $chkorder->row()->customer_id;
                $ord_type = $chkorder->row()->order_type;
                $cost_center_id = $chkorder->row()->cost_center_id;
                $order_details['order_type'] = "";
                $order_details['cost_center'] = "";
                //$getordertype = $this->db->select( "type_name" )->get_where( "tb_order_types", array( 'id' => $ord_type, 'status' => '1', 'company_code' => $chkorder->row()->company_code ) );
                $getordertype = $this->db->select("type_name")->get_where("tb_order_types", ['id' => $ord_type, 'status' => '1', 'company_code' => $chkorder->row()->company_code]);
                if ( $getordertype->num_rows() > 0 ) {
                    $order_details['order_type'] = $getordertype->row()->type_name;
                }
                /*  cost center*/
                //$getCostCenter = $this->db->select( "type_name" )->get_where( "tb_cost_center", array( 'id' => $cost_center_id, 'status' => '1', 'company_code' => $chkorder->row()->company_code ) );
                $getCostCenter = $this->db->select("type_name")->get_where("tb_cost_center", ['id' => $cost_center_id, 'status' => '1', 'company_code' => $chkorder->row()->company_code]);
                if ( $getCostCenter->num_rows() > 0 ) {
                    $order_details['cost_center'] = $getordertype->row()->type_name;
                }
                $delivery_term_id = $chkorder->row()->delivery_term;
                if ( $delivery_term_id != "" ) {
                    //$getdelivery_term = $this->db->select( "term_id,name" )->get_where( "tb_delivery_terms", array( 'term_id' => $delivery_term_id ) );
                    $getdelivery_term = $this->db->select("term_id,name")->get_where("tb_delivery_terms", ['term_id' => $delivery_term_id]);
                    if ( $getdelivery_term->num_rows() > 0 ) {
                        $delivery_term = $getdelivery_term->row()->term_id . "-" . $getdelivery_term->row()->name;
                    }
                }
                $service    = "";
                $service_id = $chkorder->row()->service;
                if ( $service_id != "" ) {
                    $getservice = $this->db->select( "service_id,name" )->get_where( "tb_service_master", array( 'id' => $service_id ) );
                    if ( $getservice->num_rows() > 0 ) {
                        $service = $getservice->row()->service_id . "-" . $getservice->row()->name;
                    }
                }
                $order_details['service']       = $service;
                $order_details['delivery_term'] = $delivery_term;
                $getpickupdetails = $this->db->select( "id,name,address,pincode,code,country" )->get_where( "tb_customers", array( 'status' => 1, 'id' => $pickup_id ) );
                if ( $getpickupdetails->num_rows() > 0 ) {
                    $pickup_details = array( 'id' => $getpickupdetails->row()->id, 'name' => $getpickupdetails->row()->name, 'party_id' => $getpickupdetails->row()->code, 'address' => $getpickupdetails->row()->address, 'pincode' => $getpickupdetails->row()->pincode, 'country' => $getpickupdetails->row()->country );
                }
                $drop_id     = $chkorder->row()->drop_custid;
                $drop_row_id = 0;


                $chekparty   = $this->db->query( "SELECT p.id,p.party_type_id, p.name,
                        p.mobile, p.email,p.code,p.fax,p.house_number,o.party_type ,aucp.id AS aucp_id, acm.id AS acm_id,
                        aucp.email AS aucp_email,acm.phoneNum AS acm_phone
                        FROM tbl_party_master p
                        INNER JOIN tb_order_parties o ON p.id=o.party_id AND o.status=1
                        INNER JOIN tb_order_references AS orf ON
                        (o.order_id = orf.order_id AND o.order_id = ? )
                        LEFT JOIN tb_au_carrier_postalcodes AS aucp ON aucp.site = orf.ref_value
                        LEFT JOIN tb_au_label_consignee_mobile_num AS acm ON acm.storeCode = orf.ref_value
                        WHERE p.status=1 AND o.order_id= ? GROUP BY o.party_type " ,[$id,$id]);

                if ( $chekparty->num_rows() > 0 ) {
                    foreach ( $chekparty->result() as $rr ) {
                        $ptype   = $rr->party_type;
                        $chktype = $this->db->select( "name" )->get_where( "tbl_party_types", array( "id" => $ptype ), 1, 0 );
                        if ( $chktype->num_rows() > 0 ) {
                            if ( $chktype->row()->name == "Consignee" ) {
                                $drop_details = array( 'name' => $rr->name, 'phone' => $rr->mobile,
                                 'email' => $rr->email, 'fax' => $rr->fax,'houseNo' => $rr->house_number, 'party_id' => $rr->code ,
                                 'aucp_email'=>$rr->aucp_email,'acm_phone'=>$rr->acm_phone);
                            } else if ( $chktype->row()->name == "Shipper" ) {
                                $shipper_details = array( 'name' => $rr->name, 'phone' => $rr->mobile,
                                 'email' => $rr->email, 'fax' => $rr->fax,'houseNo' => $rr->house_number, 'party_id' => $rr->code,
                                 'aucp_email'=>$rr->aucp_email,'acm_phone'=>$rr->acm_phone
                                 );
                            }
                        }
                    }
                }
                $shipper_details['name']    = $chkorder->row()->pickup;
                $shipper_details['street']  = $chkorder->row()->pickup_address1;
                $shipper_details['state']   = $chkorder->row()->pickup_address2;
                $shipper_details['city']    = $chkorder->row()->pickup_city;
                $shipper_details['country'] = $chkorder->row()->pickup_country;
                $shipper_details['pincode'] = $chkorder->row()->pickup_pincode;
                $drop_details['name']    = $chkorder->row()->delivery;
                $drop_details['street']  = $chkorder->row()->delivery_address1;
                $drop_details['state']   = $chkorder->row()->delivery_address2;
                $drop_details['city']    = $chkorder->row()->delivery_city;
                $drop_details['country'] = $chkorder->row()->delivery_country;
                $drop_details['pincode'] = $chkorder->row()->delivery_pincode;
                $drop_id                 = $chkorder->row()->drop_custid;
            }
        }
        $data['vatcategory'] = array();
        $getvatcategory = $this->common->gettbldata(array('company_code'=>$company_code,'status' => '1'),"id,description,vat_category,vat_percentage","tb_vat_category",0,0);
        if (!empty($getvatcategory)) {
            foreach ($getvatcategory as $res) {
                $val = $res['id']."_".$res['vat_category'];
                $desc = $res['description']." (".$res['vat_category']."-".$res['vat_percentage'].")";
                $data['vatcategory'][] = array('id' => $res['id'],'val'=>$val, 'desc'=>$desc);
            }
        }
        $data['spotondata'] = array();
        $data['spoton_lr_exist']=0;
        $getspotondata = $this->common->gettbldata(array('order_id'=>$id,'reference_id' => 'BN'),"ref_value,updatedon","tb_order_references",0,0);
        if (!empty($getspotondata)) {
            $data['spotondata']=$getspotondata;
            $data['spoton_lr_exist']=1;
        }
        $data['order_details']   = $order_details;
        $data['pickup_details']  = $pickup_details;
        $data['drop_details']    = $drop_details;
        $data['shipper_details'] = $shipper_details;
        
        $data['business_type'] = $this->session->userdata('business_type');
        
        $data['marks_numbers_column'] = checkAccessConditions('MARKS_AND_NUMBERS_OPTION', $company_code);  
        /*$getOuterCargo = $this->db->query("SELECT c.cargo_type, oc.cargo_id, oc.quantity, oc.weight, oc.volume, c.* 
        FROM tb_order_cargodetails oc
        INNER JOIN tb_cargo_details c ON c.id = oc.cargo_id
        WHERE oc.status = ? AND oc.order_id = ?", [1, $id]);
        if ( $getOuterCargo->num_rows() > 0) {
        $data['outercargo'] =  $getOuterCargo->result();
        }*/
        $getOuterCargo = $this->db->query("SELECT c.cargo_type, oc.cargo_id, oc.quantity, oc.weight, oc.volume, c.goods_description, c.marks_numbers,c.item_id,c.length,c.length_unit,c.width,c.width_unit,c.height,c.height_unit,c.weight,c.weight_unit,c.second_weight,c.volumetric_weight,c.secondweight_uom,c.volweight_uom,
        c.volume_unit,c.second_volume,c.secondvolume_uom,c.ldm,c.stackable,c.grounded,c.dg_goods,c.splittable,oc.scanned_quantity 
        FROM tb_order_cargodetails oc
        INNER JOIN tb_cargo_details c ON c.id = oc.cargo_id
        WHERE oc.status = ? AND oc.order_id = ?", [1, $id]);
        if ( $getOuterCargo->num_rows() > 0) {
        $data['outercargo'] =  $getOuterCargo->result();
        }
        $this->load->view('orders/vieworder', $data);
    }

    public function getshipperID() {
        $parties      = array();
        $partytype_id = $this->input->post( 'partytype_id' );
 
        $user_id      = $this->session->userdata( 'user_id' );
        $company_code = $this->session->userdata( 'company_code' );
        $permission = checkuserpermissions();
        $whr = "";
        if (in_array("businesspartners", $permission)) {
            $whr = "AND company_code LIKE '" . $company_code . "' ";
        } else {
            $whr = " AND user_id ='" . $user_id . "' ";
        }
       
        $where = "status = 1 AND code != '' AND company_code != '' AND company_code IS NOT NULL AND code is NOT NULL AND code != '0' " . $whr . " AND code LIKE '%" . $partytype_id . "%'";
        $this->db->select( "id,name,phone,code,email_id,company_code,branch_code" );
        $this->db->from( "tb_customers" );
        $this->db->where( $where );
        $this->db->group_by( 'id' );
        $this->db->order_by( 'createdon', 'DESC' );
        $chkqry = $this->db->get();

        if ( $chkqry->num_rows() > 0 ) {
            foreach ( $chkqry->result() as $res ) {
                $parties[] = array( 'id' => $res->id, 'party_id' => $res->code, 'name' => $res->name, 'phone' => $res->phone, 'email' => $res->email_id, 'company_code' => $res->company_code, 'branch_code' => $res->branch_code );
            }
        }
        if ( $company_code != "" ) {
            $getorder_types = $this->db->select( "id,type_name" )->get_where( "tb_order_types", array( 'company_code' => $company_code, 'status' => '1' ) );
            if ( $getorder_types->num_rows() > 0 ) {
                foreach ( $getorder_types->result() as $res ) {
                    $parties['ordparties'][] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                }
            }
        }
        echo json_encode( $parties );
    }

    public function getvendordetailsbyID() {
        $list = array();
        $code = $this->input->post( 'id' );
        if ( $code != "" ) {
            $getvendordetails = $this->db->query( "SELECT name,code FROM tb_vendors WHERE code LIKE '" . $code . "' AND status ='1'" );

            if ( $getvendordetails->num_rows() > 0 ) {
                $list = array( 'name' => $getvendordetails->row()->name, 'code' => $getvendordetails->row()->code );
            }
        }
        echo json_encode( $list );
    }

    public function getshipperdetailsbyID() {
        $parties      = array();
        $code         = $this->input->post( 'id' );
        $customer_id  = "";
        $user_id      = $this->session->userdata( 'user_id' );
        $company_code = $this->session->userdata( 'company_code' );
        
        $permission = checkuserpermissions();
        if (in_array("businesspartners", $permission)) {
            $chk_customers = $this->common->gettblrowdata(array( 'id' => $code, 'company_code' => $company_code, 'status' => '1' ), "id,name,phone,location,address,street,location,state,pincode,code,country,email_id,fax,company_code,branch_code", "tb_customers", 0, 0);
        } else {
            $chk_customers = $this->common->gettblrowdata(array( 'id' => $code, 'user_id' => $user_id, 'status' => '1' ), "id,name,phone,location,address,street,location,state,pincode,code,country,email_id,fax,company_code,branch_code", "tb_customers", 0, 0);
        }

        if ( !empty($chk_customers) ) {
            $customer_id                   = $chk_customers['id'];
            $parties['customer_details'][] = array(
                'id'           => $chk_customers['id'],
                'name'         => $chk_customers['name'],
                'phone'        => $chk_customers['phone'],
                'street'       => $chk_customers['street'],
                'city'         => $chk_customers['location'],
                'pincode'      => $chk_customers['pincode'],
                'code'         => $chk_customers['code'],
                'country'      => $chk_customers['country'],
                'email_id'     => $chk_customers['email_id'],
                'fax'          => $chk_customers['fax'],
                'state'        => $chk_customers['state'],
                'location'     => $chk_customers['location'],
                'address'      => $chk_customers['address'],
                'company_code' => $chk_customers['company_code'],
                'branch_code'  => $chk_customers['branch_code']
            );
        }
        
        $parties['ordparties'] = array();
        if ( $customer_id != "" ) {
            $getorder_types = $this->db->select( "id,type_name" )->group_by( 'type_name' )->get_where( "tb_order_types", array( 'customer_id' => $customer_id, 'status' => '1', 'company_code' => $company_code ) );
            if ( $getorder_types->num_rows() > 0 ) {
                foreach ( $getorder_types->result() as $res ) {
                    $parties['ordparties'][] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                }
            } else {
                $getorders = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_order_types", array( 'company_code' => $company_code, "status" => 1 ) );
                if ( $getorders->num_rows() > 0 ) {
                    foreach ( $getorders->result() as $res ) {
                        $parties['ordparties'][] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                    }
                } else {
                    $getorders = $this->db->select( "id,type_name" )->group_by( "type_name" )->get_where( "tb_order_types", array( 'company_code' => "SGKN", "status" => 1 ) );
                    if ( $getorders->num_rows() > 0 ) {
                        foreach ( $getorders->result() as $res ) {
                            $parties['ordparties'][] = array( 'type_id' => $res->id, 'type_name' => $res->type_name );
                        }
                    }
                }
            }
        }

        echo json_encode( $parties );
    }

    public function saveshipper() {
        $post          = $this->input->post();
        $master_id     = "";
        $user_id       = $this->session->userdata( 'user_id' );
        $cust_id       = isset( $post['shipper_row_id'] ) ? $post['shipper_row_id'] : "";
        $customer_code = isset( $post['scustomer_code'] ) ? $post['scustomer_code'] : "";
        $order_id      = isset( $post['shipper_orderrow_id'] ) ? $post['shipper_orderrow_id'] : "";
        $company_code  = isset( $post['shipper_company_code'] ) ? $post['shipper_company_code'] : "";
        $branch_code   = isset( $post['shipper_branch_code'] ) ? $post['shipper_branch_code'] : "";
        $pickup_instructions = !empty( $post['shipper_pickup_instructions'] )
            ? json_encode(['pickup_instructions' => $post['shipper_pickup_instructions']]) : null;
        $cdate         = date( 'Y-m-d H:i:s' );
        $status        = '1';
        $address       = $post['shipper_street'] . ',' . $post['shipper_city'] . ',' . $post['shipper_state'];
        if ( $company_code == "" ) {
            $company_code = $this->session->userdata( 'company_code' );
        }
        if ( $branch_code == "" ) {
            $branch_code = $this->session->userdata( 'branch_code' );
        }
        $partyCompanyCondition = checkAccessConditions('CHECK_BUSINESS_PARTY_TYPES', $company_code);
        $master_id = 0;
        $chktype   = $this->db->select( "id" )->order_by( 'created_on', 'DESC' )->get_where( "tbl_party_types", array( 'name' => 'Shipper', 'user_id' => $user_id ) );
        if ( $chktype->num_rows() > 0 ) {
            $party_id = $chktype->row()->id;
        } else {
            $party    = array( 'name' => 'Shipper', 'description' => 'Shipper', 'company_code' => $company_code, 'branch_code' => $branch_code, 'created_on' => $cdate, 'user_id' => $user_id );
            $ins      = $this->db->insert( "tbl_party_types", $party );
            $party_id = $this->db->insert_id();
        }
        $code = $post['shipper_id'];
        if ( $code == "" ) {
            $code = 0;
        }
        $master = array(
            'party_type_id'      => $party_id,
            'name'               => $post['shipper_name'],
            'email'              => $post['shipper_email'],
            'street'             => $post['shipper_street'],
            'state'              => $post['shipper_state'],
            'mobile'             => $post['shipper_phone'],
            'pincode'            => $post['shipper_zipcode'],
            'country'            => $post['shipper_country'],
            'user_id'            => $user_id,
            'code'               => $code,
            'customeridentifier' => $code,
            'company_code'       => $company_code,
            'branch_code'        => $branch_code,
            'status'             => '1',
            'fax'                => $post['shipper_fax'],
            'address'            => $address,
            'location_id'        => $post['shipper_city'],
            'additional_info'    => $pickup_instructions,
        );
        if ( $code != '0' ) {
            $shipper_id = $code;
            $chkmaster  = $this->db->select( 'id,customer_code' )->get_where( "tbl_party_master", array( 'code' => $post['shipper_id'],'status' => 1 ) );
            if ( $chkmaster->num_rows() > 0 ) {
                $master_id             = $chkmaster->row()->id;
                $shipper_customer_code = $chkmaster->row()->customer_code;
                if ( $order_id != "" ) {
                    if ( $shipper_customer_code == "" || $shipper_customer_code == '0' ) {
                        $upd = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", array( 'mobile' => $post['shipper_phone'], 'email' => $post['shipper_email'], 'fax' => $post['shipper_fax'], 'customer_code' => $customer_code ) );
                    } else {
                        $upd = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", array( 'mobile' => $post['shipper_phone'], 'email' => $post['shipper_email'], 'fax' => $post['shipper_fax'] ) );
                    }

                    $status = '1';
                } else {
                    if ( $shipper_customer_code == "" || $shipper_customer_code == '0' ) {
                        $master['customer_code'] = $customer_code;
                    }
                    $upd    = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", $master );
                    $status = '1';
                }

            } else {
                $conisgnee_id = "";
                $chktype      = $this->db->select( "id" )->order_by( 'created_on', 'DESC' )->get_where( "tbl_party_types", array( 'name' => 'Consignee', 'company_code' => $company_code ) );
                if ( $chktype->num_rows() > 0 ) {
                    $conisgnee_id = $chktype->row()->id;
                }
                if ($partyCompanyCondition) {
                    $master['party_types'] = $party_id;
                } else {
                    $master['party_types'] = $conisgnee_id;
                }

                $master['created_on']    = $cdate;
                $master['customer_code'] = $customer_code;
                $ins                     = $this->db->insert( "tbl_party_master", $master );
                $master_id               = $this->db->insert_id();
                $status                  = '0';
            }
        } else {
            $conisgnee_id = "";
            $chktype      = $this->db->select( "id" )->order_by( 'created_on', 'DESC' )->get_where( "tbl_party_types", array( 'name' => 'Consignee', 'user_id' => $user_id ) );
            if ( $chktype->num_rows() > 0 ) {
                $conisgnee_id = $chktype->row()->id;
            }
            if ($partyCompanyCondition) {
                $master['party_types'] = $party_id;
            } else {
                $master['party_types'] = $conisgnee_id;
            }
            $master['created_on']    = $cdate;
            $master['customer_code'] = $customer_code;
            $ins                     = $this->db->insert( "tbl_party_master", $master );
            $master_id               = $this->db->insert_id();
            $country_code            = $this->session->userdata( "usr_tzone" )['phone_code'];
            $year                    = date( 'y' );
            $week                    = date( 'W' );
            $shipper_id              = $country_code . $year . $week . $master_id;
            $upd                     = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", array( 'code' => $shipper_id, 'customeridentifier' => $shipper_id ) );
            $status                  = '0';
        }
        if ( $order_id != "" ) {
            if ( $master_id != '0' ) {
                $chk_address = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $master_id, 'status' => '1' ) );
                if ( $chk_address->num_rows() > 0 ) {
                    $address_id = $chk_address->row()->id;
                    $upd_ar     = array( 'order_id' => $order_id, 'party_master_id' => $master_id, 'location_id' => $post['shipper_city'], 'street' => $post['shipper_street'], 'state' => $post['shipper_state'], 'address' => $address, 'pincode' => $post['shipper_zipcode'], 'country' => $post['shipper_country'], 'user_id' => $user_id );
                    $updaddress = $this->db->where( array( 'id' => $address_id ) )->update( "tbl_orderparty_address", $upd_ar );
                } else {
                    $insadd_ar  = array(
                        'order_id'        => $order_id,
                        'party_master_id' => $master_id,
                        'location_id'     => $post['shipper_city'],
                        'street'          => $post['shipper_street'],
                        'state'           => $post['shipper_state'],
                        'address'         => $address,
                        'pincode'         => $post['shipper_zipcode'],
                        'country'         => $post['shipper_country'],
                        'user_id'         => $user_id,
                        'status'          => '1',
                        'createdon'       => $cdate
                    );
                    $updaddress = $this->db->insert( "tbl_orderparty_address", $insadd_ar );
                }
            }
            $order_whr = array('id'=>$order_id);
            $order_upd = array();

            if($post['shipper_name'] != ""){
                $order_upd['pickup_company'] = $post['shipper_name'];
            }
            if($post['shipper_country'] != ""){
                $order_upd['pickup_country'] = $post['shipper_country'];
            }
            if($post['shipper_city'] != ""){
                $order_upd['pickup_city'] = $post['shipper_city'];
            }
            if($post['shipper_zipcode'] != ""){
                $order_upd['pickup_pincode'] = $post['shipper_zipcode'];
            }
            if($post['shipper_state'] != ""){
                $order_upd['pickup_address2'] = $post['shipper_state'];
            }
            if($post['shipper_street'] != ""){
                $order_upd['pickup_address1'] = $post['shipper_street'];
            }
            if(!empty($order_upd)){
                $upd_ordertbl = $this->common->updatetbledata("tb_orders",$order_upd,$order_whr);
            }
            $status = '1';
        }
        $arr = array( 'master_id' => $master_id, 'status' => $status, 'shipper_id' => $shipper_id );
        echo json_encode( $arr );
    }

    public function getconsigneeID() {

        $user_id        = 1;
        $parties        = array();
        $code           = $this->input->post( 'partytype_id' );
        $user_id        = $this->session->userdata( 'user_id' );
        $custid         = "0";
        $party_type     = isset( $_POST['type'] ) ? $_POST['type'] : "";
        $whr            = "";
        $chkcompanycode = $this->session->userdata( 'company_code' );
        $company_code   = $this->session->userdata( 'company_code' );
        $permission = checkuserpermissions();
        if ( $chkcompanycode != 'NZKN' ) {
            if ( $this->session->userdata( 'cust_id' ) !== FALSE ) {
                $custid = $this->session->userdata( 'cust_id' );
            }
            $subcusts = array();
            if ( $custid != 0 ) {
                if ( $this->session->userdata( 'sub_cust' ) !== FALSE ) {
                    if(!empty($this->session->userdata('sub_cust'))){
                        $subcusts = $this->session->userdata('sub_cust');
                    }
                    /*if ( count( $subcusts ) > 0 ) {
						array_push( $subcusts, $custid );
					} else {
						$subcusts = $custid;
					}*/
                    if(!empty($subcusts) && sizeof($subcusts)>0){
                        array_push( $subcusts, $custid );
                    }else{
                        /*$subcusts = $custid;*/
                        array_push($subcusts, $custid);
                    }
                } else {
                    /*	$subcusts = $custid;*/
                    array_push($subcusts, $custid);
                }
            }
            $customer_code = array();
            if ( ! empty( $subcusts ) ) {
                $select          = "code";
                $table           = "tb_customers";
                $customerdetails = $this->Order->getcustomercodebyids( $select, $table, $subcusts );
                if ( ! empty( $customerdetails ) ) {
                    foreach ( $customerdetails as $cust ) {
                        $customer_code[] = $cust['code'];
                    }
                }
            }
            if ( ! empty( $customer_code ) ) {
                $whr = "AND m.customer_code IN ('" . implode( "','", $customer_code ) . "') ";
            }
        }
        $party_type_whr = "";
        if ( $party_type != "" ) {
            $party_type_whr = " AND p.name LIKE '" . $party_type . "' ";
        }
        $master_ids = array();
        if (in_array("businesspartners", $permission)) {
            $where = " ( m.code LIKE '%" . $code . "%' or m.name like '%" . $code . "%') AND m.company_code LIKE '" . $company_code . "' AND m.company_code != '' AND m.company_code IS NOT NULL AND m.branch_code != '' AND m.code IS NOT NULL AND m.code != '' AND m.code !='0' AND m.branch_code IS NOT NULL  AND m.status='1' " . $party_type_whr . " " . $whr;
        } else {
            $where = "m.code LIKE '%" . $code . "%' AND m.user_id='" . $user_id . "' AND m.company_code != '' AND m.company_code IS NOT NULL AND m.branch_code != '' AND m.code IS NOT NULL AND m.code != '' AND m.code !='0' AND m.branch_code IS NOT NULL  AND m.status='1' " . $party_type_whr . " " . $whr;
        }


        $this->db->select( "m.id,m.code,m.name" );
        $this->db->from( "tbl_party_master m" );
        $this->db->join( "tbl_party_types p", "p.id=m.party_type_id", "LEFT" );
        $this->db->where( $where );
        $this->db->where("m.status", '1');
        $this->db->group_by( 'm.id' );
        $this->db->order_by( 'm.id', 'DESC' );
        $this->db->limit(1);
        $chkqry = $this->db->get();
        if ( $chkqry->num_rows() > 0 ) {
            foreach ( $chkqry->result() as $res ) {
                $master_ids[] = $res->id;
                $parties[]    = array( 'id' => $res->id, 'party_id' => $res->code,'party_name' => $res->name );
            }
        }
        $additional_ids = array();
        if ( ! empty( $master_ids ) ) {
            $mwhr = "m.id NOT IN (" . implode( ',', $master_ids ) . ") AND ";
        } else {
            $mwhr = "";
        }
        if (in_array("businesspartners", $permission)) {
            /* if ( $company_code == "RUKN" ) { */
            $getmultipleparties = $this->db->query("SELECT m.id as master_id,m.party_types FROM tbl_party_master m WHERE " . $mwhr . " m.code LIKE '%" . $code . "%'  AND m.company_code LIKE '" . $company_code . "' AND m.party_types IS NOT NULL");
        } else {
            $getmultipleparties = $this->db->query("SELECT m.id as master_id,m.party_types FROM tbl_party_master m WHERE " . $mwhr . " m.code LIKE '%" . $code . "%'  AND m.user_id ='" . $user_id . "' AND m.party_types IS NOT NULL");
        }

        if ( $getmultipleparties->num_rows() > 0 ) {
            foreach ( $getmultipleparties->result() as $res ) {
                $party_types = explode( ',', $res->party_types );
                if ( ! empty( $party_types ) ) {
                    $chkshipper = $this->db->query( "SELECT id FROM tbl_party_types WHERE id IN (" . implode( ',', $party_types ) . ") AND name LIKE '" . $party_type . "'" );
                    if ( $chkshipper->num_rows() > 0 ) {
                        $additional_ids[] = $res->master_id;
                    }
                }
            }
        }
        if ( ! empty( $additional_ids ) ) {
            if (in_array("businesspartners", $permission)) {
                $get_addids = $this->db->query("SELECT m.id as master_id,m.code,m.name FROM tbl_party_master m WHERE m.id IN (" . implode(',', $additional_ids) . ") AND m.company_code != '' AND m.company_code IS NOT NULL AND m.branch_code != '' AND m.branch_code IS NOT NULL AND m.company_code LIKE '" . $company_code . "' AND m.parent_id ='0'  AND m.status=1 ANd m.code != '' AND m.code is NOT NULL AND m.code != '0' GROUP BY m.id ORDER BY m.id DESC");
            } else {
                $get_addids = $this->db->query("SELECT m.id as master_id,m.code,m.name FROM tbl_party_master m WHERE m.id IN (" . implode(',', $additional_ids) . ") AND m.company_code != '' AND m.company_code IS NOT NULL AND m.branch_code != '' AND m.branch_code IS NOT NULL AND m.user_id='" . $user_id . "' AND m.parent_id ='0'  AND m.status=1 ANd m.code != '' AND m.code is NOT NULL AND m.code != '0' GROUP BY m.id ORDER BY m.id DESC");
            }

            if ( $get_addids->num_rows() > 0 ) {
                foreach ( $get_addids->result() as $res ) {
                    $master_ids[] = $res->master_id;
                    $parties[]    = array( 'id' => $res->master_id, 'party_id' => $res->code, 'party_name'=> $res->name  );
                }
            }
        }

        echo json_encode( $parties );

    }

    public function getconsigneedetailsbyID() {
        $user_id      = 1;
        $parties      = array();
        $code         = $this->input->post( 'id' );
        $company_code = $this->session->userdata( 'company_code' );
        $user_id      = $this->session->userdata( 'user_id' );
        $where        = array();
        $permission = checkuserpermissions();
        if(in_array("businesspartners", $permission)){
            $where['company_code'] = $company_code;
        } else {
            $where['user_id'] = $user_id;
        }
        $this->db->select( "id,name,email,street,location_id as city,state,mobile,pincode,country,code,fax" );
        $this->db->from( "tbl_party_master" );
        $this->db->where( array( "code" => $code ) );
        $this->db->where(["code" => $code, "status" => 1]);
        if ( ! empty( $where ) ) {
            $this->db->where( $where );
        }
        $this->db->order_by( "id", "DESC" );
        $chkqry = $this->db->get();
        if ( $chkqry->num_rows() > 0 ) {
            $result = $chkqry->row();
            $parties[] = ['id'       => $result->id,
                'name'     => (string)$result->name,
                'phone'    => (string)$result->mobile,
                'street'   => (string)$result->street,
                'city'     => (string)$result->city,
                'pincode'  => (string)$result->pincode,
                'code'     => (string)$result->code,
                'country'  => (string)$result->country,
                'email_id' => (string)$result->email,
                'fax'      => (string)$result->fax,
                'state'    => (string)$result->state
            ];
        }
        echo json_encode( $parties );
    }

    public function saveconsignee() {
        $post                  = $this->input->post();
        $master_id             = "";
        $c_id                  = isset( $post['consignee_row_id'] ) ? $post['consignee_row_id'] : "";
        $customer_code         = isset( $post['ccustomer_code'] ) ? $post['ccustomer_code'] : "0";
        $order_id              = isset( $post['consignee_orderrow_id'] ) ? $post['consignee_orderrow_id'] : "";
        $company_code          = isset( $post['consignee_company_code'] ) ? $post['consignee_company_code'] : "";
        $branch_code           = isset( $post['consignee_branch_code'] ) ? $post['consignee_branch_code'] : "";
        $delivery_instructions = !empty( $post['consignee_delivery_instructions'] )
                                    ? json_encode(['delivery_instructions' => $post['consignee_delivery_instructions']]) : null;
        $user_id               = $this->session->userdata( 'user_id' );
        $cdate                 = date( 'Y-m-d H:i:s' );
        $status                = '1';

        if ( $company_code == "" ) {
            $company_code = $this->session->userdata( 'company_code' );
        }
        if ( $branch_code == "" ) {
            $branch_code = $this->session->userdata( 'branch_code' );
        }
        $partyCompanyCondition = checkAccessConditions('CHECK_BUSINESS_PARTY_TYPES', $company_code);
        $user_id = $this->session->userdata( 'user_id' );
        $chktype = $this->db->query( "SELECT id FROM tbl_party_types WHERE name='Consignee' AND company_code LIKE '" . $company_code . "' ORDER BY created_on DESC" );
        if ( $chktype->num_rows() > 0 ) {
            $party_id = $chktype->row()->id;
        } else {
            $party    = array( 'name' => 'Consignee', 'description' => 'Consignee', 'company_code' => $company_code, 'branch_code' => $branch_code, 'created_on' => $cdate, 'user_id' => '1' );
            $ins      = $this->db->insert( "tbl_party_types", $party );
            $party_id = $this->db->insert_id();
        }
        $code = $post['consignee_id'];
        if ( $code == "" ) {
            $code = 0;
        }
        $address = $post['consignee_street'] . ',' . $post['consignee_city'] . ',' . $post['consignee_state'];
        $master  = array(
            'party_type_id'      => $party_id,
            'name'               => $post['consignee_name'],
            'email'              => $post['consignee_email'],
            'street'             => $post['consignee_street'],
            'state'              => $post['consignee_state'],
            'mobile'             => $post['consignee_phone'],
            'pincode'            => $post['consignee_zipcode'],
            'country'            => $post['consignee_country'],
            'code'               => $code,
            'customeridentifier' => $code,
            'status'             => '1',
            'fax'                => $post['consignee_fax'],
            'address'            => $address,
            'user_id'            => $user_id,
            'location_id'        => $post['consignee_city'],
            'additional_info'    => $delivery_instructions,
        );

        if ( $code != 0 ) {
            $consignee_id = $code;
            $chkmaster    = $this->db->select( 'id,customer_code' )->get_where( "tbl_party_master", array( 'code' => $code ) );
            if ( $chkmaster->num_rows() > 0 ) {
                $master_id               = $chkmaster->row()->id;
                $consginee_customer_code = $chkmaster->row()->customer_code;
                if ( $order_id != "" ) {
                    if ( $consginee_customer_code != "" && $consginee_customer_code != '0' ) {
                        $upd = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", array( 'mobile' => $post['consignee_phone'], 'email' => $post['consignee_email'], 'fax' => $post['consignee_fax'], 'customer_code' => $consginee_customer_code ) );
                    } else {
                        $upd = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", array( 'mobile' => $post['consignee_phone'], 'email' => $post['consignee_email'], 'fax' => $post['consignee_fax'] ) );
                    }

                    $status = '1';
                } else {
                    if ( $consginee_customer_code != "" && $consginee_customer_code != '0' ) {
                        $master['customer_code'] = $consginee_customer_code;
                    }
                    $upd    = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", $master );
                    $status = '1';
                }
            } else {
                if ( $company_code != "" ) {
                    $master['company_code'] = $company_code;
                }
                if ( $branch_code != "" ) {
                    $master['branch_code'] = $branch_code;
                }
                $custid = "0";
                if ( $this->session->userdata( 'cust_id' ) !== FALSE ) {
                    $custid = $this->session->userdata( 'cust_id' );
                }

                $shipper_id = "";
                $chktype    = $this->db->select( "id" )->order_by( 'created_on', 'DESC' )->get_where( "tbl_party_types", array( 'name' => 'Shipper', 'user_id' => $user_id ) );
                if ( $chktype->num_rows() > 0 ) {
                    $shipper_id = $chktype->row()->id;
                }
                if ($partyCompanyCondition) {
                    $master['party_types'] = $party_id;
                } else {
                    $master['party_types'] = $shipper_id;
                }
                $master['created_on']    = $cdate;
                $master['customer_code'] = $customer_code;
                $ins                     = $this->db->insert( "tbl_party_master", $master );
                $master_id               = $this->db->insert_id();
                $status                  = '0';
            }
        } else {
            if ( $company_code != "" ) {
                $master['company_code'] = $company_code;
            }
            if ( $branch_code != "" ) {
                $master['branch_code'] = $branch_code;
            }
            $shipper_id = "";
            $chktype    = $this->db->select( "id" )->order_by( 'created_on', 'DESC' )->get_where( "tbl_party_types", array( 'name' => 'Shipper', 'user_id' => $user_id ) );
            if ( $chktype->num_rows() > 0 ) {
                $shipper_id = $chktype->row()->id;
            }
            if ($partyCompanyCondition) {
                $master['party_types'] = $party_id;
            } else {
                $master['party_types'] = $shipper_id;
            }
            $master['created_on']    = $cdate;
            $master['customer_code'] = $customer_code;
            $ins                     = $this->db->insert( "tbl_party_master", $master );
            $master_id               = $this->db->insert_id();
            $country_code            = $this->session->userdata( "usr_tzone" )['phone_code'];
            $year                    = date( 'y' );
            $week                    = date( 'W' );
            $consignee_id            = $country_code . $year . $week . $master_id;
            $upd                     = $this->db->where( array( 'id' => $master_id ) )->update( "tbl_party_master", array( 'code' => $consignee_id, 'customeridentifier' => $consignee_id ) );
            $status                  = '0';

        }

        if ( $order_id != "" ) {
            if ( $master_id != '0' ) {
                $chk_address = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $master_id, 'status' => '1' ) );
                if ( $chk_address->num_rows() > 0 ) {
                    $address_id = $chk_address->row()->id;
                    $upd_ar     = array( 'order_id' => $order_id, 'party_master_id' => $master_id, 'location_id' => $post['consignee_city'], 'street' => $post['consignee_street'], 'state' => $post['consignee_state'], 'address' => $address, 'pincode' => $post['consignee_zipcode'], 'country' => $post['consignee_country'], 'user_id' => $user_id );
                    $updaddress = $this->db->where( array( 'id' => $address_id ) )->update( "tbl_orderparty_address", $upd_ar );
                } else {
                    $insadd_ar  = array(
                        'order_id'        => $order_id,
                        'party_master_id' => $master_id,
                        'location_id'     => $post['consignee_city'],
                        'street'          => $post['consignee_street'],
                        'state'           => $post['consignee_state'],
                        'address'         => $address,
                        'pincode'         => $post['consignee_zipcode'],
                        'country'         => $post['consignee_country'],
                        'status'          => '1',
                        'user_id'         => $user_id,
                        'createdon'       => $cdate
                    );
                    $updaddress = $this->db->insert( "tbl_orderparty_address", $insadd_ar );
                }
                $order_whr = array('id'=>$order_id);
                $order_upd = array();
                if($post['consignee_name'] != ""){
                    $order_upd['delivery_company'] = $post['consignee_name'];
                }
                if($post['consignee_country'] != ""){
                    $order_upd['delivery_country'] = $post['consignee_country'];
                }
                if($post['consignee_city'] != ""){
                    $order_upd['delivery_city'] = $post['consignee_city'];
                }
                if($post['consignee_zipcode'] != ""){
                    $order_upd['delivery_pincode'] = $post['consignee_zipcode'];
                }
                if($post['consignee_state'] != ""){
                    $order_upd['delivery_address2'] = $post['consignee_state'];
                }
                if($post['consignee_street'] != ""){
                    $order_upd['delivery_address1'] = $post['consignee_street'];
                }
                if(!empty($order_upd)){
                    $upd_ordertbl = $this->common->updatetbledata("tb_orders",$order_upd,$order_whr);
                }
            }
            $status = '1';
        }
        $arr = array( 'master_id' => $master_id, 'status' => $status, 'consignee_id' => $consignee_id );
        echo json_encode( $arr );

    }

    public function getinvolvedpartyId() {

        $user_id = $this->session->userdata( 'user_id' );
        $parties = array();
        $code    = $this->input->post( 'code' );
        if ( $user_id != "" ) {
            $custid         = "0";
            $whr            = "";
            $chkcompanycode = $this->session->userdata( 'company_code' );
            if ( $chkcompanycode != 'NZKN' ) {
                if ( $this->session->userdata( 'cust_id' ) !== FALSE ) {
                    $custid = $this->session->userdata( 'cust_id' );
                }
                $subcusts = array();
                if ( $custid != 0 ) {
                    if ( $this->session->userdata( 'sub_cust' ) !== FALSE ) {
                        $subcusts = $this->session->userdata( 'sub_cust' );
                        if ( count( $subcusts ) > 0 ) {
                            array_push( $subcusts, $custid );
                        } else {
                            $subcusts = $custid;
                            // array_push($subcusts, $custid);
                        }
                    } else {
                        $subcusts = $custid;
                        // array_push($subcusts, $custid);
                    }
                }
                $customer_code = array();
                if ( ! empty( $subcusts ) ) {
                    $select          = "code";
                    $table           = "tb_customers";
                    $customerdetails = $this->Order->getcustomercodebyids( $select, $table, $subcusts );
                    if ( ! empty( $customerdetails ) ) {
                        foreach ( $customerdetails as $cust ) {
                            $customer_code[] = $cust['code'];
                        }
                    }
                }
                if ( ! empty( $customer_code ) ) {
                    $whr = "AND m.customer_code IN ('" . implode( "','", $customer_code ) . "') ";
                }
            }
            $pwhr = "m.user_id ='" . $user_id . "' AND ";
            $permission = checkuserpermissions();
            if (in_array("businesspartners", $permission)) {
                $company_code = $this->session->userdata('company_code');
                $pwhr = "m.company_code LIKE '" . $company_code . "' AND ";
            } else {
                $pwhr = "m.user_id ='" . $user_id . "' AND ";
            }
            $chkqry = $this->db->query( "SELECT m.id,m.code FROM tbl_party_master m,tbl_party_types t WHERE t.id=m.party_type_id AND m.user_id='" . $user_id . "' AND m.code LIKE '%" . $code . "%' AND m.code IS NOT NULL AND m.code != '' AND m.code !='0' AND m.company_code != '' AND m.company_code IS NOT NULL AND m.branch_code != '' AND m.branch_code IS NOT NULL " . $whr . " GROUP BY m.id ORDER BY m.created_on DESC" );
            if ( $chkqry->num_rows() > 0 ) {
                foreach ( $chkqry->result() as $res ) {
                    $parties[] = array( 'id' => $res->id, 'customeridentifier' => $res->code );
                }
            }

        }

        echo json_encode( $parties );
    }

    public function getpartydetailsbyID() {
        $parties = array();
        $code    = $this->input->post( 'id' );
        $chkqry  = $this->db->query( "SELECT m.id,m.name,m.email,m.street,m.location_id as city,m.state,m.mobile,m.address,m.country,m.pincode,m.country,m.code,m.fax,t.id as partytype_id,t.name as role FROM tbl_party_master m,tbl_party_types t WHERE m.code LIKE '%" . $code . "%' AND t.id=m.party_type_id ORDER BY m.id DESC" );
        if ( $chkqry->num_rows() > 0 ) {
            $parties[] = array(
                'id'           => $chkqry->row()->id,
                'name'         => $chkqry->row()->name,
                'phone'        => $chkqry->row()->mobile,
                'street'       => $chkqry->row()->street,
                'city'         => $chkqry->row()->city,
                'pincode'      => $chkqry->row()->pincode,
                'code'         => $chkqry->row()->code,
                'country'      => $chkqry->row()->country,
                'email_id'     => $chkqry->row()->email,
                'fax'          => $chkqry->row()->fax,
                'state'        => $chkqry->row()->state,
                'role'         => $chkqry->row()->role,
                'partytype_id' => $chkqry->row()->partytype_id,
                'address'      => $chkqry->row()->address,
                'country'      => $chkqry->row()->country
            );
        }
        echo json_encode( $parties );
    }

    public function addinvolvedpartyfororder( $order_id = NULL ) {

        $post         = $this->input->post();
        $cdate        = date( 'Y-m-d H:i:s' );
        $party_id     = 0;
        $inner_id     = $data = array();
        $user_id      = $this->session->userdata( 'user_id' );
        $company_code = isset( $_POST['party_company_id'] ) ? $_POST['party_company_id'] : "";
        $branch_code  = isset( $_POST['party_branch_id'] ) ? $_POST['party_branch_id'] : "";
        if ( $user_id != "" ) {
            $company_code = $this->session->userdata( 'company_code' );
            $branch_code  = $this->session->userdata( 'branch_code' );
            $address      = $post['street'] . ',' . $post['city'] . ',' . $post['city'];
            $party        = array(
                'customeridentifier' => $post['party_id'],
                'code'               => $post['party_id'],
                'name'               => $post['party_name'],
                'street'             => $post['street'],
                'pincode'            => $post['zipcode'],
                'country'            => $post['country'],
                'state'              => $post['state'],
                'mobile'             => $post['mobile'],
                'fax'                => $post['fax'],
                'email'              => $post['email'],
                'created_on'         => $cdate,
                'address'            => $address,
                'company_code'       => $company_code,
                'branch_code'        => $branch_code,
                'location_id'        => $post['city']
            );
            $role_id      = 0;
            if ( $post['role'] != "" ) {
                $getroleid = $this->db->select( "id" )->get_where( "tbl_party_types", array( 'name' => $post['role'], 'company_code' => $company_code, 'branch_code' => $branch_code, 'status' => 1, 'user_id' => $user_id ) );
                if ( $getroleid->num_rows() > 0 ) {
                    $role_id = $getroleid->row()->id;
                } else {
                    $getroleid_nobranch = $this->db->select( "id" )->get_where( "tbl_party_types", array( 'name' => $post['role'], 'company_code' => $company_code, 'status' => 1, 'user_id' => $user_id ) );
                    if ( $getroleid_nobranch->num_rows() > 0 ) {
                        $role_id = $getroleid_nobranch->row()->id;
                    } else {
                        $ins_role = array( 'name' => $post['role'], 'description' => $post['role'], 'company_code' => $company_code, 'branch_code' => $branch_code, 'user_id' => $user_id, 'status' => '1', 'created_on' => $cdate );
                        $insqry   = $this->db->insert( "tbl_party_types", $ins_role );
                        $role_id  = $this->db->insert_id();
                    }

                }
            }

            $party['party_type_id'] = $role_id;
            $party_type             = "";
            $getpartytype           = $this->db->select( "name" )->get_where( "tbl_party_types", array( 'id' => $party_id ) );
            if ( $getpartytype->num_rows() > 0 ) {
                $party_type = $getpartytype->row()->name;
            }
            $parties = array(
                'party_id'   => $post['party_id'],
                'party_type' => $party_type,
                'name'       => $post['party_name'],
                'street'     => $post['street'],
                'zipcode'    => $post['zipcode'],
                'city'       => $post['city'],
                'country'    => $post['country'],
                'state'      => $post['state'],
                'mobile'     => $post['mobile'],
                'fax'        => $post['fax'],
                'emailid'    => $post['email'],
                'action'     => "<button id=" . $post['party_id'] . " class='btn btn-primary btn-xs editparties' onclick='editpartydetails(" . $post['party_id'] . ",event)'><small><i class='glyphicon glyphicon-pencil'></i></small></button> <button id=" . $post['party_id'] . " class='btn btn-primary btn-xs deleteround' onclick='deletepartydetails(" . $post['party_id'] . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>"
            );

            $chk = $this->db->select( 'id' )->get_where( 'tbl_party_master', array( 'code' => $post['party_id'] ) );
            if ( $chk->num_rows() > 0 ) {
                $party_id = $chk->row()->id;
                $upd      = $this->db->where( array( 'id' => $party_id ) )->update( "tbl_party_master", $party );
            } else {
                $ins      = $this->db->insert( "tbl_party_master", $party );
                $party_id = $this->db->insert_id();
            }
            if ( $order_id != NULL ) {
                $chk = $this->db->select( 'id,status' )->get_where( 'tb_order_parties', array( 'party_id' => $party_id, 'order_id' => $order_id ) );
                if ( $chk->num_rows() > 0 ) {
                    $id     = $chk->row()->id;
                    $status = $chk->row()->status;
                    if ( $status == '1' ) {
                        echo "2";
                    } else if ( $status == '0' ) {

                        $upd = $this->db->where( array( 'id' => $id ) )->update( 'tb_order_parties', array( 'status' => '1' ) );
                        if ( $upd ) {
                            echo "1";
                        }
                    }
                    if ( $role_id != "0" ) {
                        $upd = $this->db->where( array( 'id' => $id ) )->update( "tb_order_parties", array( 'party_type' => $role_id ) );
                    }
                } else {
                    $getorder_number = $this->db->select( "order_id" )->get_where( "tb_orders", array( 'id' => $order_id ) );
                    $order_number    = $getorder_number->row()->order_id;
                    $party_type      = 1;
                    if ( $role_id != "0" ) {
                        $party_type = $role_id;
                    } else {
                        $getpartytype = $this->db->query( "SELECT party_type_id FROM tbl_party_master WHERE id='" . $party_id . "'" );
                        if ( $getpartytype->num_rows() > 0 ) {
                            $party_type = $getpartytype->row()->party_type_id;
                        }
                    }
                    $order_ins = array( 'party_id' => $party_id, 'order_id' => $order_id, 'createdon' => $cdate, 'status' => '1', 'party_type' => $party_type, 'order_number' => $order_number );
                    $ins       = $this->db->insert( "tb_order_parties", $order_ins );
                    if ( $ins ) {
                        echo "1";
                    } else {
                        echo "0";
                    }
                }

            }
        }
    }
    
    public function updateorder() {
        $order_id = isset( $_POST['order_id'] ) ? $_POST['order_id'] : '0';
        if ( $order_id != "0" ) {
            $cdate                  = date( 'Y-m-d H:i:s' );
            $user_id                = $this->session->userdata( 'user_id' );
            $booking_id             = isset( $_POST['booking_id'] ) ? $_POST['booking_id'] : "";
            $company_code           = isset( $_POST['company_code'] ) ? $_POST['company_code'] : "";
            $branch_code            = isset( $_POST['branch_code'] ) ? $_POST['branch_code'] : "";
            $department_code        = isset( $_POST['department_code'] ) ? $_POST['department_code'] : "";
            $product                = isset( $_POST['product'] ) ? $_POST['product'] : "";
            $service                = isset( $_POST['service'] ) ? $_POST['service'] : "";
            $delivery_terms         = isset( $_POST['delivery_terms'] ) ? $_POST['delivery_terms'] : "";
            $modeof_trasnport       = isset( $_POST['modeof_trasnport'] ) ? $_POST['modeof_trasnport'] : "TL";
            $order_type             = isset( $_POST['order_type'] ) ? $_POST['order_type'] : "";
            $cost_center             = isset( $_POST['cost_center'] ) ? $_POST['cost_center'] : null;
            $incoterm               = isset( $_POST['incoterm'] ) ? $_POST['incoterm'] : "";
            $shipment_id            = isset( $_POST['delivery_note'] ) ? $_POST['delivery_note'] : "";
            $container_no           = isset( $_POST['container_num'] ) ? $_POST['container_num'] : "";
            $porder                 = isset( $_POST['purchase_order'] ) ? $_POST['purchase_order'] : "";
            $order_shipper_id       = isset( $_POST['order_shipper_id'] ) ? $_POST['order_shipper_id'] : "0";
            $customer_id            = isset( $_POST['customer_id'] ) ? $_POST['customer_id'] : "0";
            $pickup                 = isset( $_POST['order_pickup_id'] ) ? $_POST['order_pickup_id'] : "0";
            $docs_sent_datetime     = isset( $_POST['docs_sent_datetime'] ) ? $_POST['docs_sent_datetime'] : "";
            $docs_received_datetime = isset( $_POST['docs_received_datetime'] ) ? $_POST['docs_received_datetime'] : "";
            $consignee_name         = isset( $_POST['consignee_name'] ) ? $_POST['consignee_name'] : "";
            $consignee_street       = isset( $_POST['consignee_street'] ) ? $_POST['consignee_street'] : "";
            $consignee_city         = isset( $_POST['consignee_city'] ) ? $_POST['consignee_city'] : "";
            $consignee_state        = isset( $_POST['consignee_state'] ) ? $_POST['consignee_state'] : "";
            $consignee_zipcode      = isset( $_POST['consignee_zipcode'] ) ? $_POST['consignee_zipcode'] : "";
            if ( $pickup == "" || $pickup == "0" ) {
                if ( $customer_id != "" && $customer_id != "0" ) {
                    $getcustomerid = $this->db->select( "id" )->get_where( "tb_customers", array( 'code' => $customer_id, 'user_id' => $user_id, 'status' => '1' ) );
                    if ( $getcustomerid->num_rows() > 0 ) {
                        $pickup = $getcustomerid->row()->id;
                    }
                }
            }
            $getbookingid = $this->common->gettblrowdata( array( 'id' => $order_id ), "order_id", "tb_orders", 0, 0 );
            if ( ! empty( $getbookingid ) ) {
                $booking_id = $getbookingid['order_id'];
            }
            $notify_party                 = isset( $_POST['notify_party'] ) ? $_POST['notify_party'] : "";
            $driver_pickup_instructions   = isset( $_POST['driver_pickup_instructions'] ) ? $_POST['driver_pickup_instructions'] : "";
            $driver_delivery_instructions = isset( $_POST['driver_delivery_instructions'] ) ? $_POST['driver_delivery_instructions'] : "";
            $multiple_marks_numbers = isset( $_POST['multiple_marks_numbers'] ) ? str_replace(['\r\n','\r','\n'], ", ", $_POST['multiple_marks_numbers']) : "";
            if ($shipment_id != "") {
                $this->Order->updateOrderReference($order_id, 'DQ', $shipment_id);
            }
            if ($company_code == 'AUKN' || $company_code == 'UKKN') {
                if ($container_no != "") {
                    $this->Order->updateOrderReference($order_id, 'CTR', $container_no);
                }
            }
            if ($driver_pickup_instructions != "") {
                $this->Order->updateOrderReference($order_id, 'ORD_PIKINST', $driver_pickup_instructions);
            }
            if ($driver_delivery_instructions != "") {
                $this->Order->updateOrderReference($order_id, 'ORD_DLVINST', $driver_delivery_instructions);
            }
            if (!empty($multiple_marks_numbers)) {
                $this->Order->updateOrderReference($order_id, 'MARKS_NUMBERS', $multiple_marks_numbers);
            }
            if ($porder != "") {
                $this->Order->updateOrderReference($order_id, 'PO', $porder);
            }
            $goods_value = isset( $_POST['goods_value'] ) ? $_POST['goods_value'] : "0.00";
            if ( $goods_value == "" ) {
                $goods_value = 0.00;
            }
            if (checkAccessConditions("CHECK_STS_REFERENCE_COUNTRIES", $company_code )) {
                $ins_ref = ['order_id' => $order_id, 'reference_id' => 'STS'];
                $checkSTSRef = $this->common->gettblrowdata($ins_ref, "id", "tb_order_references", 0, 0);
                if (count($checkSTSRef) == 0) {
                    $ins_ref['ref_value'] = "Pending";
                    $this->common->insertTableData("tb_order_references", $ins_ref);
                }
            }
            $currency = isset($_POST['currency']) ? $_POST['currency'] : "";
            $party_row_id     = isset( $_POST['order_party_row_id'] ) ? $_POST['order_party_row_id'] : "0";
            $reference_ids    = isset( $_POST['reference_ids'] ) ? $_POST['reference_ids'] : "0";
            $order_inv_row_id = isset( $_POST['order_inv_row_id'] ) ? $_POST['order_inv_row_id'] : '0';
            $order_cargo_id   = isset( $_POST['order_cargo_id'] ) ? $_POST['order_cargo_id'] : "";
            $pickup           = isset( $_POST['order_pickup_id'] ) ? $_POST['order_pickup_id'] : "";
            $delivery         = isset( $_POST['order_drop_id'] ) ? $_POST['order_drop_id'] : "";
            $early_pickup     = isset( $_POST['early_pickup'] ) ? $_POST['early_pickup'] : "";
            $late_pickup      = isset( $_POST['late_pickup'] ) ? $_POST['late_pickup'] : "";
            $early_delivery   = isset( $_POST['early_delivery'] ) ? $_POST['early_delivery'] : "";
            $late_delivery    = isset( $_POST['late_delivery'] ) ? $_POST['late_delivery'] : "";
            $e_pickup         = date( 'Y-m-d H:i:s' );
            $curtz            = $this->session->userdata( "usr_tzone" )['timezone'];
            if ( $early_pickup != "" ) {
                $e_pickup = date( 'Y-m-d H:i:s', strtotime( $early_pickup ) );
            }
            if ( $late_pickup != "" ) {
                $l_pickup = date( 'Y-m-d H:i:s', strtotime( $late_pickup ) );
            } else {
                $l_pickup = date( 'Y-m-d H:i:s', strtotime( '+1 hour', strtotime( $e_pickup ) ) );
            }
            $e_delivery = date( 'Y-m-d H:i:s' );
            if ( $early_delivery != "" ) {
                $e_delivery = date( 'Y-m-d H:i:s', strtotime( $early_delivery ) );
            }
            if ( $late_delivery != "" ) {
                $l_delivery = date( 'Y-m-d H:i:s', strtotime( $late_delivery ) );
            } else {
                $l_delivery = date( 'Y-m-d H:i:s', strtotime( '+1 hour', strtotime( $e_delivery ) ) );
            }
            if ( $docs_sent_datetime != "" && $docs_sent_datetime != "0000-00-00 00:00:00" ) {
                $getdocsent         = getdatetimebytimezone( DFLT_TZ, $docs_sent_datetime, $curtz );
                $docs_sent_datetime = $getdocsent['datetime'];
            }
            if ( $docs_received_datetime != "" && $docs_received_datetime != "0000-00-00 00:00:00" ) {
                $getdocrec              = getdatetimebytimezone( DFLT_TZ, $docs_received_datetime, $curtz );
                $docs_received_datetime = $getdocrec['datetime'];
            }
            $pickup_name   = $pickup_country = $pickup_street = $pickup_pincode = $pickup_city = "";
            $drop_id       = $drop_name = $drop_country = $drop_street = $drop_pincode = $drop_city = $drop_state = $pickup_state = $drop_state = $pickup_address = $drop_address = "";
            $pickup_custid = $drop_custid = $pickup_id = 0;

            $drop_row_id = $shipper_party_id = $consignee_party_id = 0;
            $chekparty   = $this->db->query( "SELECT p.id,p.party_type_id, p.name,p.code,o.id as order_party_id,o.party_type FROM tbl_party_master p INNER JOIN tb_order_parties o ON p.id=o.party_id AND o.status=1  WHERE p.status=1 AND o.order_id='$order_id' GROUP BY o.party_type" );
            if ( $chekparty->num_rows() > 0 ) {
                foreach ( $chekparty->result() as $rr ) {
                    $ptype   = $rr->party_type;
                    $chktype = $this->db->select( "name" )->get_where( "tbl_party_types", array( "id" => $ptype ), 1, 0 );
                    if ( $chktype->num_rows() > 0 ) {
                        if ( $chktype->row()->name == "Consignee" ) {
                            $drop_row_id        = $rr->id;
                            $drop_id            = $rr->code;
                            $drop_name          = $rr->name;
                            $drop_custid        = $rr->code;
                            $consignee_party_id = $rr->order_party_id;
                        } else if ( $chktype->row()->name == "Shipper" ) {
                            $pickup_id        = $rr->id;
                            $pickup_custid    = $rr->code;
                            $pickup_name      = $rr->name;
                            $shipper_party_id = $rr->order_party_id;
                        }
                    }
                }
            }
            if ( $pickup_id != $order_shipper_id ) {
                if ( $order_shipper_id != "0" ) {
                    $getshippercustid = $this->db->query( "SELECT name,code,location_id as city,street,state,address,country,pincode FROM tbl_party_master WHERE id='" . $order_shipper_id . "'" );
                    if ( $getshippercustid->num_rows() > 0 ) {
                        $pickup_custid  = $getshippercustid->row()->code;
                        $pickup_name    = $getshippercustid->row()->name;
                        $pickup_state   = $getshippercustid->row()->state;
                        $pickup_address = $getshippercustid->row()->address;
                        $pickup_country = $getshippercustid->row()->country;
                        $pickup_street  = $getshippercustid->row()->street;
                        $pickup_pincode = $getshippercustid->row()->pincode;
                        $pickup_city    = $getshippercustid->row()->city;
                        if ( $pickup_id != 0 ) {
                            if ( $shipper_party_id != 0 ) {
                                $chkorder_sparty = $this->db->select( "id" )->get_where( "tb_order_parties", array( 'id' => $shipper_party_id ) );
                                if ( $chkorder_sparty->num_rows() > 0 ) {
                                    $upd_sparty_address = $this->db->where( array( 'id' => $shipper_party_id ) )->update( "tb_order_parties", array( 'status' => '0' ) );
                                }
                            }
                            $chkprevious_shipperaddress = $this->db->select( 'id' )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $pickup_id, 'status' => '1' ) );
                            if ( $chkprevious_shipperaddress->num_rows() > 0 ) {
                                $upd_oldsaddress = $this->db->where( array( 'id' => $chkprevious_shipperaddress->row()->id ) )->update( "tbl_orderparty_address", array( 'status' => '0' ) );
                            }
                        }
                        $chkpartyaddress = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'status' => '1' ) );
                        $shipper_address = array( 'order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'location_id' => $pickup_city, 'street' => $pickup_street, 'state' => $pickup_state, 'address' => $pickup_address, 'pincode' => $pickup_pincode, 'country' => $pickup_country, 'user_id' => $user_id, 'status' => '1' );
                        if ( $chkpartyaddress->num_rows() > 0 ) {
                            $pickup_addressid = $chkpartyaddress->row()->id;
                            $upd              = $this->db->where( array( 'id' => $pickup_addressid ) )->update( "tbl_orderparty_address", $shipper_address );
                        } else {
                            $shipper_address['createdon'] = $cdate;
                            $this->db->insert( "tbl_orderparty_address", $shipper_address );
                        }
                    }
                }
            } else if ( $order_shipper_id == $pickup_id ) {
                if ( $order_shipper_id != 0 ) {
                    $chk_shipperaddress = $this->db->select( "location_id,street,state,address,pincode,country" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'status' => '1' ) );
                    if ( $chk_shipperaddress->num_rows() > 0 ) {
                        $pickup_city    = $chk_shipperaddress->row()->location_id;
                        $pickup_country = $chk_shipperaddress->row()->country;
                        $pickup_street  = $chk_shipperaddress->row()->street;
                        $pickup_pincode = $chk_shipperaddress->row()->pincode;
                        $pickup_state   = $chk_shipperaddress->row()->state;
                        $pickup_address = $chk_shipperaddress->row()->address;
                    }
                }
            }
            if ( $drop_row_id != $delivery ) {
                if ( $delivery != "0" ) {
                    $getdropcustid = $this->db->query( "SELECT name,code,location_id as city,street,state,address,country,pincode FROM tbl_party_master WHERE id='" . $delivery . "'" );
                    if ( $getdropcustid->num_rows() > 0 ) {
                        $drop_id      = $delivery;
                        $drop_custid  = $getdropcustid->row()->code;
                        $drop_name    = $getdropcustid->row()->name;
                        $drop_state   = $getdropcustid->row()->state;
                        $drop_address = $getdropcustid->row()->address;
                        $drop_country = $getdropcustid->row()->country;
                        $drop_street  = $getdropcustid->row()->street;
                        $drop_pincode = $getdropcustid->row()->pincode;
                        $drop_city    = $getdropcustid->row()->city;
                        if ( $drop_row_id != 0 ) {
                            $chkprevious_dropaddress = $this->db->select( 'id' )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $drop_row_id, 'status' => '1' ) );
                            if ( $chkprevious_dropaddress->num_rows() > 0 ) {
                                $upd_olddaddress = $this->db->where( array( 'id' => $chkprevious_dropaddress->row()->id ) )->update( "tbl_orderparty_address", array( 'status' => '0' ) );
                            }
                        }
                        if ( $consignee_party_id != '0' ) {
                            $chkorder_cparty = $this->db->select( "id" )->get_where( "tb_order_parties", array( 'id' => $shipper_party_id ) );
                            if ( $chkorder_cparty->num_rows() > 0 ) {
                                $upd_cparty_address = $this->db->where( array( 'id' => $consignee_party_id ) )->update( "tb_order_parties", array( 'status' => '0' ) );
                            }
                        }
                        $chkpartyaddress = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $delivery, 'status' => '1' ) );
                        $drop_address    = array( 'order_id' => $order_id, 'party_master_id' => $delivery, 'location_id' => $drop_city, 'street' => $drop_street, 'state' => $drop_state, 'address' => $drop_address, 'pincode' => $drop_pincode, 'country' => $drop_country, 'user_id' => $user_id, 'status' => '1' );
                        if ( $chkpartyaddress->num_rows() > 0 ) {
                            $drop_addressid = $chkpartyaddress->row()->id;
                            $upd            = $this->db->where( array( 'id' => $drop_addressid ) )->update( "tbl_orderparty_address", $drop_address );
                        } else {
                            $drop_address['createdon'] = $cdate;
                            $this->db->insert( "tbl_orderparty_address", $drop_address );
                        }
                    }
                }
            } else if ( $drop_row_id == $delivery ) {
                if ( $delivery != 0 ) {
                    $chkdrop = $this->db->select( "location_id,street,state,address,pincode,country" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $delivery, 'status' => '1' ) );
                    if ( $chkdrop->num_rows() > 0 ) {
                        $drop_city    = $chkdrop->row()->location_id;
                        $drop_state   = $chkdrop->row()->state;
                        $drop_country = $chkdrop->row()->country;
                        $drop_street  = $chkdrop->row()->street;
                        $drop_pincode = $chkdrop->row()->pincode;
                        $drop_address = $chkdrop->row()->address;
                    }
                }
            }
            $sub_cut_parties = array();
            $sub_cut_parties['0'] = $order_shipper_id;
            $sub_cut_parties['1'] = $delivery;
            $sub_cut_parties['2'] = '0';
            $sub_cut_parties['3'] = '0';
            if (!empty($sub_cut_parties)) {
                subcustpartiesinsert($order_id, $booking_id, $sub_cut_parties);
            }
            $ship_row_id      = 0;
            $enddate          = date( 'Y-m-d H:i:s', strtotime( "+1 day" ) );
            $tid              = $tname = "";
            $gettrasnportmode = $this->db->query( "SELECT id,name FROM tb_transportmode WHERE code LIKE '" . $modeof_trasnport . "'" );
            if ( $gettrasnportmode->num_rows() > 0 ) {
                $tid   = $gettrasnportmode->row()->id;
                $tname = $gettrasnportmode->row()->name;
            }
            $ship_arr   = array(
                'unitspec'         => 1,
                'shipid'           => $shipment_id,
                'txnid'            => $shipment_id,
                'trucktype'        => $tname,
                'pickupcnt'        => '1',
                'dropcnt'          => '1',
                'insertusr'        => $pickup_custid,
                'carrier'          => '0',
                'insertuserdate'   => $cdate,
                'enddate'          => $enddate,
                'insdate'          => $cdate,
                'upddate'          => $cdate,
                'reason'           => 'SHIPMENT',
                'purpose'          => 'SEND INTEGRATION',
                'ship_object'      => 'SHIPMENT',
                'logdate'          => $cdate,
                'transport_mode'   => $modeof_trasnport,
                'domainname'       => $branch_code,
                'company_code'     => $company_code,
                'branch_code'      => $branch_code,
                'product'          => $product,
                'freight_term'     => '60',
                'freight_termname' => 'Free of Charge',
                'incoterm'         => $incoterm,
                'modeoftransport'  => $tid
            );
            $chk_shipid = $this->db->query( "SELECT id FROM tb_shipments WHERE shipid LIKE '" . $shipment_id . "'" );
            if ( $chk_shipid->num_rows() > 0 ) {
                $ship_row_id = $chk_shipid->row()->id;
                $this->db->where( array( 'id' => $ship_row_id ) )->update( "tb_shipments", $ship_arr );
            } else {

                $ship_arr['createdon'] = $cdate;
                $ship_ins              = $this->db->insert( "tb_shipments", $ship_arr );
                $ship_row_id           = $this->db->insert_id();
            }

            $getpickup    = getdatetimebytimezone( DFLT_TZ, $e_pickup, $curtz );
            $e_pickup     = $getpickup['datetime'];
            $getlpickup   = getdatetimebytimezone( DFLT_TZ, $l_pickup, $curtz );
            $l_pickup     = $getlpickup['datetime'];
            $getdelivery  = getdatetimebytimezone( DFLT_TZ, $e_delivery, $curtz );
            $e_delivery   = $getdelivery['datetime'];
            $getldelivery = getdatetimebytimezone( DFLT_TZ, $l_delivery, $curtz );
            $l_delivery   = $getldelivery['datetime'];
            $ins = [
                'shipment_id' => $ship_row_id,
                'product' => $product,
                'pickup_datetime' => $e_pickup,
                'delivery_datetime' => $e_delivery,
                'pickup_endtime' => $l_pickup,
                'drop_endtime' => $l_delivery,
                'goods_value' => $goods_value,
                'currency' => $currency,
                'company_code' => $company_code,
                'branch_code' => $branch_code,
                'transport_mode' => $modeof_trasnport,
            ];
            $getDefaultTimeZone = getdatetimebytimezone(DFLT_TZ, date('Y-m-d H:i:s'), $curtz);
            $ins['updatedon'] = $getDefaultTimeZone['datetime'];
            if ( $pickup_name != "" ) {
                $ins['pickup_company'] = $pickup_name;
            }
            if ( $pickup_country != "" ) {
                $ins['pickup_country'] = $pickup_country;
            }
            if ( $consignee_name != "" ) {
                $ins['delivery_company'] = $consignee_name;
            }
            if ( $drop_country != "" ) {
                $ins['delivery_country'] = $drop_country;
            }
            if ( $pickup_street != "" ) {
                $ins['pickup_address1'] = $pickup_street;
            }
            if ( $pickup_city != "" ) {
                $ins['pickup_city'] = $pickup_city;
            }
            if ( $pickup_pincode != "" ) {
                $loc                   = [];
                $add1                  = implode( ",", [ $pickup_street, $pickup_city, $pickup_country, $pickup_pincode ] );
                $loc                   = getlatlngsbyplace( $add1 );
                $ins['plat']           = @$loc[0];
                $ins['plng']           = @$loc[1];
                $ins['pickup_pincode'] = $pickup_pincode;
            }
            if ( $pickup_state != "" ) {
                $ins['pickup_address2'] = $pickup_state;
            }
            if ( $consignee_street != "" ) {
                $ins['delivery_address1'] = $consignee_street;
            }
            if ( $consignee_state != "" ) {
                $ins['delivery_address2'] = $consignee_state;
            }
            if ( $consignee_city != "" ) {
                $ins['delivery_city'] = $consignee_city;
            }
            if ( $pickup != "" && $pickup != "" ) {
                $ins['customer_id'] = $pickup;
            }
            if ( $consignee_zipcode != "" ) {
                $ins['delivery_pincode'] = $consignee_zipcode;
            }

            if ( $drop_pincode != "" ) {
                $loc                     = [];
                $add2                    = implode( ",", [ $drop_street, $drop_city, $drop_country, $drop_pincode ] );
                $loc                     = getlatlngsbyplace( $add2 );
                $ins['dlat']             = @$loc[0];
                $ins['dlng']             = @$loc[1];
            }
            $this->db->where( array( 'id' => $order_id ) )->update( 'tb_orders', $ins );
            insertOrdersRefFileLineIdentifier(['pickupCity' => $pickup_city, 'pickupState' => $pickup_state, 'pickupCountry' => $pickup_country, 'dropCity' => $drop_city, 'dropState' => $drop_state, 'dropCountry' => $drop_country, 'companyCode' => $company_code, 'branchCode' => $branch_code, 'orderRowId' => $order_id, 'date' => $cdate]);
            $details_ins = array(
                'service'                => $service,
                'delivery_term'          => $delivery_terms,
                'incoterm'               => $incoterm,
                /*	'purchase_order'         => $porder,*/
                'notify_party'           => $notify_party,
                'lane_reference'         => "LR",
                'distance' => '0',
                'department_code' => $department_code,
                'temperature_control' => '0',
                'valorance_insurance' => '0',
                'high_cargo_value' => '0',
                'customs_required' => '0',
                'order_type' => $order_type,
                'cost_center_id' => $cost_center,
                'docs_received_datetime' => $docs_received_datetime,
                'docs_sent_datetime' => $docs_sent_datetime
            );
            $chk = $this->db->select("id")->get_where("tb_order_details", array('order_row_id' => $order_id));
            if ($chk->num_rows() > 0) {
                $upd_details = $this->db->where(array('order_row_id' => $order_id))->update(
                    "tb_order_details",
                    $details_ins
                );
            } else {
                $details_ins['createdon'] = $cdate;
                $details_ins['order_row_id'] = $order_id;
                $details_ins['order_id'] = $booking_id;
                $ins = $this->db->insert("tb_order_details", $details_ins);
            }

            $totalWeight = $totalVolume = $totalQuantity = 0;
            $getTotal = $this->db->query(
                "SELECT TRUNCATE(sum(Case When cd.weight_unit IN ('G', 'Gms', 'gms', 'grm') Then ocd.weight/1000 Else
                                            (Case When cd.weight_unit IN ('Kg', 'kg') Then ocd.weight Else
                                               (Case When cd.weight_unit IN ('Tons', 'tons') Then ocd.weight * 1000 Else 0 End) End) End), 3) as total_weight,
                        sum(ocd.volume) as total_volume,sum(ocd.quantity) as total_quantity
                FROM tb_order_cargodetails ocd
                LEFT JOIN tb_cargo_details cd ON cd.id = ocd.cargo_id
                WHERE ocd.order_id='" . $order_id . "' AND ocd.status ='1'"
            );

            if ($getTotal->num_rows() > 0) {
                $totalVolume = $getTotal->row()->total_volume;
                $totalWeight = $getTotal->row()->total_weight;
                $totalQuantity = $getTotal->row()->total_quantity;
            }

            $this->db->where(['id' => $order_id])->update(
                "tb_orders",
                [
                    'volume' => $totalVolume,
                    'weight' => $totalWeight,
                    'quantity' => $totalQuantity
                ]
            );

            $chkshipment = $this->db->select("shift_id")->get_where("tb_orders", array('id' => $order_id));
            if ($chkshipment->num_rows() > 0) {
                $shiftid = $chkshipment->row()->shift_id;
                $chkshipmentemp = $this->db->select("id,stop_id,drop_stopid")->get_where(
                    "tb_employee",
                    array(
                        'shift_id' => $shiftid,
                        'order_id' => $booking_id
                    )
                );
                $empid_ins = $pickupstops = $deliverystops = [];

                if ($chkshipmentemp->num_rows() > 0) {
                    $empid = $chkshipmentemp->row()->id;
                    $empid_ins['pickup_datetime'] = $e_pickup;
                    $empid_ins['drop_datetime'] = $l_delivery;
                    $empid_ins['startdate'] = $e_pickup;
                    $empid_ins['enddate'] = $l_delivery;
                    $empid_ins['shipment_weight'] = $totalWeight;
                    $this->db->where(['id' => $empid])->update("tb_employee", $empid_ins);

                    $pickupstops['startdate'] = $e_pickup;
                    $pickupstops['enddate'] = $l_pickup;
                    $pickupstops['weight'] = $totalWeight;
                    $empstop_id = $chkshipmentemp->row()->stop_id;
                    $this->db->where(['id' => $empstop_id])->update("tb_shiporder_stops", $pickupstops);

                    $deliverystops['startdate'] = $e_delivery;
                    $deliverystops['enddate'] = $l_delivery;
                    $deliverystops['weight'] = $totalWeight;
                    $empdrop_stopid = $chkshipmentemp->row()->drop_stopid;
                    $this->db->where(['id' => $empdrop_stopid])->update("tb_shiporder_stops", $deliverystops);
                }
            }
            $this->ordernotify('booking_edit', $order_id);

            $chk_oid = $this->db->select( "order_id" )->get_where( "tb_orders", array( 'id' => $order_id ) );
            if ( $chk_oid->num_rows() > 0 ) {
                $o_id = $chk_oid->row()->order_id;
                $chk_drop_stopid = $this->db->select("drop_stopid")->get_where("tb_employee", array('order_id' => $o_id)
                );
                if ($chk_drop_stopid->num_rows() > 0) {
                    $drop_stopid = $chk_drop_stopid->row()->drop_stopid;
                    $upd_so_details = $this->db->where(array('id' => $drop_stopid))->update(
                        "tb_shiporder_stops",
                        array(
                            'startdate' => $e_delivery,
                            'enddate' => $l_delivery
                        )
                    );
                }
            }
        }
        if ( $order_id != "" && $order_id != '0' ) {
            $this->session->set_flashdata( 'success_msg', 'Order Updated Successfully - ' . $booking_id );
            redirect( 'orders/orderslist/' . $order_id );
        } else {
            redirect( 'orders' );
        }


    }

    public function insertinvolvedparties( $id = NULL ) {

        $post     = $this->input->post();
        $cdate    = date( 'Y-m-d H:i:s' );
        $party_id = 0;
        $inner_id = $data = array();
        $user_id  = $this->session->userdata( 'user_id' );
        $order_id = isset( $_POST['party_order_id'] ) ? $_POST['party_order_id'] : "0";
        if ( $user_id != "" ) {
            $custid = "0";
            if ( $this->session->userdata( 'cust_id' ) !== FALSE ) {
                $custid = $this->session->userdata( 'cust_id' );
            }
            $company_code = $this->session->userdata( 'company_code' );
            $branch_code  = $this->session->userdata( 'branch_code' );

            $address      = $post['street'] . ',' . $post['city'] . $post['state'];
            $party        = array(
                'customeridentifier' => $post['party_id'],
                'code'               => $post['party_id'],
                'name'               => $post['party_name'],
                'street'             => $post['street'],
                'pincode'            => $post['zipcode'],
                'country'            => $post['country'],
                'state'              => $post['state'],
                'mobile'             => $post['mobile'],
                'fax'                => $post['fax'],
                'email'              => $post['email'],
                'created_on'         => $cdate,
                'address'            => $address,
                'company_code'       => $company_code,
                'branch_code'        => $branch_code,
                'user_id'            => $user_id,
                'location_id'        => $post['city']
            );
            $party_type   = "";
            $getpartyname = $this->db->select( "name" )->get_where( "tbl_party_types", array( 'id' => $post['party_id'] ) );
            if ( $getpartyname->num_rows() > 0 ) {
                $party_type = $getpartyname->row()->name;
            }

            $parties = array(
                'party_id'   => $post['party_id'],
                'party_type' => $post['role'],
                'name'       => $post['party_name'],
                'street'     => $post['street'],
                'zipcode'    => $post['zipcode'],
                'city'       => $post['city'],
                'country'    => $post['country'],
                'state'      => $post['state'],
                'mobile'     => $post['mobile'],
                'fax'        => $post['fax'],
                'emailid'    => $post['email'],
                'action'     => "<button id=" . $post['party_id'] . " class='btn btn-primary btn-xs editparties' onclick='editpartydetails(" . $post['party_id'] . ",event)'><small><i class='glyphicon glyphicon-pencil'></i></small></button> <button id=" . $post['party_id'] . " class='btn btn-primary btn-xs deleteround' onclick='deletepartydetails(" . $post['party_id'] . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>"
            );
            $role_id = 0;
            if ( $post['role'] != '' ) {
                $getroleid = $this->db->select( "id" )->get_where( "tbl_party_types", array( 'name' => $post['role'], 'company_code' => $company_code, 'branch_code' => $branch_code, 'status' => 1, 'user_id' => $user_id ) );
                if ( $getroleid->num_rows() > 0 ) {
                    $role_id = $getroleid->row()->id;
                } else {
                    $getroleid_nobranch = $this->db->select( "id" )->get_where( "tbl_party_types", array( 'name' => $post['role'], 'company_code' => $company_code, 'status' => 1, 'user_id' => $user_id ) );
                    if ( $getroleid_nobranch->num_rows() > 0 ) {
                        $role_id = $getroleid_nobranch->row()->id;
                    } else {
                        $ins_role = array( 'name' => $post['role'], 'description' => $post['role'], 'company_code' => $company_code, 'branch_code' => $branch_code, 'user_id' => $user_id, 'status' => '1', 'created_on' => $cdate );
                        $insqry   = $this->db->insert( "tbl_party_types", $ins_ar );
                        $role_id  = $this->db->insert_id();
                    }
                }
            }
            if ( $id == NULL ) {
                if ( $custid != "0" ) {
                    $getcustomer_code = $this->db->select( "code" )->get_where( "tb_customers", array( 'id' => $custid ) );
                    if ( $getcustomer_code->num_rows() > 0 ) {
                        $party['customer_code'] = $getcustomer_code->row()->code;
                    }
                }
                $chk = $this->db->select( 'id' )->get_where( 'tbl_party_master', array( 'code' => $post['party_id'] ) );
                if ( $chk->num_rows() > 0 ) {
                    $party_id = $chk->row()->id;
                    $upd      = $this->db->where( array( 'id' => $party_id ) )->update( "tbl_party_master", $party );
                } else {

                    $party['party_type_id'] = $role_id;
                    $ins                    = $this->db->insert( "tbl_party_master", $party );
                    $party_id               = $this->db->insert_id();
                }

                $data = array( 'party_id' => $party_id );
            } else {
                $party_id = $id;
                $upd      = $this->db->where( array( 'id' => $party_id ) )->update( "tbl_party_master", $party );
                if ( $order_id != "0" ) {
                    $chkorderparty = $this->db->select( "id" )->get_where( "tb_order_parties", array( 'order_id' => $order_id, 'party_id' => $party_id ) );
                    if ( $chkorderparty->num_rows() > 0 ) {
                        $rowid = $chkorderparty->row()->id;
                        if ( $role_id != "0" ) {
                            $upd = $this->db->where( array( 'id' => $rowid ) )->update( "tb_order_parties", array( 'party_type' => $role_id ) );
                        }
                    }
                }
                $data = array( 'party_id' => $party_id );
            }
            echo json_encode( $data );
        }
    }

    public function getorderinvolvedparties()
    {
        $parties = [];
        $shiftId = $zeroValue = 0;
        $orderID = $_REQUEST['order_id'] ?? "";
        $customerID = $this->session->userdata("cust_id");
        if (!empty($orderID)) {
            $getTripDetails = $this->db->query("SELECT shift_id FROM tb_orders WHERE id =? AND status >? ",[$orderID,0]);
            if($getTripDetails->num_rows() >0){
                $shiftId = $getTripDetails->row()->shift_id > 0 ? $getTripDetails->row()->shift_id : 0;
            }
            $getParties = $this->db->query(
                "SELECT m.id as party_master_id,m.name as username,m.email as emailid,m.mobile as mobile,m.location_id as city,m.state,m.street as street,m.pincode as zipcode,m.country,m.partyindetifier,m.code,m.fax,p.name,p.id as party_type_id,p.name as party_name,p.company_code,p.branch_code,t.id as party_id FROM tbl_party_master m,tbl_party_types p,tb_order_parties t WHERE t.order_id=? AND t.status =? AND m.id=t.party_id AND t.party_type=p.id GROUP BY t.party_type ORDER BY m.id DESC"
                ,[$orderID,1]);
            if ($getParties->num_rows() > 0) {
                foreach ($getParties->result() as $res) {
                    $partyName = $res->party_name;
                    $id = '"' . $res->party_master_id . '"';
                    $code = '"' . $res->code . '"';
                    $name = '"' . $res->username . '"';
                    $street = '"' . $res->street . '"';
                    $emailid = '"' . $res->emailid . '"';
                    $state = '"' . $res->state . '"';
                    $country = '"' . $res->country . '"';
                    $fax = '"' . $res->fax . '"';
                    $city = '"' . $res->city . '"';
                    $role = '"' . $partyName . '"';
                    $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown-toggle' data-toggle='dropdown' href='#'><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'><li><a id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowPartyEdit(this," . $id . "," . $code . "," . $name . "," . $street . "," . $emailid . "," . $res->mobile . "," . $state . "," . $country . "," . $res->zipcode . "," . $fax . "," . $city . "," . $role . "," . $orderID . ")'><span class='glyphicon glyphicon-pencil' > </span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='deletepartydetailswithorder(" . $id . ")'><span class='glyphicon glyphicon-trash'> </span>Remove<li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAddParty(this);'><span class='glyphicon glyphicon-plus' > </span>Add Parties</a></li></ul></li></ul>";
                    if (empty($customerID)) {
                        $chkCarrier = strtoupper($partyName) == "CARRIER" && $shiftId == 0 ? $zeroValue : 1;
                        if($chkCarrier >0){
                            $parties[] = [
                                'id' => $res->party_master_id,
                                'party_id' => $res->code,
                                'street' => $res->street,
                                'party_type' => $partyName,
                                'name' => $res->name,
                                'username' => $res->username,
                                'email' => $res->emailid,
                                'mobile' => $res->mobile,
                                'zipcode' => $res->zipcode,
                                'street' => $res->street,
                                'customeridentifier' => $res->code,
                                'partyindetifier' => $res->partyindetifier,
                                'fax' => $res->fax,
                                'code' => $res->code,
                                'name' => $res->name,
                                'city' => $res->city,
                                'state' => $res->state,
                                'country' => $res->country,
                                'company_code' => $res->company_code,
                                'branch_code' => $res->branch_code,
                                'action' => $action
                            ];
                        }

                    } else {
                        if (strtoupper($partyName) != 'CARRIER') {
                            $parties[] = [
                                'id' => $res->party_master_id,
                                'party_id' => $res->code,
                                'street' => $res->street,
                                'party_type' => $partyName,
                                'name' => $res->name,
                                'username' => $res->username,
                                'email' => $res->emailid,
                                'mobile' => $res->mobile,
                                'zipcode' => $res->zipcode,
                                'street' => $res->street,
                                'customeridentifier' => $res->code,
                                'partyindetifier' => $res->partyindetifier,
                                'fax' => $res->fax,
                                'code' => $res->code,
                                'name' => $res->name,
                                'city' => $res->city,
                                'state' => $res->state,
                                'country' => $res->country,
                                'company_code' => $res->company_code,
                                'branch_code' => $res->branch_code,
                                'action' => $action
                            ];
                        }
                    }
                }
            }
        }
        echo json_encode($parties);
    }

    public function showinvolvedparties() {

        $user_id      = $this->session->userdata( 'user_id' );
        $parties      = $ids = array();
        $party_row_id = isset( $_POST['party_row_id'] ) ? $_POST['party_row_id'] : "";
        if ( $party_row_id != "" ) {
            $ids = implode( ',', $party_row_id );
            if ( ! empty( $ids ) ) {
                $getparties = $this->db->query( "SELECT m.id as party_master_id,m.name as username,m.email as emailid,m.mobile as mobile,m.location_id as city,m.state,m.street as street,m.pincode as zipcode,m.country,m.partyindetifier,m.code,m.fax,m.code,p.id as party_type_id,p.name as party_type,p.company_code,p.branch_code FROM tbl_party_master m,tbl_party_types p WHERE m.id IN (" . $ids . ") AND m.party_type_id=p.id GROUP BY m.id ORDER BY m.id DESC" );
                if ( $getparties->num_rows() > 0 ) {
                    foreach ( $getparties->result() as $res ) {
                        $id = '"' . $res->party_master_id . '"';
                        $code = '"' . $res->code . '"';
                        $name = '"' . $res->username . '"';
                        $street = '"' . $res->street . '"';
                        $emailid = '"' . $res->emailid . '"';
                        $state = '"' . $res->state . '"';
                        $country = '"' . $res->country . '"';
                        $fax = '"' . $res->fax . '"';
                        $city = '"' . $res->city . '"';
                        $role = '"' . $res->party_type . '"';
                        $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown-toggle' data-toggle='dropdown' href='#'><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'><li><a id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowPartyEdit(this," . $id . "," . $code . "," . $name . "," . $street . "," . $emailid . "," . $res->mobile . "," . $state . "," . $country . "," . $res->zipcode . "," . $fax . "," . $city . "," . $role . ")'><span class='glyphicon glyphicon-pencil' > </span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='rowPartyElim(this," . $id . ")'><span class='glyphicon glyphicon-trash'> </span>Remove<li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAddParty(this);'><span class='glyphicon glyphicon-plus' > </span>Add Parties</a></li></ul></li></ul>";

                        $parties[] = array(
                            'party_id' => $res->code,
                            'party_type' => $res->party_type,
                            'party_type_id' => $res->party_type_id,
                            'street' => $res->street,
                            'username' => $res->username,
                            'email' => $res->emailid,
                            'mobile' => $res->mobile,
                            'zipcode' => $res->zipcode,
                            'street'             => $res->street,
                            'customeridentifier' => $res->code,
                            'partyindetifier'    => $res->partyindetifier,
                            'fax'                => $res->fax,
                            'code'               => $res->code,
                            'city'               => $res->city,
                            'state'              => $res->state,
                            'country'            => $res->country,
                            'company_code'       => $res->company_code,
                            'branch_code'        => $res->branch_code,
                            'action'             => $action
                        );
                    }
                }
            }
        }
        echo json_encode( $parties );
    }

    public function editpartydetails() {
        $id      = $this->input->post( 'id' );
        $parties = array();
        $chk     = $this->db->select( 'id' )->get_where( "tbl_party_master", array( 'id' => $id ) );
        if ( $chk->num_rows() > 0 ) {
            $get_parties = $this->db->query( "SELECT m.id,m.party_type_id,m.name,m.email,m.mobile,m.location_id,m.street,m.state,m.fax,m.address,m.pincode,m.country,m.user_id,m.customeridentifier,p.id as party_type_id FROM tbl_party_master m,tbl_party_types p WHERE m.id='" . $id . "' AND p.id=m.party_type_id ORDER BY m.id DESC" );
            if ( $get_parties->num_rows() > 0 ) {
                $parties = array(
                    'name'    => $get_parties->row()->name,
                    'street'  => $get_parties->row()->street,
                    'zipcode' => $get_parties->row()->pincode,
                    'city'    => $get_parties->row()->location_id,
                    'country' => $get_parties->row()->country,
                    'state'   => $get_parties->row()->state,
                    'phone'   => $get_parties->row()->mobile,
                    'email'   => $get_parties->row()->email,
                    'fax'     => $get_parties->row()->fax,
                    'code'    => $get_parties->row()->customeridentifier,
                    'type_id' => $get_parties->row()->party_type_id
                );
            }
        }
        echo json_encode( $parties );
    }

    public function additem() {
        $cdate              = date( 'y-m-d H:i:s' );
        $post               = $this->input->post();
        $item_id            = $post['item_id'];
        $item_name          = $post['item_name'];
        $description        = $post['description'];
        $user_id            = $this->session->userdata( 'user_id' );
        $length             = isset( $post['length'] ) ? $post['length'] : "0";
        $width              = isset( $post['width'] ) ? $post['width'] : "0";
        $weight             = isset( $post['weight'] ) ? $post['weight'] : "0";
        $height             = isset( $post['height'] ) ? $post['height'] : "0";
        $volume             = isset( $post['volume'] ) ? $post['volume'] : "0";
        $second_volume      = isset( $post['second_volume'] ) ? $post['second_volume'] : "0";
        $second_weight      = isset( $post['second_weight'] ) ? $post['second_weight'] : "0";
        $volumentric_weight = isset( $post['volumentric_weight'] ) ? $post['volumentric_weight'] : "0";
        $volumentric_weight = isset( $post['volumentric_weight'] ) ? $post['volumentric_weight'] : "0";
        $secondvolume_uom   = isset( $post['secondvolume_uom'] ) ? $post['secondvolume_uom'] : "cbm";
        $item_number = isset($post['item_number']) ? $post['item_number'] : "";
        $hsn_code = isset($post['hsn_code']) ? $post['hsn_code'] : "";
        $color_code = isset($post['color_code']) ? $post['color_code'] : "";
        $color_code_name = isset($post['color_code_name']) ? $post['color_code_name'] : "";
        $size_code = isset($post['size_code']) ? $post['size_code'] : "";
        $size_code_name = isset($post['size_code_name']) ? $post['size_code_name'] : "";
        $unit_price = isset($post['unit_price']) ? $post['unit_price'] : 0.00;
        if ( $secondvolume_uom == "" ) {
            $secondvolume_uom = 'cbm';
        }
        $secondweight_uom = isset( $post['secondweight_uom'] ) ? $post['secondweight_uom'] : "kg";
        if ( $secondweight_uom == "" ) {
            $secondweight_uom = 'kg';
        }
        if ( $length == "" ) {
            $length = 0;
        }
        if ( $second_volume == "" ) {
            $second_volume = 0;
        }
        if ( $second_weight == "" ) {
            $second_weight = 0;
        }
        if ( $width == "" ) {
            $width = 0;
        }
        if ( $weight == "" ) {
            $weight = 0;
        }
        if ( $height == "" ) {
            $height = 0;
        }
        if ( $volume == "" ) {
            $volume = 0;
        }
        if ( $volumentric_weight == "" ) {
            $volumentric_weight = 0;
        }
        $ins_ar = array(
            'item_id'           => $item_id,
            'item_name'         => $item_name,
            'description'       => $description,
            'status'            => '1',
            'createdby'         => $user_id,
            'length'            => $length,
            'length_unit'       => $post['length_uom'],
            'width'             => $width,
            'width_unit'        => $post['width_uom'],
            'weight'            => $weight,
            'weight_unit'       => $post['weight_uom'],
            'height'            => $height,
            'height_unit'       => $post['height_uom'],
            'volume'            => $volume,
            'volume_unit'       => $post['volume_uom'],
            'volumetric_weight' => $volumentric_weight,
            'volweight_uom'     => $post['volumeticweight_uom'],
            'second_volume'     => $second_volume,
            'second_weight'     => $second_weight,
            'secondweight_uom'  => $secondweight_uom,
            'secondvolume_uom'  => $secondvolume_uom,
            'item_number' => $item_number,
            'hsn_code' => $hsn_code,
            'color_code' => $color_code,
            'color_code_name' => $color_code_name,
            'size_code' => $size_code,
            'size_code_name' => $size_code_name,
            'unit_price' => $unit_price
        );
        $chk = $this->db->select('id')->get_where('tb_items', $ins_ar);
        if ($chk->num_rows() == 0) {
            $ins = $this->common->insertTableData('tb_items', $ins_ar);
            if ($ins) {
                $ins_id = $ins;
                $ins_type = 'ins';
            } else {
                $ins_id = 0;
                $ins_type = '';
            }
        } else {
            $ins_id = $chk->row()->id;
            $ins_type = 'upd';
        }
        $res = array( 'id' => $ins_id, 'ins' => $ins_type );
        echo json_encode( $res );
    }

    public function getitemid() {

        $post        = $this->input->post();
        $term        = $post['term'];
        $result      = array();
        $whr         = "";
        $outer_cargo = isset( $_POST['outer_cargo'] ) ? $_POST['outer_cargo'] : "";
        if ( $outer_cargo != "" ) {
            $whr .= " AND item_id NOT LIKE '" . $outer_cargo . "' ";
        }
        $whr1 = $whr2 = "";
        if ( $this->session->userdata( 'cust_id' ) !== FALSE ) {
            $custid           = $this->session->userdata( 'cust_id' );
            $ironmountain_ids = array( '415', '187', '188', '192', '226', '428', '431', '430', '426', '427', '418', '417', '429', '419', '423', '416', '422', '425', '420', '424', '489', '421' );
            if ( $custid != "" && $custid != '0' ) {
                if ( in_array( $custid, $ironmountain_ids ) ) {
                    $whr1 = "AND item_id IN ('Docs','Non-Docs') ";
                }
                $company_code = $this->session->userdata( 'company_code' );
                if ( $company_code == "NZKN" ) {
                    $whr2 = " AND description LIKE 'APPLIANCES' ";
                }
            }
        }
        $getitemname = $this->db->query( "SELECT id,item_id FROM tb_items WHERE item_id LIKE '%" . $term . "%' " . $whr . " " . $whr1 . " " . $whr2 . " ORDER BY createdon DESC" );
        if ( $getitemname->num_rows() > 0 ) {
            foreach ( $getitemname->result() as $res ) {
                $result[] = array( 'id' => $res->id, 'item_id' => $res->item_id );
            }
        }
        echo json_encode( $result );

    }

    public function searchviewitem() {

        $post        = $this->input->post();
        $term        = $post['term'];
        $result      = array();
        $getitemname = $this->db->query( "SELECT * FROM tb_items WHERE item_id LIKE '%" . $term . "%' GROUP BY id ORDER BY createdon DESC" );
        if ( $getitemname->num_rows() > 0 ) {
            foreach ( $getitemname->result() as $res ) {
                $second_weight = $res->second_weight;
                $second_volume = $res->second_volume;
                if ( $second_weight == "" ) {
                    $second_weight = 0;
                }
                if ( $second_volume == "" ) {
                    $second_volume = 0;
                }
                $check    = "<input type='radio' name='listitem' id='listitem_" . $res->id . "' class='listitem' onchange='selectitem(" . $res->id . ")' value='" . $res->id . "'>";
                $result[] = array(
                    'check'             => $check,
                    'id'                => $res->id,
                    'item_id'           => $res->item_id,
                    'item_name'         => $res->item_name,
                    'description'       => $res->description,
                    'length'            => $res->length . $res->length_unit,
                    'width'             => $res->width . $res->width_unit,
                    'height'            => $res->height . $res->height_unit,
                    'weight'            => $res->weight . $res->weight_unit,
                    'volume'            => $res->volume . $res->volume_unit,
                    'volumetric_weight' => $res->volumetric_weight . $res->volweight_uom,
                    'second_weight'     => $second_weight . $res->secondweight_uom,
                    'second_volume'     => $second_volume . $res->secondvolume_uom
                );
            }
        }
        echo json_encode( $result );

    }

    public function finditembyid() {
        $post        = $this->input->post();
        $term        = $post['item'];
        $result      = array();
        $getitemname = $this->db->query( "SELECT * FROM tb_items WHERE item_id LIKE '%" . $term . "%' GROUP BY id ORDER BY createdon DESC" );
        if ( $getitemname->num_rows() > 0 ) {
            foreach ( $getitemname->result() as $res ) {
                $second_weight = $res->second_weight;
                $second_volume = $res->second_volume;
                if ( $second_weight == "" ) {
                    $second_weight = 0;
                }
                if ( $second_volume == "" ) {
                    $second_volume = 0;
                }
                $check    = "<input type='radio' name='listitem' id='listitem_" . $res->id . "' class='listitem' onchange='selectitem(" . $res->id . ")' value='" . $res->item_id . "'>";
                $result[] = array(
                    'check'         => $check,
                    'id'            => $res->id,
                    'item_id'       => $res->item_id,
                    'item_name'     => $res->item_name,
                    'description'   => $res->description,
                    'length'        => $res->length . $res->length_unit,
                    'width'         => $res->width . $res->width_unit,
                    'height'        => $res->height . $res->height_unit,
                    'weight'        => $res->weight . $res->weight_unit,
                    'volume'        => $res->volume . $res->volume_unit,
                    'second_weight' => $second_weight . $res->secondweight_uom,
                    'second_volume' => $second_volume . $res->secondvolume_uom
                );
            }
        }
        echo json_encode( $result );
    }

    public function viewitemslist() {
        $items = array();
        $type  = isset( $_POST['ctype'] ) ? $_POST['ctype'] : "";
        $popup = isset( $_POST['popup'] ) ? $_POST['popup'] : "";
        $whr   = "";
        if ( $type != "" ) {
            $whr .= " AND item_id NOT LIKE '%" . $type . "%'";
        }
        $check = $whr1 = $whr2 = "";
        if ( $this->session->userdata( 'cust_id' ) !== FALSE ) {
            $custid           = $this->session->userdata( 'cust_id' );
            $ironmountain_ids = array( '415', '187', '188', '192', '226', '428', '431', '430', '426', '427', '418', '417', '429', '419', '423', '416', '422', '425', '420', '424', '489', '421' );
            if ( $custid != "" && $custid != '0' ) {
                if ( in_array( $custid, $ironmountain_ids ) ) {
                    $whr1 = "AND item_id IN ('Docs','Non-Docs') ";
                }
                $company_code = $this->session->userdata( 'company_code' );
                if ( $company_code == 'NZKN' ) {
                    $whr2 = " AND description LIKE 'APPLIANCES' ";
                }
            }
        }
        $this->load->model( 'quickbook_model' );
        $whereCondition =  $this->quickbook_model->getPackagesWhereCondtion();
        $qry = $this->db->query("SELECT * FROM tb_items WHERE status='1'" . $whr . " " . $whr1 . " " . $whr2 . " " . $whereCondition . "  GROUP BY id ORDER BY id DESC");

        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                $second_weight = $res->second_weight;
                $second_volume = $res->second_volume;
                if ( $second_weight == "" ) {
                    $second_weight = 0;
                }
                if ( $second_volume == "" ) {
                    $second_volume = 0;
                }
                $check   = "<input type='radio' name='listitem' id='listitem_" . $res->id . "' class='listitem' onchange='selectitem(" . $res->id . ")' value='" . $res->id . "'>";
                $items[] = array(
                    'check'              => $check,
                    'item_name'          => $res->item_name,
                    'item_id'            => $res->item_id,
                    'description'        => $res->description,
                    'length'             => $res->length . $res->length_unit,
                    'width'              => $res->width . $res->width_unit,
                    'height'             => $res->height . $res->height_unit,
                    'weight'             => $res->weight . $res->weight_unit,
                    'volume'             => $res->volume . $res->volume_unit,
                    'volumentric_weight' => $res->volumetric_weight . $res->volweight_uom,
                    'second_weight'      => $second_weight . $res->secondweight_uom,
                    'second_volume'      => $second_volume . $res->secondvolume_uom
                );
            }
        }
        echo json_encode( $items );
    }

    public function getitemdetailsbyId() {

        $items   = array();
        $item_id = $_POST['item_id'];
        $qry     = $this->db->query( "SELECT * FROM tb_items WHERE status='1' and item_id LIKE '" . $item_id . "' ORDER BY createdon DESC" );
        if ( $qry->num_rows() > 0 ) {
            foreach ( $qry->result() as $res ) {
                $second_weight = $res->second_weight;
                $second_volume = $res->second_volume;
                if ( $second_weight == "" ) {
                    $second_weight = 0;
                }
                if ( $second_volume == "" ) {
                    $second_volume = 0;
                }
                $items[] = array(
                    'item_name'     => $res->item_name,
                    'item_id'       => $res->item_id,
                    'description'   => $res->description,
                    'length'        => $res->length,
                    'length_uom'    => $res->length_unit,
                    'width'         => $res->width,
                    'width_uom'     => $res->width_unit,
                    'height'        => $res->height,
                    'height_uom'    => $res->height_unit,
                    'weight'        => $res->weight,
                    'weight_uom'    => $res->weight_unit,
                    'volume'        => $res->volume,
                    'volume_uom'    => $res->volume_unit,
                    'second_weight' => $second_weight . $res->secondweight_uom,
                    'second_volume' => $second_volume . $res->secondvolume_uom
                );
            }
        }
        echo json_encode( $items );

    }

    public function getitemdetailslist() {
        $items = $post = array();
        $post = $this->input->post(NULL, TRUE);
        $item_id = isset($post['item_id']) ? $post['item_id'] : "";
        if ( $item_id != "" ) {
            $qry = $this->db->query( "SELECT * FROM tb_items WHERE status='1' and id = '" . $item_id . "' ORDER BY createdon DESC" );
            if ( $qry->num_rows() > 0 ) {
                foreach ( $qry->result() as $res ) {
                    $second_weight = $res->second_weight;
                    $second_volume = $res->second_volume;
                    if ( $second_weight == "" ) {
                        $second_weight = 0;
                    }
                    if ( $second_volume == "" ) {
                        $second_volume = 0;
                    }
                    $items[] = array(
                        'item_name'         => $res->item_name,
                        'item_id'           => $res->item_id,
                        'description'       => $res->description,
                        'length'            => $res->length,
                        'length_uom'        => ucfirst( $res->length_unit ),
                        'width'             => $res->width,
                        'width_uom'         => ucfirst( $res->width_unit ),
                        'height'            => $res->height,
                        'height_uom'        => ucfirst( $res->height_unit ),
                        'weight'            => $res->weight,
                        'weight_uom'        => ucfirst( $res->weight_unit ),
                        'volume'            => $res->volume,
                        'volume_uom'        => ucfirst( $res->volume_unit ),
                        'volumetric_weight' => $res->volumetric_weight,
                        'volweight_uom'     => ucfirst( $res->volweight_uom ),
                        'second_volume'     => $second_volume,
                        'second_weight'     => $second_weight,
                        'secondweight_uom'  => ucfirst( $res->secondweight_uom ),
                        'secondvolume_uom'  => ucfirst( $res->secondvolume_uom ),
                        'item_num_id' => $res->id,
                        'item_number' => $res->item_number,
                        'hsn_code' => $res->hsn_code,
                        'color_code' => $res->color_code,
                        'color_code_name' => $res->color_code_name,
                        'size_code' => $res->size_code,
                        'size_code_name' => $res->size_code_name,
                        'unit_price' => $res->unit_price
                    );
                }
            }
        }

        echo json_encode( $items );

    }

    public function getordercargodetails() {
        $cargos   = array();
        $order_id = isset( $_POST['order_id'] ) ? $_POST['order_id'] : "";
        if ( $order_id != "" ) {
            $qry = $this->db->query( "SELECT c.id,c.cargo_type,c.length_unit,c.width_unit,c.height_unit,c.weight_unit,c.volume_unit,c.secondweight_uom,c.secondvolume_uom,c.goods_description,c.stackable,c.grounded,c.splittable,c.dg_goods,o.id as ordcargoid,o.length,o.width,o.height,o.weight,o.second_weight,o.volume,o.second_volume,o.volumetric_weight,o.volweight_uom,c.ldm,o.quantity,o.scanned_quantity,o.qr_code,o.reference_order_num FROM tb_cargo_details c,tb_order_cargodetails o WHERE o.order_id ='" . $order_id . "' AND o.cargo_id=c.id AND o.status=1 GROUP BY c.id ORDER BY c.id DESC" );

            if ( $qry->num_rows() > 0 ) {
                $totalqty = count( $qry->result() );
                $i        = 0;
                foreach ( $qry->result() as $res ) {
                    $i ++;
                    $stackable = 'Off';
                    if ( $res->stackable == 0 ) {
                        $stackable = 'Off';
                    } else if ( $res->stackable == 1 ) {
                        $stackable = 'On';
                    }
                    $grounded = 'Off';
                    if ( $res->grounded == 0 ) {
                        $grounded = 'Off';
                    } else if ( $res->grounded == 1 ) {
                        $grounded = 'On';
                    }
                    $splittable = 'Off';
                    if ( $res->splittable == 0 ) {
                        $splittable = 'Off';
                    } else if ( $res->splittable == 1 ) {
                        $splittable = 'On';
                    }
                    $dg_goods = ($res->dg_goods == 1) ? 'Yes' : 'No';
                    $cargo_type       = '"' . $res->cargo_type . '"';
                    $goods_desc       = '"' . $res->goods_description . '"';
                    $length_unit      = '"' . $res->length_unit . '"';
                    $width_unit       = '"' . $res->width_unit . '"';
                    $height_unit      = '"' . $res->height_unit . '"';
                    $weight_unit      = '"' . $res->weight_unit . '"';
                    $volume_unit      = '"' . $res->volume_unit . '"';
                    $volweight_uom    = '"' . $res->volweight_uom . '"';
                    $secondweight_uom = '"' . $res->secondweight_uom . '"';
                    $secondvolume_uom = '"' . $res->secondvolume_uom . '"';
                    $scanned_quantity = $res->scanned_quantity;
                    $second_weight    = $res->second_weight;
                    $second_volume    = $res->second_volume;
                    if ( $scanned_quantity == "" ) {
                        $scanned_quantity = 0;
                    }
                    if ( $second_volume == "" ) {
                        $second_volume = 0;
                    }
                    if ( $second_weight == "" ) {
                        $second_weight = 0;
                    }
                    if ( $scanned_quantity == 0 ) {
                        $alertmsg = "'There is no Labels Scanned for this cargo..!'";
                        $label    = '<a href="#" onclick="alert(' . $alertmsg . ')"><span class="icon tru-icon-pdf"></span></a>';
                    } else {
                        $label = '<a href="' . base_url( "aulabel/index?order_car_id=" . $res->ordcargoid . "&tot=" . $totalqty . "&cargo_row_id=" . $i ) . '" target="_blank" title="' . $this->lang->line( 'print_label' ) . '"><span class="icon tru-icon-pdf"></span></a>';
                    }

                    $volumetric_weight = $res->volumetric_weight;
                    if($volumetric_weight == ""){
                        $volumetric_weight = 0;
                    }
                    $ldm = $res->ldm;
                    if($ldm == ""){
                        $ldm = 0;
                    }
                    $qrcode = $res->qr_code;
                    if ( ($this->session->userdata( 'company_code' ) == "NZKN" || $this->session->userdata( 'company_code' ) == "NZPG") && $this->session->userdata( 'cust_id' ) != "" ) {
                        $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft '> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcuscargoEdit(this," . $res->id . "," . $cargo_type . "," . $goods_desc . "," . $res->quantity . "," . $res->length . "," . $res->width . "," . $res->height . "," . $res->weight . "," . $res->volume . "," . $volumetric_weight . "," . $res->stackable . "," . $res->grounded . "," . $res->splittable . "," . $res->dg_goods . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scanned_quantity . "," . $second_weight . "," . $secondweight_uom . "," . $second_volume . "," . $secondvolume_uom . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='deleteordercargodetails(" . $res->id . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $res->id . ")'><span class='fa fa-archive' > </span>Get Inner Cargos</a></li>";

                        $empty    = "";
                        $cargos[] = array(
                            'id'                  => $res->id,
                            'cargo_type'          => $res->cargo_type,
                            'goods_desc'          => $res->goods_description,
                            'quantity'            => $res->quantity,
                            'length'              => $res->length . " " . $res->length_unit,
                            'width'               => $res->width . " " . $res->width_unit,
                            'height'              => $res->height . " " . $res->height_unit,
                            'weight'              => $res->weight . " " . $res->weight_unit,
                            'volume'              => $res->volume . " " . $res->volume_unit,
                            'volumetric_weight'   => $volumetric_weight . " " . $res->volweight_uom,
                            'stackable'           => $stackable,
                            'splittable'          => $splittable,
                            'grounded'            => $grounded,
                            'action'              => $action,
                            'empty'               => $empty,
                            'dg_goods'            => $dg_goods,
                            "ldm"                 => $ldm,
                            'scanned_quantity'    => $scanned_quantity,
                            'qrcode'              => $qrcode,
                            'label'               => $label,
                            'reference_order_num' => $res->reference_order_num,
                            'second_weight'       => $second_weight . " " . $res->secondweight_uom,
                            'second_volume'       => $second_volume . " " . $res->secondvolume_uom
                        );

                    } else {
                        $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft '> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a data-ordertype='editOrder' id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcargoEdit(this," . $res->id . "," . $cargo_type . "," . $goods_desc . "," . $res->quantity . "," . $res->length . "," . $res->width . "," . $res->height . "," . $res->weight . "," . $res->volume . "," . $volumetric_weight . "," . $res->stackable . "," . $res->grounded . "," . $res->splittable . "," . $res->dg_goods . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scanned_quantity . "," . $second_weight . "," . $secondweight_uom . "," . $second_volume . "," . $secondvolume_uom . "," . (!empty($qrcode) ? $qrcode : 0) . "," . $order_id . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='deleteordercargodetails(" . $res->id . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $res->id . ")'><span class='fa fa-archive' > </span>Get Inner Cargos</a></li>";
                        $empty = "";
                        $cargos[] = array(
                            'id' => $res->id,
                            'cargo_type' => $res->cargo_type,
                            'goods_desc' => $res->goods_description,
                            'quantity' => $res->quantity,
                            'length' => $res->length . " " . $res->length_unit,
                            'width' => $res->width . " " . $res->width_unit,
                            'height' => $res->height . " " . $res->height_unit,
                            'weight' => $res->weight . " " . $res->weight_unit,
                            'volume' => $res->volume . " " . $res->volume_unit,
                            'volumetric_weight'   => $volumetric_weight . " " . $res->volweight_uom,
                            'stackable'           => $stackable,
                            'splittable'          => $splittable,
                            'grounded'            => $grounded,
                            'action'              => $action,
                            'empty'               => $empty,
                            'dg_goods'            => $dg_goods,
                            "ldm"                 => $ldm,
                            'scanned_quantity'    => $scanned_quantity,
                            'qrcode'              => $qrcode,
                            'label'               => $label,
                            'reference_order_num' => $res->reference_order_num,
                            'second_weight'       => $second_weight . " " . $res->secondweight_uom,
                            'second_volume'       => $second_volume . " " . $res->secondvolume_uom
                        );
                    }
                }
            }

        }
        echo json_encode( $cargos );
    }

    public function deleteorder(int $id): void
    {
        if ($id > 0) {
            $deleteOrder = $this->Order->deleteOrderById($id);
            if ($deleteOrder) {
                $refs = new OrderReference();
                $refs->deleteForOrder($id, ['DQ']);
                $this->ordernotify('booking_delete', $id);
            }
        }
        echo "1";
    }

    public function deleteordercargodetails()
    {
        $order_id = isset($_POST['order_id']) ? $_POST['order_id'] : '0';
        $cargo_id = isset($_POST['cargo_id']) ? $_POST['cargo_id'] : '0';
        $cargoid['order_cargo_id'] = '';
        if ($order_id != '0' && $cargo_id != '0') {
            $chk = $this->db->select('id')->get_where('tb_order_cargodetails', ['order_id' => $order_id, 'cargo_id' => $cargo_id]);
            if ($chk->num_rows() > 0) {
                $row_id = $chk->row()->id;
                $upd = $this->db->where(['id' => $row_id])->update('tb_order_cargodetails', ['status' => '0']);
                if ($upd) {
                    $cargochk = $this->db->select('cargo_id')->get_where('tb_order_cargodetails', ['order_id' => $order_id, 'status' => '1']);
                    if ($cargochk->num_rows() > 0) {
                        $cargoid['order_cargo_id'] = $cargochk->row()->cargo_id;
                    }
                }
            }
        }
        echo json_encode($cargoid);
    }

    public function showcargodetails()
    {
        $cargos = [];
        $postIds = $this->db->escape_str($_POST['cargo_id']) ?? "";
        $type = $_POST['type'] ?? "";
        $order_id = $_POST['order_id'] ?? 0;
        $companyCode = $this->session->userdata('company_code');
        $marksAndNumbersCondition = checkAccessConditions('MARKS_AND_NUMBERS_OPTION', $companyCode);
        if (!empty($postIds)) {
            $getCargos = $this->common->gettbldata("id IN (" . implode(',', $postIds) . ") and status ='1'","*","tb_cargo_details",0,0);
            if (!empty($getCargos)) {
                if ($type == 'popup') {
                    foreach ($getCargos as $eachRow) {
                        $qrcode = "";
                        $qrcodeqry = $this->common->gettblrowdata(["cargo_id" => $eachRow['id'], "qr_code <>" => ""], "qr_code", "tb_order_cargodetails", 0, 0);
                        if (!empty($qrcodeqry)) {
                            $qrcode = $qrcodeqry['qr_code'];
                        }
                        $stackable = ($eachRow['stackable'] == 1) ? 'On' : 'Off';
                        $grounded = ($eachRow['grounded'] == 1) ? 'On' : 'Off';
                        $splittable = ($eachRow['splittable'] == 1) ? 'On' : 'Off';
                        $dgGoods = ($eachRow['dg_goods'] == 1) ? "<span title='Click To Get Dgoods' onclick = 'getDangerousGoodsDetails(" . $eachRow['dg_goods'] . "," . $eachRow['id'] . ",0)' style='cursor:pointer;'>On</span>" : "No";
                        $secondVolume = $eachRow['second_volume'] ?: 0;
                        $secondWeight = $eachRow['second_weight'] ?: 0;
                        $volumetricWeight = $eachRow['volumetric_weight'] ?: 0;
                        $ldm = $eachRow['ldm'] ?: 0;
                        $action = "<button id=" . $eachRow['id'] . " class='btn btn-xs' onclick='editpopupcargodetails(" . $eachRow['id'] . ",event)'><span class='icon tru-icon-edit' aria-hidden='true'></span></button> <button id=" . $eachRow['id'] . " class='btn btn-xs' onclick='deletepopupcargodetails(" . $eachRow['id'] . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>";
                        $cargos[] = [
                            'cargo_type' => $eachRow['cargo_type'],
                            'goods_desc' => $eachRow['goods_description'],
                            'quantity' => $eachRow['quantity'],
                            'qrcode' => $qrcode,
                            'length' => $eachRow['length'] . " " . $eachRow['length_unit'],
                            'width' => $eachRow['width'] . " " . $eachRow['width_unit'],
                            'height' => $eachRow['height'] . " " . $eachRow['height_unit'],
                            'weight' => $eachRow['weight'] . " " . $eachRow['weight_unit'],
                            'volume' => $eachRow['volume'] . " " . $eachRow['volume_unit'],
                            'volumentric_weight' => $volumetricWeight . " " . $eachRow['volweight_uom'],
                            'stackable' => $stackable,
                            'grounded' => $grounded,
                            'splittable' => $splittable,
                            'dg_goods' => $dgGoods,
                            'ldm' => $ldm,
                            'second_weight' => $secondWeight . " " . $eachRow['secondweight_uom'],
                            'second_volume' => $secondVolume . " " . $eachRow['secondvolume_uom'],
                            'action' => $action
                        ];
                    }
                } else {
                    foreach ($getCargos as $eachRow) {
                        $qrcode = "";
                        $qrcodeqry = $this->common->gettblrowdata(["cargo_id" => $eachRow['id'], "qr_code <>" => ""], "qr_code", "tb_order_cargodetails", 0, 0);
                        if (!empty($qrcodeqry)) {
                            $qrcode = $qrcodeqry['qr_code'];
                        }
                        $stackable = ($eachRow['stackable'] == 1) ? 'On' : 'Off';
                        $grounded = ($eachRow['grounded'] == 1) ? 'On' : 'Off';
                        $splittable = ($eachRow['splittable'] == 1) ? 'On' : 'Off';
                        $dgGoods = ($eachRow['dg_goods'] == 1) ? "<span title='Click To Get Dgoods' onclick = 'getDangerousGoodsDetails(" . $eachRow['dg_goods'] . "," . $eachRow['id'] . ",0)' style='cursor:pointer;'>On</span>" : "No";
                        $secondVolume = $eachRow['second_volume'] ?: 0;
                        $secondWeight = $eachRow['second_weight'] ?: 0;
                        $volumetricWeight = $eachRow['volumetric_weight'] ?: 0;
                        $ldm = $eachRow['ldm'] ?: 0;
                        $cargo_type = '"' . $eachRow['cargo_type'] . '"';
                        $goods_desc = '"' . $eachRow['goods_description'] . '"';
                        $length_unit = '"' . $eachRow['length_unit'] . '"';
                        $width_unit = '"' . $eachRow['width_unit'] . '"';
                        $height_unit = '"' . $eachRow['height_unit'] . '"';
                        $weight_unit = '"' . $eachRow['weight_unit'] . '"';
                        $volume_unit = '"' . $eachRow['volume_unit'] . '"';
                        $volweight_uom = '"' . $eachRow['volweight_uom'] . '"';
                        $secondweight_uom = '"' . $eachRow['secondweight_uom'] . '"';
                        $secondvolume_uom = '"' . $eachRow['secondvolume_uom'] . '"';
                        $scannedQuantity = 0;
                        $marks_numbers       = '"' . $eachRow['marks_numbers'] . '"';
                        if (($this->session->userdata('company_code') == "NZKN" || $this->session->userdata('company_code') == "NZPG") && $this->session->userdata('cust_id') != "") {
                            $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcuscargoEdit(this," . $eachRow['id'] . "," . $cargo_type . "," . $goods_desc . "," . $eachRow['quantity'] . "," . $eachRow['length'] . "," . $eachRow['width'] . "," . $eachRow['height'] . "," . $eachRow['weight'] . "," . $eachRow['volume'] . "," . $volumetricWeight . "," . $eachRow['stackable'] . "," . $eachRow['grounded'] . "," . $eachRow['splittable'] . "," . $eachRow['dg_goods'] . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scannedQuantity . "," . $secondWeight . "," . $secondweight_uom . "," . $secondVolume . "," . $secondvolume_uom . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='rowCargoElim(this," . $eachRow['id'] . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $eachRow['id'] . ")'><span class='fa fa-archive' > </span>Get Inner Cargo</a></li>";
                        } elseif ($marksAndNumbersCondition) {
                            $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a data-ordertype='newOrder' id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcargoEdit(this," . $eachRow['id'] . "," . $cargo_type . "," . $goods_desc . "," . $marks_numbers . "," . $eachRow['quantity'] . "," . $eachRow['length'] . "," . $eachRow['width'] . "," . $eachRow['height'] . "," . $eachRow['weight'] . "," . $eachRow['volume'] . "," . $volumetricWeight . "," . $eachRow['stackable'] . "," . $eachRow['grounded'] . "," . $eachRow['splittable'] . "," . $eachRow['dg_goods'] . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scannedQuantity . "," . $secondWeight . "," . $secondweight_uom . "," . $secondVolume . "," . $secondvolume_uom . "," . (!empty($qrcode) ? $qrcode : 0) . "," . $order_id . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='rowCargoElim(this," . $eachRow['id'] . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $eachRow['id'] . ")'><span class='fa fa-archive' > </span>Get Inner Cargo</a></li>";
                        } else {
                            $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a data-ordertype='newOrder' id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcargoEdit(this," . $eachRow['id'] . "," . $cargo_type . "," . $goods_desc . "," . "0" . "," . $eachRow['quantity'] . "," . $eachRow['length'] . "," . $eachRow['width'] . "," . $eachRow['height'] . "," . $eachRow['weight'] . "," . $eachRow['volume'] . "," . $volumetricWeight . "," . $eachRow['stackable'] . "," . $eachRow['grounded'] . "," . $eachRow['splittable'] . "," . $eachRow['dg_goods'] . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scannedQuantity . "," . $secondWeight . "," . $secondweight_uom . "," . $secondVolume . "," . $secondvolume_uom . "," . (!empty($qrcode) ? $qrcode : 0) . "," . $order_id . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='rowCargoElim(this," . $eachRow['id'] . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $eachRow['id'] . ")'><span class='fa fa-archive' > </span>Get Inner Cargo</a></li>";
                        }
                        $cargo = [
                            'id' => $eachRow['id'],
                            'cargo_type' => $eachRow['cargo_type'],
                            'goods_desc' => $eachRow['goods_description'],
                            'quantity' => $eachRow['quantity'],
                            'qrcode' => $qrcode,
                            'length' => $eachRow['length'] . " " . $eachRow['length_unit'],
                            'width' => $eachRow['width'] . " " . $eachRow['width_unit'],
                            'height' => $eachRow['height'] . " " . $eachRow['height_unit'],
                            'weight' => $eachRow['weight'] . " " . $eachRow['weight_unit'],
                            'volume' => $eachRow['volume'] . " " . $eachRow['volume_unit'],
                            'volumentric_weight' => $volumetricWeight . " " . $eachRow['volweight_uom'],
                            'stackable' => $stackable,
                            'splittable' => $splittable,
                            'grounded' => $grounded,
                            'dg_goods' => $dgGoods,
                            'ldm' => $ldm,
                            'action' => $action,
                            'scanned_quantity' => $scannedQuantity,
                            'second_weight' => $secondWeight . " " . $eachRow['secondweight_uom'],
                            'second_volume' => $secondVolume . " " . $eachRow['secondvolume_uom']
                        ];
                        if ($marksAndNumbersCondition) {
                            $cargo['marks_numbers'] = $eachRow['marks_numbers'];
                        }
                        $cargos[] = $cargo;
                    }
                }
            }
        }
        echo json_encode($cargos);
    }

    public function getinnercargo() {
        $cargos   = array();
        $cargo_id = $this->db->escape_str($this->input->post( 'cargo_id' ));
        if ( $cargo_id != "" || $cargo_id != 0 ) {
            $inner_qry = $this->db->query( "SELECT i.id as inner_id,i.cargo_type as inner_cargo,i.goods_description as inner_gd,i.quantity as inner_quantity,i.length as inner_length,i.length_unit as inner_lum,i.width as inner_width,i.width_unit as inner_wum,i.height as inner_height,i.height_unit as inner_hum,i.weight as inner_weight,i.weight_unit as inner_weum,i.volume as inner_volume,i.volume_unit as inner_vum,i.stackable as inner_stackable,i.ref_order_num FROM tb_inner_cargo i WHERE i.cargo_id='" . $cargo_id . "' AND i.status='1' GROUP BY i.id ORDER BY i.id DESC" );

            if ( $inner_qry->num_rows() > 0 ) {
                foreach ( $inner_qry->result() as $inner ) {
                    $stackable = 'Off';
                    if ( $inner->inner_stackable == 0 ) {
                        $stackable = 'Off';
                    } else if ( $inner->inner_stackable == 1 ) {
                        $stackable = 'On';
                    }
                    $cargo_type = '"' . $inner->inner_cargo . '"';
                    $goods_desc = '"' . $inner->inner_gd . '"';
                    /* $action     = "<ul class='nav nav-tabs'><li class='dropdown'> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowinnercargoEdit(this," . $inner->inner_id . "," . $cargo_type . "," . $goods_desc . "," . $inner->inner_quantity . "," . $inner->inner_length . "," . $inner->inner_width . "," . $inner->inner_height . "," . $inner->inner_weight . "," . $inner->inner_volume . ");'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default'  onclick='deleteinnercargopackage(" . $inner->inner_id . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='addinnercargo(this," . $cargo_id . ");'><span class='fa fa-archive' > </span>Inner Cargo</a></li>";*/
                    $action        = "";
                    $ref_order_num = $inner->ref_order_num;
                    $ref_order_num = ( ! empty( $ref_order_num ) ) ? ( $ref_order_num ) : "";
                    $cargos[]      = array(
                        'inner_id'        => $inner->inner_id,
                        'main_cargo_id'   => $cargo_id,
                        'ref_order_num'   => $ref_order_num,
                        'inner_cargo'     => $inner->inner_cargo,
                        'inner_gd'        => $inner->inner_gd,
                        'inner_quantity'  => $inner->inner_quantity,
                        'inner_width'     => uom_string($inner->inner_width, $inner->inner_wum),
                        'inner_height'    => uom_string($inner->inner_height, $inner->inner_hum),
                        'inner_length'    => uom_string($inner->inner_length, $inner->inner_lum),
                        'inner_weight'    => uom_string($inner->inner_weight, $inner->inner_weum),
                        'inner_volume'    => uom_string($inner->inner_volume, $inner->inner_vum),
                        'inner_stackable' => $stackable,
                        'action'          => $action
                    );
                }
            }
        }
        echo json_encode( $cargos );
    }

    public function deleteorderpartydetails() {
        $order_id = isset( $_POST['order_id'] ) ? $_POST['order_id'] : "0";
        $party_id = isset( $_POST['party_id'] ) ? $_POST['party_id'] : "0";
        if ( $order_id != '0' && $party_id != '0' ) {
            $getdata = $this->db->query( "SELECT id FROM tb_order_parties WHERE status='1' AND party_id='" . $party_id . "' AND order_id ='" . $order_id . "'" );
            if ( $getdata->num_rows() > 0 ) {
                $id  = $getdata->row()->id;
                $upd = $this->db->where( array( 'id' => $id ) )->update( "tb_order_parties", array( 'status' => 0 ) );
                if ( $upd ) {
                    echo "1";
                } else {
                    echo "0";
                }
            } else {
                echo "0";
            }
        }
    }
    /**
     * save cargo details, added additional items details
     *
     *
     *
     * @author    Developer Name external.ram.k@kuehne-nagel.com
     * @date      31-03-2021 14:00:00+05.30
     * @change    Asia
     * @param Array cargo request data
     * @return    Json
     */
    public function savecargo($id = null, $orderId = null)
    {
        $post = array();
        $post = $this->input->post(null, true);
        $cdate = date('Y-m-d H:i:s');
        $cargo_id = 0;
        $inner_id = $data = $inner = array();
        $user_id = $this->session->userdata('user_id');
        $stackable = isset($_POST['stackable']) ? $this->db->escape_str($_POST['stackable']) : "0";
        $grounded = isset($_POST['grounded']) ? $this->db->escape_str($_POST['grounded']) : "0";
        $splittable = isset($_POST['splittable']) ? $this->db->escape_str($_POST['splittable']) : "0";
        $dg_goods = isset($_POST['dg_goods']) ? $this->db->escape_str($_POST['dg_goods']) : "0";
        $length = isset($post['length']) ? $this->db->escape_str($post['length']) : "0.00";
        $width = isset($post['width']) ? $this->db->escape_str($post['width']) : "0.00";
        $height = isset($post['height']) ? $this->db->escape_str($post['height']) : "0.00";
        $weight = isset($post['weight']) ? $this->db->escape_str($post['weight']) : "0.00";
        $volume = isset($post['volume']) ? $this->db->escape_str($post['volume']) : "0.00";
        $ldm = isset($post['ldm']) ? $this->db->escape_str($post['ldm']) : "0.00";
        $itemid = isset($post['item_num_id']) ? $this->db->escape_str($post['item_num_id']) : 0;
        $secondweight = isset($post['secondweight']) ? $this->db->escape_str($post['secondweight']) : "0.00";
        $secondvolume = isset($post['secondvolume']) ? $this->db->escape_str($post['secondvolume']) : "0.00";
        $marks_numbers = isset($post['marks_numbers']) ? $this->db->escape_str($post['marks_numbers']) : "";
        $dgRowIds = $post['dgRowIds'] ?? [];
        if ( $ldm == "" || ! ( is_numeric( $ldm ) ) ) {
            $ldm = "0.00";
        }
        if ( $secondvolume == "" || ! ( is_numeric( $secondvolume ) ) ) {
            $secondvolume = "0.00";
        }
        if ( $secondweight == "" || ! ( is_numeric( $secondweight ) ) ) {
            $secondweight = "0.00";
        }
        $volumetric_weight = isset( $post['volumetric_weight'] ) ? $post['volumetric_weight'] : "0.00";
        if ( $volumetric_weight == "" || ! ( is_numeric( $volumetric_weight ) ) ) {
            $volumetric_weight = "0.00";
        }
        if ( $length == "" ) {
            $length = '0.00';
        }
        if ( $width == "" ) {
            $width = '0.00';
        }
        if ( $height == "" ) {
            $height = '0.00';
        }
        if ( $weight == "" ) {
            $weight = '0.00';
        }
        if ( $volume == "" ) {
            $volume = '0.00';
        }
        if ( $volumetric_weight == "" ) {
            $volumetric_weight = '0.00';
        }

        $cargo = array(
            'cargo_type'        => $this->db->escape_str($post['cargo_type']),
            'goods_description' => $this->db->escape_str($post['goods_desc']),
            'quantity'          => $this->db->escape_str($post['quantity']),
            'length'            => $length,
            'length_unit'       => $this->db->escape_str($post['length_uom']),
            'width'             => $width,
            'width_unit'        => $this->db->escape_str($post['width_uom']),
            'height'            => $height,
            'height_unit'       => $this->db->escape_str($post['height_uom']),
            'weight'            => $weight,
            'weight_unit'       => $this->db->escape_str($post['weight_uom']),
            'volume'            => $volume,
            'volume_unit'       => $this->db->escape_str($post['volume_uom']),
            'volumetric_weight' => $volumetric_weight,
            'volweight_uom'     => $this->db->escape_str($post['volweight_uom']),
            'stackable'         => $stackable,
            'grounded'          => $grounded,
            'splittable' => $splittable,
            'dg_goods' => $dg_goods,
            'createdby' => $user_id,
            'createdon' => $cdate,
            'ldm' => $ldm,
            'second_weight' => $secondweight,
            'second_volume' => $secondvolume,
            'secondvolume_uom' => $this->db->escape_str($post['secondvolume_uom']),
            'secondweight_uom' => $this->db->escape_str($post['secondweight_uom']),
            'marks_numbers'    => $marks_numbers
        );
        if ($id === null || $id === "0") {
            if ($itemid == "") {
                $cargochk = $this->common->gettblrowdata(
                    array("item_id" => $post['cargo_type']),
                    "id",
                    "tb_items",
                    0,
                    0
                );
                if (count($cargochk) > 0) {
                    $itemid = $cargochk['id'];
                }
            }
            if ($itemid != "") {
                $cargo['item_id'] = $itemid;
            }
            $ins = $this->db->insert("tb_cargo_details", $cargo);
            $cargo_id = $this->db->insert_id();
            $data = array('cargo_id' => $cargo_id, 'inner_cargo_id' => $inner_id);
        } else {
            $cargo_id = $id;
            $qr_code = "";
            if ($itemid == "") {
                $cargodetail = $this->common->gettblrowdata(
                    array("id" => $cargo_id),
                    "item_id",
                    "tb_cargo_details",
                    0,
                    0
                );
                if (count($cargodetail) > 0) {
                    $itemid = $cargodetail['item_id'];
                }
            }
            if($itemid != ""){
                $cargo['item_id'] = $itemid;
                $items = $this->common->gettblrowdata(array("id"=>$itemid),"item_number,hsn_code,color_code,color_code_name,size_code,size_code_name,unit_price","tb_items",0,0);
                if(count($items)>0){
                    $qr_code = $items['item_number'];
                }
            }
            $upd      = $this->db->where( array( 'id' => $cargo_id ) )->update( "tb_cargo_details", $cargo );
            $ordcargo = array(
                'length'            => $length,
                'width'             => $width,
                'height'            => $height,
                'weight'            => $weight,
                'volume'            => $volume,
                'quantity'          => $this->db->escape_str($post['quantity']),
                'quantity_type'     => $this->db->escape_str($post['cargo_type']),
                'cargo_content'     => $this->db->escape_str($post['goods_desc']),
                'volumetric_weight' => $volumetric_weight,
                'volweight_uom'     => $this->db->escape_str($post['volweight_uom']),
                'ldm'               => $ldm,
                'second_weight'     => $secondweight,
                'second_volume'     => $secondvolume,
                'marks_numbers'     => $marks_numbers
            );
            if($qr_code != ""){
                $ordcargo['qr_code'] = $qr_code;
            }
            $upd = $this->db->where( array( 'cargo_id' => $cargo_id ) )->update( "tb_order_cargodetails",$ordcargo);
            $data = array( 'cargo_id' => $cargo_id, 'inner_cargo_id' => $inner_id );
        }
        $order_id = isset( $_POST['order_forcargo'] ) ? $this->db->escape_str($_POST['order_forcargo']) : "0";
        if ($order_id == 0) {
            if ($dg_goods > 0) {
                foreach ($dgRowIds as $eachRowId) {
                    if ($eachRowId > 0) {
                        $this->common->updatetbledata("tb_order_dg_goods", ['order_cargo_id' => $cargo_id, 'order_id' => '0'], ['id' => $eachRowId]);
                    }
                }
            }
        }
        if ( $order_id > 0) {
            /*get item details*/
            $qr_code = $hsn_code = $color_code = $color_code_name = $size_code = $size_code_name = "";
            $unit_price = 0;
            $items = $this->common->gettblrowdata(array("id"=>$itemid),"item_number,hsn_code,color_code,color_code_name,size_code,size_code_name,unit_price","tb_items",0,0);
            if(count($items)>0){
                $qr_code = $items['item_number'];
                $hsn_code = $items['hsn_code'];
                $color_code = $items['color_code'];
                $color_code_name = $items['color_code_name'];
                $size_code = $items['size_code'];
                $size_code_name = $items['size_code_name'];
                $unit_price = $items['unit_price'];
            }
            $chk = $this->db->select( 'id' )->get_where( 'tb_order_cargodetails', array( 'order_id' => $order_id, 'cargo_id' => $cargo_id, 'status' => '1' ) );
            $gethandling_unit = $this->db->query( "SELECT id FROM tbl_shipunit_types WHERE unit_name LIKE '" . $post['cargo_type'] . "'" );
            $handling_unit    = "";
            if ( $gethandling_unit->num_rows() > 0 ) {
                $handling_unit = $gethandling_unit->row()->id;
            } else {
                $handlingunit_ar = array( 'unit_name' => $this->db->escape_str($post['cargo_type']), 'description' => $this->db->escape_str($post['cargo_type']), 'user_id' => $user_id, 'created_at' => $cdate, 'status' => '1' );
                $this->db->insert( "tbl_shipunit_types", $handlingunit_ar );
                $handling_unit = $this->db->insert_id();
            }
            if ( $chk->num_rows() == 0 ) {
                $ins = $this->db->insert( 'tb_order_cargodetails', array(
                    'order_id'          => $order_id,
                    'cargo_id'          => $cargo_id,
                    'status'            => '1',
                    'createdon'         => $cdate,
                    'length'            => $length,
                    'width'             => $width,
                    'height'            => $height,
                    'weight'            => $weight,
                    'volume'            => $volume,
                    'quantity'          => $this->db->escape_str($post['quantity']),
                    'quantity_type'     => $this->db->escape_str($post['cargo_type']),
                    'cargo_content'     => $this->db->escape_str($post['goods_desc']),
                    'handling_unit'     => $handling_unit,
                    'volumetric_weight' => $volumetric_weight,
                    'volweight_uom'     => $this->db->escape_str($post['volweight_uom']),
                    'ldm'               => $ldm,
                    'second_weight'     => $secondweight,
                    'second_volume'     => $secondvolume,
                    'qr_code'           => $qr_code,
                    'marks_numbers'     => $marks_numbers
                ) );
                $cargoId = $this->db->insert_id();
                if ($dg_goods > 0) {
                    foreach ($dgRowIds as $eachRowId) {
                        if ($eachRowId > 0) {
                            $this->common->updatetbledata("tb_order_dg_goods", ['order_cargo_id' => $cargoId, 'order_id' => $order_id], ['id' => $eachRowId]);
                        }
                    }
                }
            } else {
                $upd = $this->db->where( array( 'order_id' => $order_id, 'cargo_id' => $cargo_id ) )->update( "tb_order_cargodetails", array(
                    'length'            => $length,
                    'width'             => $width,
                    'height'            => $height,
                    'weight'            => $weight,
                    'volume'            => $volume,
                    'quantity'          => $this->db->escape_str($post['quantity']),
                    'quantity_type'     => $this->db->escape_str($post['cargo_type']),
                    'cargo_content'     => $this->db->escape_str($post['goods_desc']),
                    'handling_unit' => $handling_unit,
                    'volumetric_weight' => $volumetric_weight,
                    'volweight_uom' => $this->db->escape_str($post['volweight_uom']),
                    'ldm' => $ldm,
                    'second_weight' => $secondweight,
                    'second_volume' => $secondvolume,
                    'qr_code'       => $qr_code,
                    'marks_numbers' => $marks_numbers
                ));
                if ($dg_goods > 0) {
                    foreach ($dgRowIds as $eachRowId) {
                        if ($eachRowId > 0) {
                            $this->common->updatetbledata("tb_order_dg_goods", ['order_cargo_id' => $chk->row()->id, 'order_id' => $order_id], ['id' => $eachRowId]);
                        }
                    }
                }
            }
            if ($qr_code != "" && $color_code != "" && $size_code != "") {
                /*check exists*/
                $chkinner = $this->common->gettblrowdata(
                    array('cargo_id' => $cargo_id, 'cargo_type' => $post['cargo_type']),
                    "id",
                    "tb_inner_cargo",
                    0,
                    0
                );
                $innerarr = array(
                    'cargo_id' => $cargo_id,
                    'cargo_type' => $post['cargo_type'],
                    'goods_description' => $post['goods_desc'],
                    'quantity' => $post['quantity'],
                    'scanned_quantity' => 0,
                    'length' => $length,
                    'length_unit' => $cargo['length_unit'],
                    'width' => $width,
                    'width_unit' => $cargo['width_unit'],
                    'height' => $height,
                    'height_unit' => $cargo['height_unit'],
                    'weight' => $weight,
                    'weight_unit' => $cargo['weight_unit'],
                    'volume' => $volume,
                    'volume_unit' => $cargo['volume_unit'],
                    'stackable' => 0,
                    'qr_code' => $qr_code,
                    'status' => 1,
                    'createdby' => $user_id,
                    'createdon' => $cdate,
                    'updatedon' => $cdate,
                    'color_code' => $color_code,
                    'color_code_name' => $color_code_name,
                    'size_code' => $size_code,
                    'size_name' => $size_code_name,
                    'unit_price' => $unit_price,
                    'd_hsn_code' => $hsn_code
                );
                if (count($chkinner) > 0) {
                    $upd = $this->common->updatetbledata("tb_inner_cargo", $innerarr, $whr);
                } else {
                    $inner_id = $this->common->insertTableData('tb_inner_cargo', $innerarr);
                }
            }
        }

        //   $this->carrierweightupdate->updateCarrierWeight($orderId);

        echo json_encode($data);
    }


    public function saveinnercargo( $id = NULL ) {
        $post          = $this->input->post();
        $cdate         = date( 'Y-m-d H:i:s' );
        $cargo_id      = 0;
        $inner_id      = $data = $inner = array();
        $main_cargo_id = isset( $_POST['main_cargo_id'] ) ? $this->db->escape_str($_POST['main_cargo_id']) : "0";
        $user_id       = $this->session->userdata( 'user_id' );
        $stackable = $post['stackable'] = isset($post['stackable']) ? $this->db->escape_str($post['stackable']) : "0";

        $length        = isset( $post['length'] ) ? $this->db->escape_str($post['length']) : "0.00";
        $width         = isset( $post['width'] )  ? $this->db->escape_str($post['width']) : "0.00";
        $height        = isset( $post['height'] ) ? $this->db->escape_str($post['height']) : "0.00";
        $weight        = isset( $post['weight'] ) ? $this->db->escape_str($post['weight']) : "0.00";
        $volume        = isset( $post['volume'] ) ? $this->db->escape_str($post['volume']) : "0.00";

        //   if($main_cargo_id != "0"){
        if ( $length == "" ) {
            $length = '0.00';
        }
        if ( $width == "" ) {
            $width = '0.00';
        }
        if ( $height == "" ) {
            $height = '0.00';
        }
        if ( $weight == "" ) {
            $weight = '0.00';
        }
        if ( $volume == "" ) {
            $volume = '0.00';
        }
        if ( $id == NULL ) {
            $inner_cargo   = array(
                'cargo_id'          => $main_cargo_id,
                'cargo_type'        => $this->db->escape_str($post['cargo_type']),
                'goods_description' => $this->db->escape_str($post['goods_desc']),
                'quantity'          => $this->db->escape_str($post['quantity']),
                'length'            => $length,
                'length_unit'       => $this->db->escape_str($post['length_uom']),
                'width'             => $width,
                'width_unit'        => $this->db->escape_str($post['width_uom']),
                'height'            => $height,
                'height_unit'       => $this->db->escape_str($post['height_uom']),
                'weight'            => $weight,
                'weight_unit'       => $this->db->escape_str($post['weight_uom']),
                'volume'            => $volume,
                'volume_unit'       => $this->db->escape_str($post['volume_uom']),
                'stackable'         => $stackable,
                'createdby'         => $user_id,
                'createdon'         => $cdate
            );
            $ins           = $this->db->insert( "tb_inner_cargo", $inner_cargo );
            $innercargo_id = $this->db->insert_id();
            $data          = array( 'main_cargo_id' => $main_cargo_id );
        } else {
            $innercargo_id = $id;
            if ( $main_cargo_id == "" && $main_cargo_id == 0 ) {
                $getmaincargo = $this->db->select( "cargo_id" )->get_where( "tb_inner_cargo", array( 'id' => $innercargo_id ) );
                if ( $getmaincargo->num_rows() > 0 ) {
                    $main_cargo_id = $getmaincargo->row()->cargo_id;
                }
            }
            $inner_cargo = array(
                'cargo_id'          => $main_cargo_id,
                'cargo_type'        => $this->db->escape_str($post['cargo_type']),
                'goods_description' => $this->db->escape_str($post['goods_desc']),
                'quantity'          => $this->db->escape_str($post['quantity']),
                'length'            => $length,
                'length_unit'       => $this->db->escape_str($post['length_uom']),
                'width'             => $width,
                'width_unit'        => $this->db->escape_str($post['width_uom']),
                'height'            => $height,
                'height_unit'       => $this->db->escape_str($post['height_uom']),
                'weight'            => $weight,
                'weight_unit'       => $this->db->escape_str($post['weight_uom']),
                'volume'            => $volume,
                'volume_unit'       => $this->db->escape_str($post['volume_uom']),
                'stackable'         => $stackable
            );
            $upd         = $this->db->where( array( 'id' => $innercargo_id ) )->update( "tb_inner_cargo", $inner_cargo );
            $data        = array( 'main_cargo_id' => $main_cargo_id );
        }
        echo json_encode( $data );
    }

    public function savepopupcargo( $id = NULL ) {
        $post             = $this->input->post();
        $cdate            = date( 'Y-m-d H:i:s' );
        $cargo_id         = 0;
        $inner_id         = $data = $inner = array();
        $user_id          = $this->session->userdata( 'user_id' );
        $stackable        = isset( $_POST['popupstackable'] ) ? $this->db->escape_str($_POST['popupstackable']) : "0";
        $grounded         = isset( $_POST['popupgroundable'] ) ? $this->db->escape_str($_POST['popupgroundable']) : "0";
        $splittable       = isset( $_POST['popupsplittable'] ) ? $this->db->escape_str($_POST['popupsplittable']) : "0";
        $popuplength      = isset( $_POST['popuplength'] ) ? $this->db->escape_str($_POST['popuplength']) : "0";
        $popupwidth       = isset( $_POST['popupwidth'] ) ? $this->db->escape_str($_POST['popupwidth']) : "0";
        $popupheight      = isset( $_POST['popupheight'] ) ? $this->db->escape_str($_POST['popupheight']) : "0";
        $popupweight      = isset( $_POST['popupweight'] ) ? $this->db->escape_str($_POST['popupweight']) : "0";
        $popupvolume      = isset( $_POST['popupvolume'] ) ? $this->db->escape_str($_POST['popupvolume']) : "0";
        $popupdg_goods    = isset( $_POST['popupdg_goods'] ) ? $this->db->escape_str($_POST['popupdg_goods']) : "0";
        $popupldm         = isset( $_POST['popupldm'] ) ? $this->db->escape_str($_POST['popupldm']) : "0";
        $second_weight    = isset( $_POST['secondweight'] ) ? $this->db->escape_str($_POST['secondweight']) : "0";
        $second_volume    = isset( $_POST['secondvolume'] ) ? $this->db->escape_str($_POST['secondvolume']) : "0";
        $secondweight_uom = isset( $_POST['secondpopupweight_uom'] ) ? $this->db->escape_str($_POST['secondpopupweight_uom']) : "";
        if ( $secondweight_uom == "" ) {
            $secondweight_uom = "Kg";
        }
        $secondvolume_uom = isset( $_POST['secondpopupvolume_uom'] ) ? $this->db->escape_str($_POST['secondpopupvolume_uom']) : "";
        if ( $secondvolume_uom == "" ) {
            $secondvolume_uom = "cbm";
        }
        if ( $popupldm == "" || ! ( is_numeric( $popupldm ) ) ) {
            $popupldm = "0.00";
        }
        $popupvolumetric_weight = isset( $_POST['popupvolumetric_weight'] ) ? $this->db->escape_str($_POST['popupvolumetric_weight']) : "0";
        if ( $popuplength == "" ) {
            $popuplength = '0.00';
        }
        if ( $popupwidth == "" ) {
            $popupwidth = '0.00';
        }
        if ( $popupheight == "" ) {
            $popupheight = '0.00';
        }
        if ( $popupweight == "" ) {
            $popupweight = '0.00';
        }
        if ( $popupvolume == "" ) {
            $popupvolume = '0.00';
        }
        if ( $popupvolumetric_weight == "" ) {
            $popupvolumetric_weight = '0.00';
        }
        if ( $second_weight == "" ) {
            $second_weight = '0.00';
        }
        if ( $second_volume == "" ) {
            $second_volume = '0.00';
        }

        $cargo = array(
            'cargo_type'        => $this->db->escape_str($post['popupcargo_type']),
            'goods_description' => $this->db->escape_str($post['popupgoods_desc']),
            'quantity'          => $this->db->escape_str($post['popupquantity']),
            'length'            => $popuplength,
            'length_unit'       => $this->db->escape_str($post['popuplength_uom']),
            'width'             => $popupwidth,
            'width_unit'        => $this->db->escape_str($post['popupwidth_uom']),
            'height'            => $popupheight,
            'height_unit'       => $this->db->escape_str($post['popupheight_uom']),
            'weight'            => $popupweight,
            'weight_unit'       => $this->db->escape_str($post['popupweight_uom']),
            'volume'            => $popupvolume,
            'volume_unit'       => $this->db->escape_str($post['popupvolume_uom']),
            'volumetric_weight' => $popupvolumetric_weight,
            'volweight_uom'     => $this->db->escape_str($post['popupvow_uom']),
            'stackable'         => $stackable,
            'grounded'          => $grounded,
            'splittable'        => $splittable,
            'createdby'         => $user_id,
            'createdon'         => $cdate,
            'dg_goods'          => $popupdg_goods,
            'ldm'               => $popupldm,
            'second_weight'     => $second_weight,
            'second_volume'     => $second_volume,
            'secondweight_uom'  => $secondweight_uom,
            'secondvolume_uom'  => $secondvolume_uom
        );
        if ( $id == NULL ) {
            $ins      = $this->db->insert( "tb_cargo_details", $cargo );
            $cargo_id = $this->db->insert_id();

            $data = array( 'cargo_id' => $cargo_id );
        } else {
            $cargo_id = $id;
            $upd      = $this->db->where( array( 'id' => $cargo_id ) )->update( "tb_cargo_details", $cargo );
            $data     = array( 'cargo_id' => $cargo_id );
        }
        if ($popupdg_goods > 0) {
            $dgRowIds = $post['dgRowIds'] ?? [];
            foreach ($dgRowIds as $eachRowId) {
                if ($eachRowId > 0) {
                    $this->common->updatetbledata("tb_order_dg_goods", ['order_cargo_id' => $cargo_id, 'order_id' => '0'], ['id' => $eachRowId]);
                }
            }
        }
        echo json_encode( $data );
    }

    public function editcargodetails() {
        $id    = $this->db->escape_str($this->input->post( 'id' ));
        $cargo = $inner = array();
        if ( $id != "" ) {
            $get_cargo = $this->db->query( "SELECT * FROM tb_cargo_details WHERE id='" . $id . "' GROUP BY id" );
            if ( $get_cargo->num_rows() > 0 ) {
                $get_inner = $this->db->query( "SELECT * FROM tb_inner_cargo WHERE cargo_id='" . $id . "' AND status='1' GROUP BY id" );
                if ( $get_inner->num_rows() > 0 ) {
                    foreach ( $get_inner->result() as $res ) {
                        $inner[] = array(
                            'inner_id'                => $res->id,
                            'inner_cargo_type'        => $res->cargo_type,
                            'inner_goods_description' => $res->goods_description,
                            'inner_quantity'          => $res->quantity,
                            'inner_length'            => $res->length,
                            'inner_length_uom'        => $res->length_unit,
                            'inner_width'             => $res->width,
                            'inner_width_uom'         => $res->width_unit,
                            'inner_height'            => $res->height,
                            'inner_height_uom'        => $res->height_unit,
                            'inner_weight'            => $res->weight,
                            'inner_weight_uom'        => $res->weight_unit,
                            'inner_volume'            => $res->volume,
                            'inner_volume_uom'        => $res->volume_unit,
                            'inner_stackable'         => $res->stackable
                        );
                    }
                }
                $cargo = array(
                    'id'                => $get_cargo->row()->id,
                    'cargo_type'        => $get_cargo->row()->cargo_type,
                    'goods_description' => $get_cargo->row()->goods_description,
                    'quantity'          => $get_cargo->row()->quantity,
                    'length'            => $get_cargo->row()->length,
                    'length_uom'        => $get_cargo->row()->length_unit,
                    'width'             => $get_cargo->row()->width,
                    'width_uom'         => $get_cargo->row()->width_unit,
                    'height'            => $get_cargo->row()->height,
                    'height_uom'        => $get_cargo->row()->height_unit,
                    'weight'            => $get_cargo->row()->weight,
                    'weight_uom'        => $get_cargo->row()->weight_unit,
                    'volume'            => $get_cargo->row()->volume,
                    'volume_uom'        => $get_cargo->row()->volume_unit,
                    'volumetric_weight' => $get_cargo->row()->volumetric_weight,
                    'volweight_uom'     => $get_cargo->row()->volweight_uom,
                    'stackable'         => $get_cargo->row()->stackable,
                    'grounded'          => $get_cargo->row()->grounded,
                    'splittable'        => $get_cargo->row()->splittable,
                    'dg_goods'          => $get_cargo->row()->dg_goods,
                    'ldm'               => $get_cargo->row()->ldm,
                    'second_weight'     => $get_cargo->row()->second_weight,
                    'second_volume'     => $get_cargo->row()->second_volume,
                    'secondvolume_uom'  => $get_cargo->row()->secondvolume_uom,
                    'secondweight_uom'  => $get_cargo->row()->secondweight_uom,
                    'inner'             => $inner
                );
            }
        }
        echo json_encode( $cargo );
    }

    public function deleteinnercargopackage() {
        $inner_id = isset( $_POST['inner_id'] ) ? $this->db->escape_str($_POST['inner_id']) : '0';
        $cargo_id = 0;
        if ( $inner_id != 0 ) {
            $chk = $this->db->select( 'id,cargo_id' )->get_where( 'tb_inner_cargo', array( 'id' => $inner_id ) );
            if ( $chk->num_rows() > 0 ) {
                $cargo_id = $chk->row()->cargo_id;
                $upd      = $this->db->where( array( 'id' => $inner_id ) )->update( 'tb_inner_cargo', array( 'status' => '0' ) );

            }
        }
        echo json_encode( $cargo_id );
    }

    public function insertorder() {

        $cdate            = date( 'Y-m-d H:i:s' );
        $user_id          = $this->session->userdata( 'user_id' );
        $company_code     = isset( $_POST['company_code'] ) ? $this->db->escape_str($_POST['company_code']) : "";
        $branch_code      = isset( $_POST['branch_code'] ) ? $this->db->escape_str($_POST['branch_code']) : "";
        $department_code  = isset( $_POST['department_code'] ) ? $this->db->escape_str($_POST['department_code']) : "";
        $product          = isset( $_POST['product'] ) ? $this->db->escape_str($_POST['product']) : "";
        $service          = isset( $_POST['service'] ) ? $this->db->escape_str($_POST['service']) : "";
        $order_shipper_id = isset( $_POST['order_shipper_id'] ) ? $this->db->escape_str($_POST['order_shipper_id']) : "";
        /*$order_status     = isset($_POST['order_status']) ? $this->db->escape_str($_POST['order_status']) : "";
    if ($order_status == "") {
        $order_status = "OPEN";
    }*/
        $delivery_terms = isset( $_POST['delivery_terms'] ) ? $this->db->escape_str($_POST['delivery_terms']) : "";
        $incoterm       = isset( $_POST['incoterm'] ) ? $this->db->escape_str($_POST['incoterm']) : "";
        $shipment_id    = isset( $_POST['delivery_note'] ) ? $this->db->escape_str($_POST['delivery_note']) : "";
        $container_no   = isset( $_POST['container_num'] ) ? $this->db->escape_str($_POST['container_num']) : "";
        $porder         = isset( $_POST['purchase_order'] ) ? $this->db->escape_str($_POST['purchase_order']) : "";
        $notify_party   = isset( $_POST['notify_party'] ) ? $this->db->escape_str($_POST['notify_party']) : "";
        $currency       = isset( $_POST['currency'] ) ? $this->db->escape_str($_POST['currency']) : "";
        $goods_value    = isset( $_POST['goods_value'] ) ? $this->db->escape_str($_POST['goods_value']) : "0.00";
        $external_order_id = isset( $_POST['external_order_id'] ) ? $this->db->escape_str($_POST['external_order_id']) : "";
        if ( $goods_value == "" ) {
            $goods_value = 0.00;
        }
        $pLatitude = $_POST['p_latitude'] ?? "";
        $pLongitude = $_POST['p_longitude'] ?? "";
        $dLatitude = $_POST['d_latitude'] ?? "";
        $dLongitude = $_POST['d_longitude'] ?? "";
        $party_row_id                 = isset( $_POST['order_party_row_id'] ) ? $this->db->escape_str($_POST['order_party_row_id']) : "0";
        $order_inv_row_id             = isset( $_POST['order_inv_row_id'] ) ? $this->db->escape_str($_POST['order_inv_row_id']) : '0';
        $order_cargo_id               = isset( $_POST['order_cargo_id'] ) ? $this->db->escape_str($_POST['order_cargo_id']) : "";
        $pickup                       = isset( $_POST['order_pickup_id'] ) ? $this->db->escape_str($_POST['order_pickup_id']) : "0";
        $delivery                     = isset( $_POST['order_drop_id'] ) ? $this->db->escape_str($_POST['order_drop_id']) : "";
        $early_pickup                 = isset( $_POST['early_pickup'] ) ? $this->db->escape_str($_POST['early_pickup']) : "";
        $late_pickup                  = isset( $_POST['late_pickup'] ) ? $this->db->escape_str($_POST['late_pickup']) : "";
        $early_delivery               = isset( $_POST['early_delivery'] ) ? $this->db->escape_str($_POST['early_delivery']) : "";
        $late_delivery                = isset( $_POST['late_delivery'] ) ? $this->db->escape_str($_POST['late_delivery']) : "";
        $modeof_trasnport             = isset( $_POST['modeof_trasnport'] ) ? $this->db->escape_str($_POST['modeof_trasnport']) : "LTL";
        $order_type                   = isset( $_POST['order_type'] ) ? $this->db->escape_str($_POST['order_type']) : "";
        $cost_center                   = isset( $_POST['cost_center'] ) ? $this->db->escape_str($_POST['cost_center']) :null;
        $rev_row_id                   = isset( $_POST['rev_row_id'] ) ? $this->db->escape_str($_POST['rev_row_id']) : "";
        $ordcost_row_id               = isset( $_POST['ordcost_row_id'] ) ? $this->db->escape_str($_POST['ordcost_row_id']) : "";
        $customer_code                = isset( $_POST['customer_id'] ) ? $this->db->escape_str($_POST['customer_id']) : "";
        $driver_pickup_instructions   = isset( $_POST['driver_pickup_instructions'] ) ? $this->db->escape_str($_POST['driver_pickup_instructions']) : "";
        $driver_delivery_instructions = isset( $_POST['driver_delivery_instructions'] ) ? $this->db->escape_str($_POST['driver_delivery_instructions']) : "";
        $multiple_marks_numbers       = isset( $_POST['multiple_marks_numbers'] ) ? str_replace(['\r\n','\r','\n'], ", ", $_POST['multiple_marks_numbers']) : "";
        $docs_sent_datetime           = isset( $_POST['docs_sent_datetime'] ) ? $this->db->escape_str($_POST['docs_sent_datetime']) : "";
        $docs_received_datetime       = isset( $_POST['docs_received_datetime'] ) ? $this->db->escape_str($_POST['docs_received_datetime']) : "";
        $e_pickup                     = date( 'Y-m-d H:i:s' );
        if ( $early_pickup != "" ) {
            $e_pickup = date( 'Y-m-d H:i:s', strtotime( $early_pickup ) );
        }
        if ( $late_pickup != "" ) {
            $l_pickup = date( 'Y-m-d H:i:s', strtotime( $late_pickup ) );
        } else {
            $l_pickup = date( 'Y-m-d H:i:s', strtotime( '+1 hour', strtotime( $e_pickup ) ) );
        }
        $e_delivery = date( 'Y-m-d H:i:s' );
        if ( $early_delivery != "" ) {
            $e_delivery = date( 'Y-m-d H:i:s', strtotime( $early_delivery ) );
        }
        if ( $late_delivery != "" ) {
            $l_delivery = date( 'Y-m-d H:i:s', strtotime( $late_delivery ) );
        } else {
            $l_delivery = date( 'Y-m-d H:i:s', strtotime( '+1 hour', strtotime( $e_delivery ) ) );
        }
        $same_porder = "0";
        /*if ( $porder != "" ) {
			$chkporder = $this->db->query( "SELECT id FROM tb_order_details WHERE purchase_order='" . $porder . "' AND status='1'" );
			if ( $chkporder->num_rows() > 0 ) {
				$same_porder = "1";
			}
		}*/
        if ( $same_porder == 1 ) {
            $this->session->set_flashdata( 'error_msg', 'Purchase Order "' . $porder . '" already exists with One ORDER' );
            redirect( "orders" );
            /*return FALSE;*/
        } else {
            $drop_id        = $pickup_custid = 0;
            $pickup_name    = $pickup_country = $pickup_street = $pickup_pincode = $pickup_city = $drop_name = $drop_country = $drop_street = $drop_pincode = $drop_city = $pickup_address = $pickup_state = $drop_address = $drop_state = $drop_latitude = $drop_longitude = $pickup_latitude = $pickup_longitude = "";
            $getdrop_custid = $this->db->query( "SELECT name,location_id as city,street,state,address,country,customeridentifier,pincode,latitude,longitude FROM tbl_party_master WHERE id='" . $delivery . "'" );
            if ( $getdrop_custid->num_rows() > 0 ) {
                $drop_id      = $getdrop_custid->row()->customeridentifier;
                $drop_name    = $getdrop_custid->row()->name;
                $drop_state   = $getdrop_custid->row()->state;
                $drop_address = $getdrop_custid->row()->address;
                $drop_country = $getdrop_custid->row()->country;
                $drop_street  = $getdrop_custid->row()->street;
                $drop_pincode = $getdrop_custid->row()->pincode;
                $drop_city    = $getdrop_custid->row()->city;
                $drop_latitude = $getdrop_custid->row()->latitude;
                $drop_longitude = $getdrop_custid->row()->longitude;
            }

            $getshippercustid = $this->db->query( "SELECT name,location_id as city,street,state,address,country,customeridentifier,pincode,latitude,longitude FROM tbl_party_master WHERE id='" . $order_shipper_id . "'" );
            if ( $getshippercustid->num_rows() > 0 ) {
                $pickup_custid  = $getshippercustid->row()->customeridentifier;
                $pickup_name    = $getshippercustid->row()->name;
                $pickup_state   = $getshippercustid->row()->state;
                $pickup_address = $getshippercustid->row()->address;
                $pickup_country = $getshippercustid->row()->country;
                $pickup_street  = $getshippercustid->row()->street;
                $pickup_pincode = $getshippercustid->row()->pincode;
                $pickup_city    = $getshippercustid->row()->city;
                $pickup_latitude = $getshippercustid->row()->latitude;
                $pickup_longitude = $getshippercustid->row()->longitude;

            }
            if ($pickup_latitude != "" && $pickup_longitude != "" && $drop_latitude != "" && $drop_longitude != "") {
                $lat1 = $pickup_latitude;
                $lng1 = $pickup_longitude;
                $lat2 = $drop_latitude;
                $lng2 = $drop_longitude;
            } else {
                if ($pLatitude != "" && $pLongitude != "" && $dLatitude != "" && $dLongitude != "") {
                    $lat1 = $pLatitude;
                    $lng1 = $pLongitude;
                    $lat2 = $dLatitude;
                    $lng2 = $dLongitude;
                } else {
                    $add1 = implode(",", [$pickup_street, $pickup_city, $pickup_country, $pickup_pincode]);
                    $add2 = implode(",", [$drop_street, $drop_city, $drop_country, $drop_pincode]);
                    $data = getlatlngsbyplace($add1);
                    $lat1 = @$data[0];
                    $lng1 = @$data[1];
                    $data = getlatlngsbyplace($add2);
                    $lat2 = @$data[0];
                    $lng2 = @$data[1];
                }
            }
            $ship_row_id      = 0;
            $enddate          = date( 'Y-m-d H:i:s', strtotime( "+1 day" ) );
            $tid              = $tname = "";
            $gettrasnportmode = $this->db->query( "SELECT id,name FROM tb_transportmode WHERE code LIKE '" . $modeof_trasnport . "'" );
            if ( $gettrasnportmode->num_rows() > 0 ) {
                $tid   = $gettrasnportmode->row()->id;
                $tname = $gettrasnportmode->row()->name;
            }
            if ( $shipment_id == "" ) {
                $shipment_id = "SVK" . time();
            }

            $ship_arr   = array(
                'shipid'           => $shipment_id,
                'txnid'            => $shipment_id,
                'trucktype'        => $tname,
                'pickupcnt'        => '1',
                'dropcnt'          => '1',
                'unitspec'         => 1,
                'insertusr'        => $pickup_custid,
                'carrier'          => '0',
                'insertuserdate'   => $cdate,
                'enddate'          => $enddate,
                'insdate'          => $cdate,
                'upddate'          => $cdate,
                'reason'           => 'SHIPMENT',
                'purpose'          => 'SEND INTEGRATION',
                'ship_object'      => 'SHIPMENT',
                'logdate'          => $cdate,
                'transport_mode'   => $modeof_trasnport,
                'domainname'       => $branch_code,
                'company_code'     => $company_code,
                'branch_code'      => $branch_code,
                'product'          => $product,
                'freight_term'     => '60',
                'freight_termname' => 'Free of Charge',
                'incoterm'         => $incoterm,
                'modeoftransport'  => $tid
            );
            $chk_shipid = $this->db->query( "SELECT id FROM tb_shipments WHERE shipid LIKE '" . $shipment_id . "'" );
            if ( $chk_shipid->num_rows() > 0 ) {
                $ship_row_id = $chk_shipid->row()->id;
                $this->db->where( array( 'id' => $ship_row_id ) )->update( "tb_shipments", $ship_arr );
            } else {
                $ship_arr['createdon'] = $cdate;
                $ship_ins              = $this->db->insert( "tb_shipments", $ship_arr );
                $ship_row_id           = $this->db->insert_id();
            }
            $customer_id = 0;
            $cust_id     = $this->session->userdata( 'cust_id' );
            if ( $pickup == "" ) {
                $pickup = 0;
            }
            $customer_id = $pickup;
            if ( $customer_id == "" || $customer_id == "0" ) {
                if ( $customer_code != "" && $customer_code != "0" ) {
                    $getcustomerid = $this->db->select( "id" )->get_where( "tb_customers", array( 'code' => $customer_code, 'user_id' => $user_id, 'status' => '1' ) );
                    if ( $getcustomerid->num_rows() > 0 ) {
                        $customer_id = $getcustomerid->row()->id;
                    }
                }
            }
            if ( $this->session->userdata( 'company_code' ) == 'NZKN' ) {
                if ( $product == "" ) {
                    $product = "KN AsiaLink";
                }
                if ( $modeof_trasnport == "" ) {
                    $modeof_trasnport = "LTL";
                }
                if ( $service == "" ) {
                    $service = "19";
                }
            }
            $curtz        = $this->session->userdata( "usr_tzone" )['timezone'];
            $logdate      = date( 'Y-m-d H:i:s' );
            $getactual    = getdatetimebytimezone( DFLT_TZ, $logdate, $curtz );
            $logdate      = $getactual['datetime'];
            $getpickup    = getdatetimebytimezone( DFLT_TZ, $e_pickup, $curtz );
            $e_pickup     = $getpickup['datetime'];
            $getlpickup   = getdatetimebytimezone( DFLT_TZ, $l_pickup, $curtz );
            $l_pickup     = $getlpickup['datetime'];
            $getdelivery  = getdatetimebytimezone( DFLT_TZ, $e_delivery, $curtz );
            $e_delivery   = $getdelivery['datetime'];
            $getldelivery = getdatetimebytimezone( DFLT_TZ, $l_delivery, $curtz );
            $l_delivery   = $getldelivery['datetime'];
            $childid      = 0;
            if ( $this->session->userdata( 'childid' ) ) {
                $childid = $this->session->userdata( 'childid' );
            }
            $created_source = '4';
            if($branch_code == "INCL"){
                $created_source = '15';
                $ordtypechk = $this->common->gettblrowdata(array("id"=>$order_type),"ordtype_code","tb_order_types",0,0);
                if(count($ordtypechk)>0){
                    if($ordtypechk['ordtype_code'] == "Return"){
                        $created_source = '16';
                    }
                }
            }
            $orderinfo    = array(
                'shipment_id'       => $ship_row_id,
                'customer_id'       => $customer_id,
                'product'           => $product,
                'pickup_datetime'   => $e_pickup,
                'delivery_datetime' => $e_delivery,
                'pickup_endtime'    => $l_pickup,
                'drop_endtime'      => $l_delivery,
                'goods_value'       => $goods_value,
                'currency'          => $currency,
                'company_code'      => $company_code,
                'branch_code'       => $branch_code,
                'createdon'         => $cdate,
                'drop_custid'       => $drop_id,
                'drop_partyid'      => $drop_id,
                'user_id'           => $user_id,
                'sub_uid'           => $childid,
                'pickup_custid'     => $pickup_custid,
                'pickup_partyid'    => $pickup_custid,
                'pickup_country'    => $pickup_country,
                'pickup_city'       => $pickup_city,
                'pickup_pincode'    => $pickup_pincode,
                'pickup_company'    => $pickup_name,
                'pickup_address1'   => $pickup_street,
                'pickup_address2'   => $pickup_state,
                'delivery_country'  => $drop_country,
                'delivery_city'     => $drop_city,
                'delivery_pincode'  => $drop_pincode,
                'delivery_company'  => $drop_name,
                'delivery_address1' => $drop_street,
                'delivery_address2' => $drop_state,
                'is_created'        => '1',
                'plat'              => $lat1,
                'plng'              => $lng1,
                'dlat'              => $lat2,
                'dlng'              => $lng2,
                'transport_mode'    => $modeof_trasnport,
                'created_source'    => $created_source,
                'createdon'         => $logdate,
                'external_order_id' => $external_order_id
            );
            $ins_order    = $this->db->insert( "tb_orders", $orderinfo );
            $order_id     = $this->db->insert_id();
            $get_country  = $this->db->select( 'country_code,company_code' )->get_where( "tb_users", array( 'id' => $user_id ) );
            $country_code = $get_country->row()->country_code;
            $company_code = $get_country->row()->company_code;
            $genord       = array( "user_id" => $user_id, "order_id" => $order_id, "country_code" => $country_code, "company_code" => $company_code );
            $booking_id   = generatebookingid( $genord );
            $invtypes     = makeorderinvolvedpartiestype( $customer_id, $order_id, "CUSTOMER" );
            insertOrdersRefFileLineIdentifier(['pickupCity' => $pickup_city, 'pickupState' => $pickup_state, 'pickupCountry' => $pickup_country, 'dropCity' => $drop_city, 'dropState' => $drop_state, 'dropCountry' => $drop_country, 'companyCode' => $company_code, 'branchCode' => $branch_code, 'orderRowId' => $order_id, 'date' => $logdate]);
            $upd          = $this->db->where( array( 'id' => $order_id ) )->update( "tb_orders", array( 'order_id' => $booking_id ) );
            if ( $docs_sent_datetime != "" && $docs_sent_datetime != "0000-00-00 00:00:00" ) {
                $getdocsent         = getdatetimebytimezone( DFLT_TZ, $docs_sent_datetime, $curtz );
                $docs_sent_datetime = $getdocsent['datetime'];
            }
            if ( $docs_received_datetime != "" && $docs_received_datetime != "0000-00-00 00:00:00" ) {
                $getdocrec              = getdatetimebytimezone( DFLT_TZ, $docs_received_datetime, $curtz );
                $docs_received_datetime = $getdocrec['datetime'];
            }
            $details = array(
                'service'                => $service,
                'delivery_term'          => $delivery_terms,
                'incoterm'               => $incoterm,
                /*'purchase_order'         => $porder,*/
                'notify_party'           => $notify_party,
                'department_code'        => $department_code,
                'temperature_control'    => '0',
                'valorance_insurance'    => '0',
                'high_cargo_value'       => '0',
                'customs_required'       => '0',
                'order_row_id'           => $order_id,
                'order_id'               => $booking_id,
                'createdon'              => $cdate,
                'shipper_id'             => $order_shipper_id,
                'order_type'             => $order_type,
                'docs_received_datetime' => $docs_received_datetime,
                'docs_sent_datetime'     => $docs_sent_datetime
            );
            if($company_code == 'NZPG'){
                $details['cost_center_id'] =  $cost_center;
            }

            $this->db->insert( "tb_order_details", $details );
            /**
             * AU delivery note
             */
            if($this->session->userdata('company_code') == 'KNAU'){
                $this->load->helper('aumacpac_helper');
                au_deliverynote_customer_specific($order_id,$booking_id);
            }
            $shipper_address    = array( 'order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'location_id' => $pickup_city, 'street' => $pickup_street, 'state' => $pickup_state, 'address' => $pickup_address, 'pincode' => $pickup_pincode, 'country' => $pickup_country, 'user_id' => $user_id );
            $chk_shipperaddress = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'status' => '1' ) );
            if ( $chk_shipperaddress->num_rows() > 0 ) {
                $shipperadd_id = $chk_shipperaddress->row()->id;
                $upd_add       = $this->db->where( array( 'id' => $shipperadd_id ) )->update( "tbl_orderparty_address", $shipper_address );
            } else {
                $shipper_address['createdon'] = $cdate;
                $this->db->insert( "tbl_orderparty_address", $shipper_address );
                $shipperadd_id = $this->db->insert_id();
            }
            $delivery_address    = array( 'order_id' => $order_id, 'party_master_id' => $delivery, 'location_id' => $drop_city, 'street' => $drop_street, 'state' => $drop_state, 'address' => $drop_address, 'pincode' => $drop_pincode, 'country' => $drop_country, 'user_id' => $user_id );
            $chk_deliveryaddress = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $delivery, 'status' => '1' ) );
            if ( $chk_deliveryaddress->num_rows() > 0 ) {
                $dropadd_id = $chk_deliveryaddress->row()->id;
                $upd_add    = $this->db->where( array( 'id' => $dropadd_id ) )->update( "tbl_orderparty_address", $delivery_address );
            } else {
                $delivery_address['createdon'] = $cdate;
                $this->db->insert( "tbl_orderparty_address", $delivery_address );
                $dropadd_id = $this->db->insert_id();
            }
            $length        = $width = $height = $weight = $volume = $ldm = $volumetric_weight = 0;
            $quantity      = 1;
            $cargo_forship = array();
            if ( $order_cargo_id != "" ) {
                $cargo_ids = array();
                $cargo_ids = explode( ',', $order_cargo_id );
               
                if(!empty($cargo_ids)){
                    $cargo_ids = array_unique($cargo_ids);
                    
                    for ( $i = 0; $i < count( $cargo_ids ); $i ++ ) {
                        $length           = $width = $height = $weight = $volume = $ldm = $volumetric_weight = $second_volume = $second_weight = $item_id = 0;
                        $quantity         = 1;
                        $getcargo_details = $this->db->query("SELECT cargo_type,length,width,height,weight,volumetric_weight,ldm,volume,second_weight,second_volume,quantity,goods_description,marks_numbers,item_id FROM tb_cargo_details WHERE id='" . $cargo_ids[$i] . "'");
                        $cargo_type       = $description = "";
                        if ( $getcargo_details->num_rows() > 0 ) {
                            $length              = $getcargo_details->row()->length;
                            $width               = $getcargo_details->row()->width;
                            $height              = $getcargo_details->row()->height;
                            $weight              = $getcargo_details->row()->weight;
                            $volume              = $getcargo_details->row()->volume;
                            $quantity            = $getcargo_details->row()->quantity;
                            $cargo_type          = $getcargo_details->row()->cargo_type;
                            $description         = $getcargo_details->row()->goods_description;
                            $volumetric_weight   = $getcargo_details->row()->volumetric_weight;
                            $ldm                 = $getcargo_details->row()->ldm;
                            $second_weight       = $getcargo_details->row()->second_weight;
                            $second_volume       = $getcargo_details->row()->second_volume;
                            $cargo_forship[ $i ] = $getcargo_details->row()->cargo_type;
                            $item_id             = $getcargo_details->row()->item_id;
                            $marks_numbers       = $getcargo_details->row()->marks_numbers;
                        }
                        $cargo_type = str_replace(array("'", "\""), "", htmlspecialchars($cargo_type));
                        $description = str_replace(array("'", "\""), "", htmlspecialchars($description));
                        $gethandling_unit = $this->db->query( "SELECT id FROM tbl_shipunit_types WHERE unit_name LIKE '" . $cargo_type . "'" );
                        $handling_unit    = "";
                        if ( $gethandling_unit->num_rows() > 0 ) {
                            $handling_unit = $gethandling_unit->row()->id;
                        } else {
                            $handlingunit_ar = array( 'unit_name' => $cargo_type, 'description' => $cargo_type, 'user_id' => $user_id, 'created_at' => $cdate, 'status' => '1' );
                            $this->db->insert( "tbl_shipunit_types", $handlingunit_ar );
                            $handling_unit = $this->db->insert_id();
                        }
                        $qr_code = "";
                        if($item_id > 0){
                            $items = $this->common->gettblrowdata(array("id"=>$item_id),"item_number","tb_items",0,0);
                            if(count($items)>0){
                                $qr_code = $items['item_number'];
                            }
                        }
                        $cargo     = array(
                            'order_id'          => $order_id,
                            'cargo_id'          => $cargo_ids[ $i ],
                            'status'            => '1',
                            'length'            => $length,
                            'width'             => $width,
                            'height'            => $height,
                            'weight'            => $weight,
                            'volumetric_weight' => $volumetric_weight,
                            'volweight_uom'     => 'kg',
                            'volume'            => $volume,
                            'quantity'          => $quantity,
                            'cargo_content'     => $description,
                            'quantity_type'     => $cargo_type,
                            'handling_unit'     => $handling_unit,
                            'ldm'               => $ldm,
                            'second_volume'     => $second_volume,
                            'second_weight'     => $second_weight,
                            'qr_code'           => $qr_code,
                            'marks_numbers'     => $marks_numbers
                        );
                        $orderCargoId = $this->common->insertTableData("tb_order_cargodetails", $cargo);
                        $checkDgGoods = $this->common->gettbldata(['order_cargo_id' => $cargo_ids[$i], 'status' => '1'], "id", "tb_order_dg_goods", 0, 0);
                        foreach ($checkDgGoods as $eachLine) {
                            $this->common->updatetbledata("tb_order_dg_goods", ['order_cargo_id' => $orderCargoId, 'order_id' => $order_id], ['id' => $eachLine['id']]);
                        }
                    }
                }
            }
            $unitspec = "1";
            if ( ! empty( $cargo_forship ) ) {
                $unitspec = implode( ',', $cargo_forship );
            }
            $updship      = $this->db->where( array( 'id' => $ship_row_id ) )->update( "tb_shipments", array( 'unitspec' => $unitspec, 'txncode' => $booking_id ) );
            $total_weight = $total_volume = $total_quantity = 0;
            $gettotal     = $this->db->query( "SELECT sum(weight) as total_weight,sum(volume) as total_volume,sum(quantity) as total_quantity FROM tb_order_cargodetails WHERE order_id='" . $order_id . "' AND status='1'" );
            if ( $gettotal->num_rows() > 0 ) {
                $total_volume   = $gettotal->row()->total_volume;
                $total_weight   = $gettotal->row()->total_weight;
                $total_quantity = $gettotal->row()->total_quantity;
            }
            $upd_order = $this->db->where( array( 'id' => $order_id ) )->update( "tb_orders", array( 'volume' => $total_volume, 'weight' => $total_weight, 'quantity' => $total_quantity ) );
            $ids       = array();
            if ( $shipment_id != ""  &&  $this->session->userdata('company_code') != 'KNAU') {
                $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'DQ', 'ref_value' => $shipment_id, 'createdon' => $cdate );
                $ins     = $this->db->insert( 'tb_order_references', $ins_ref );

            }
            if ( $company_code == 'UKKN' || $company_code == 'AUKN' ) {
                if ( $container_no != "" ) {
                    $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'CTR', 'ref_value' => $container_no, 'createdon' => $cdate );
                    $ins     = $this->db->insert( 'tb_order_references', $ins_ref );

                }
            }
            if ( $porder != "" ) {
                $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'PO', 'ref_value' => $porder, 'createdon' => $cdate );
                $ins     = $this->db->insert( 'tb_order_references', $ins_ref );
            }
            if ( $driver_pickup_instructions != "" ) {
                $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'ORD_PIKINST', 'ref_value' => $driver_pickup_instructions, 'createdon' => $cdate );
                $ins     = $this->db->insert( 'tb_order_references', $ins_ref );
            }
            if ( $driver_delivery_instructions != "" ) {
                $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'ORD_DLVINST', 'ref_value' => $driver_delivery_instructions, 'createdon' => $cdate );
                $ins     = $this->db->insert( 'tb_order_references', $ins_ref );
            }
            if ( !empty($multiple_marks_numbers) ) {
                $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'MARKS_NUMBERS', 'ref_value' => $multiple_marks_numbers, 'createdon' => $cdate );
                $ins     = $this->db->insert( 'tb_order_references', $ins_ref );
            }
            if (checkAccessConditions("CHECK_STS_REFERENCE_COUNTRIES", $company_code )) {
                $ins_ref = ['order_id' => $order_id, 'reference_id' => 'STS'];
                $checkSTSRef = $this->common->gettblrowdata($ins_ref, "id", "tb_order_references", 0, 0);
                if (count($checkSTSRef) == 0) {
                    $ins_ref['ref_value'] = "Pending";
                    $this->common->insertTableData("tb_order_references", $ins_ref);
                }
            }
            if ( $party_row_id != "0" ) {
                $ids = explode( ',', $party_row_id );
            }
            $inv_ids = array();
            if ( $order_inv_row_id != 0 || $order_inv_row_id != "" ) {
                $inv_ids = explode( ',', $order_inv_row_id );
                /* array_push($ids, $order_inv_row_id);*/
            }
            if ( ! empty( $inv_ids ) ) {
                foreach ( $inv_ids as $inv ) {
                    array_push( $ids, $inv );
                }
            }
            if ( ! empty( $ids ) ) {
                for ( $i = 0; $i < count( $ids ); $i ++ ) {
                    if ( $ids[ $i ] != "" ) {
                        $getpartytype = $this->db->query( "SELECT party_type_id FROM tbl_party_master WHERE id='" . $ids[ $i ] . "'" );
                        $party_type   = 1;
                        if ( $getpartytype->num_rows() > 0 ) {
                            $party_type = $getpartytype->row()->party_type_id;
                        }
                        $party = array( 'order_id' => $order_id, 'party_id' => $ids[ $i ], 'status' => '1', 'createdon' => $cdate, 'status' => '1', 'party_type' => $party_type, 'order_number' => $booking_id );
                        $chk   = $this->db->select( "id" )->get_where( "tb_order_parties", array( 'order_id' => $order_id, 'party_id' => $ids[ $i ], 'status' => '1', 'party_type' => $party_type, ) );
                        if ( $chk->num_rows() == 0 ) {
                            $ins_party = $this->db->insert( "tb_order_parties", $party );
                        }
                    }
                }
            }
            $sub_cut_parties = array();
            $sub_cut_parties['0'] = $order_shipper_id;
            $sub_cut_parties['1'] = $delivery;
            $sub_cut_parties['2'] = '0';
            $sub_cut_parties['3'] = '0';
            if (!empty($sub_cut_parties)) {
                subcustpartiesinsert($order_id, $booking_id, $sub_cut_parties);
            }
            $rev_ids = array();
            if ( $rev_row_id != "" && $rev_row_id != "0" ) {
                $rev_ids = explode( ',', $rev_row_id );
                if ( $ordcost_row_id != "" ) {
                    $cost_ids = array();
                    $cost_ids = explode( ',', $ordcost_row_id );
                    foreach ( $cost_ids as $ids ) {
                        array_push( $rev_ids, $ids );
                    }
                }
                if ( ! empty( $rev_ids ) ) {
                    $upd = $this->db->query( "UPDATE tb_reveneus set order_id ='" . $order_id . "' WHERE id IN (" . implode( ',', $rev_ids ) . ")" );
                }
            }
            $shipment_name = "BOXES";
            $total_weight  = $total_volume = $total_quantity = 0;
            $gettotal      = $this->db->query( "SELECT sum(weight) as total_weight,sum(volume) as total_volume,sum(quantity) as total_quantity FROM tb_order_cargodetails WHERE order_id='" . $order_id . "'" );
            if ( $gettotal->num_rows() > 0 ) {
                $total_volume   = $gettotal->row()->total_volume;
                $total_weight   = $gettotal->row()->total_weight;
                $total_quantity = $gettotal->row()->total_quantity;
            }
            $getcust_details = $this->common->gettblrowdata( array( 'id' => $customer_id ), "name,phone,email_id", 'tb_customers', 0, 0 );
            if ( ! empty( $getcust_details ) ) {
                $customer_email = $getcust_details['email_id'];
                $customer_phone = $getcust_details['phone'];
            }
            /*if($this->session->userdata('usr_tzone')['country'] == "RU"){*/
            if ( $order_id != "" && $customer_id != "" ) {
                $pickupinfo['country']       = trim( $pickup_country );
                $pickupinfo['order_country'] = trim( $pickup_country );
                $pickupinfo['order_city']    = trim( $pickup_city );
                $pickupinfo['order_zipcode'] = trim( $pickup_pincode );
                $pickupinfo['state']         = trim( $pickup_state );
                $pickupinfo['city']          = trim( $pickup_city );
                $pickupinfo['region']        = trim( $pickup_street );
                $pickupinfo['zipcode']       = trim( $pickup_pincode );

                $pickupinfo['stoptype']    = "P";
                $dropinfo['country']       = trim( $drop_country );
                $dropinfo['order_country'] = trim( $drop_country );
                $dropinfo['order_city']    = trim( $drop_city );
                $dropinfo['order_zipcode'] = trim( $drop_pincode );
                $dropinfo['state']         = trim( $drop_state );
                $dropinfo['city']          = trim( $drop_city );
                $dropinfo['region']        = trim( $drop_street );
                $dropinfo['zipcode']       = trim( $drop_pincode );
                $dropinfo['stoptype']      = "D";
                $pickupgeocode             = checkgeocode( $pickupinfo );
                $dropgeocode               = checkgeocode( $dropinfo );
                if ( ! empty( $pickupgeocode ) && ! empty( $dropgeocode ) ) {
                    $pickupgeocode['stoptype']      = "P";
                    $dropgeocode['stoptype']        = "D";
                    $pickupgeocode['order_country'] = trim( $pickup_country );
                    $pickupgeocode['order_city']    = trim( $pickup_city );
                    $pickupgeocode['order_zipcode'] = trim( $pickup_pincode );
                    $dropgeocode['order_country']   = trim( $drop_country );
                    $dropgeocode['order_city']      = trim( $drop_city );
                    $dropgeocode['order_zipcode']   = trim( $drop_pincode );
                    //-------------------------------- //for auto route
                    $pickupgeocode['cargo'] = $cargo;
                    $dropgeocode['cargo'] =  $cargo;
                    //--------------------------------
                    $pickuproute                    = getcust_routeautomate( $customer_id, $pickupgeocode );
                    $droproute                      = getcust_routeautomate( $customer_id, $dropgeocode );
                    if ( ! empty( $pickuproute ) && ! empty( $droproute ) ) {
                        $orderinfo['id']             = $order_id;
                        $orderinfo['order_id']       = $booking_id;
                        $orderinfo['shipment_name']  = $shipment_name;
                        $orderinfo['customer_phone'] = $customer_phone;
                        $orderinfo['customer_email'] = $customer_email;
                        $orderinfo['volume']         = $total_volume;
                        $orderinfo['weight']         = $total_weight;
                        $orderinfo['quantity']       = $total_quantity;
                        $orderinfo['quantity']       = $total_quantity;
                        $shipment                    = createshipmentbyorder( $pickuproute, $orderinfo );
                    } else {
                        //-------------------------------- //for auto route
                        $pickupinfo['cargo'] = $cargo;
                        $dropinfo['cargo'] =  $cargo;
                        //--------------------------------
                        $pickuproute1 = getcust_routeautomate( $customer_id, $pickupinfo );
                        $droproute1   = getcust_routeautomate( $customer_id, $dropinfo );
                        if ( ! empty( $pickuproute1 ) && ! empty( $droproute1 ) ) {
                            $orderinfo['id']             = $order_id;
                            $orderinfo['order_id']       = $booking_id;
                            $orderinfo['shipment_name']  = $shipment_name;
                            $orderinfo['customer_phone'] = $customer_phone;
                            $orderinfo['customer_email'] = $customer_email;
                            $orderinfo['volume']         = $total_volume;
                            $orderinfo['weight']         = $total_weight;
                            $orderinfo['quantity']       = $total_quantity;
                            $orderinfo['quantity']       = $total_quantity;
                            $shipment                    = createshipmentbyorder( $pickuproute1, $orderinfo );
                        }
                    }
                } else {
                    //--------------------------------//for auto route
                    $pickupinfo['cargo'] = $cargo;
                    $dropinfo['cargo'] =  $cargo;
                    //--------------------------------
                    $pickuproute1 = getcust_routeautomate( $customer_id, $pickupinfo );
                    $droproute1   = getcust_routeautomate( $customer_id, $dropinfo );
                    if ( ! empty( $pickuproute1 ) && ! empty( $droproute1 ) ) {
                        $orderinfo['id']             = $order_id;
                        $orderinfo['order_id']       = $booking_id;
                        $orderinfo['shipment_name']  = $shipment_name;
                        $orderinfo['customer_phone'] = $customer_phone;
                        $orderinfo['customer_email'] = $customer_email;
                        $orderinfo['volume']         = $total_volume;
                        $orderinfo['weight']         = $total_weight;
                        $orderinfo['quantity']       = $total_quantity;
                        $orderinfo['quantity']       = $total_quantity;
                        $shipment                    = createshipmentbyorder( $pickuproute1, $orderinfo );
                    }
                }
                $checkTripForOrder = $this->common->gettblrowdata("id='" . $order_id . "' AND shift_id >0", "id,shift_id", "tb_orders", 0, 0);
                if (!empty($checkTripForOrder)) {
                    $this->load->library('notifytrigger');
                    $this->notifytrigger->sendNotificationToCarrier($checkTripForOrder['shift_id'], $company_code, 'CR');
                }
            }
            /*}*/
            $pref_arr = array(
                'pickup'         => strtoupper( $pickup_country ),
                'pickup_state'   => strtoupper( $pickup_state ),
                'pickup_city'    => strtoupper( $pickup_city ),
                'pickup_pincode' => $pickup_pincode,
                'drop'           => strtoupper( $drop_country ),
                'drop_state'     => strtoupper( $drop_state ),
                'drop_city'      => strtoupper( $drop_city ),
                'drop_pincode'   => $drop_pincode,
                'customer_id'    => $customer_code,
                'service'        => $service,
                'product'        => $product,
                'user_id'        => $user_id,
                'company_code'   => $company_code,
                'order_type'     => $order_type,
                'order_id'       => $order_id,
                'customer_row_id'=> $customer_id,
            );

            /*if($company_code == 'PLKN'){*/
            $this->ratemanagement->addrecodfororderinsertion( $pref_arr );
            /*}*/
            $this->ordernotify( 'booking_create', $order_id );
            if ( $order_id != "" && $order_id != '0' ) {
                try {
                    $this->altovaordercreation->sendOrderToAltova($order_id);
                } catch (Exception $ex) {
                    log_message("error", "Some Problem occured!, While Sending Order to Altova ".$ex->getMessage());
                }
                $this->session->set_flashdata( 'success_msg', 'Order Created Successfully - ' . $booking_id );
                redirect( 'orders/orderslist/' . $order_id );
            } else {
                redirect( "orders" );
            }
        }

    }

    public function savequickbook() {
        $cdate                = date( 'Y-m-d H:i:s' );
        $user_id              = $this->session->userdata( 'user_id' );
        $cust_id              = $this->session->userdata( 'cust_id' );
        $company_code         = isset( $_POST['popupcompany_code'] ) ? $this->db->escape_str($_POST['popupcompany_code']) : "";
        $branch_code          = isset( $_POST['popupbranch_code'] ) ? $this->db->escape_str($_POST['popupbranch_code']) : "";
        $department_code      = isset( $_POST['popupdepartment_code'] ) ? $this->db->escape_str($_POST['popupdepartment_code']) : "";
        $product              = isset( $_POST['productpopup'] ) ? $this->db->escape_str($_POST['productpopup']) : "";
        $service              = isset( $_POST['servicepopup'] ) ? $this->db->escape_str($_POST['servicepopup']) : "";
        $delivery_terms       = isset( $_POST['popupdelivery_terms'] ) ? $this->db->escape_str($_POST['popupdelivery_terms']) : "";
        $incoterm             = isset( $_POST['incoterm_popup'] ) ? $this->db->escape_str($_POST['incoterm_popup']) : "";
        $shipment_id          = isset( $_POST['popupdelivery_note'] ) ? $this->db->escape_str($_POST['popupdelivery_note']) : "";
        $porder               = isset( $_POST['purchaseorder_popup'] ) ? $this->db->escape_str($_POST['purchaseorder_popup']) : "";
        $notify_party         = isset( $_POST['popupnotifyparty'] ) ? $this->db->escape_str($_POST['popupnotifyparty']) : "";
        $popuppickup          = isset( $_POST['popuppickup'] ) ? $this->db->escape_str($_POST['popuppickup']) : "";
        $popupdelivery        = isset( $_POST['popupdelivery'] ) ? $this->db->escape_str($_POST['popupdelivery']) : "";
        $customer_phone       = isset( $_POST['popupshipper_phone'] ) ? $this->db->escape_str($_POST['popupshipper_phone']) : "";
        $customer_email       = isset( $_POST['popupshipper_email'] ) ? $this->db->escape_str($_POST['popupshipper_email']) : "";
        $popupcustomer_id     = isset( $_POST['popupcustomer_id'] ) ? $this->db->escape_str($_POST['popupcustomer_id']) : "";
        $driverdelivery_popup = isset( $_POST['driverdelivery_popup'] ) ? $this->db->escape_str($_POST['driverdelivery_popup']) : "";
        $driverpickup_popup   = isset( $_POST['driverpickup_popup'] ) ? $this->db->escape_str($_POST['driverpickup_popup']) : "";

        $currency       = isset( $_POST['currency'] ) ? $this->db->escape_str($_POST['currency']) : "";
        $goods_value    = isset( $_POST['goods_value'] ) ? $this->db->escape_str($_POST['goods_value']) : "0.00";

        $earlyquickbook_delivery = $latequickbook_delivery = "";
        if ( $popupdelivery != "" ) {
            $earlyquickbook_delivery = date( 'Y-m-d H:i:s', strtotime( $popupdelivery ) );
            $latequickbook_delivery  = date( 'Y-m-d H:i:s', strtotime( '+1 hour', strtotime( $earlyquickbook_delivery ) ) );
        }
        $earlyquickbook_pickup = $latequickbook_pickup = "";
        if ( $popuppickup != "" ) {
            $earlyquickbook_pickup = date( 'Y-m-d H:i:s', strtotime( $popuppickup ) );
            $latequickbook_pickup  = date( 'Y-m-d H:i:s', strtotime( '+1 hour', strtotime( $earlyquickbook_pickup ) ) );
        }
        $popuporder_type       = isset( $_POST['popuporder_type'] ) ? $this->db->escape_str($_POST['popuporder_type']) : "";
        $popupmodeof_trasnport = isset( $_POST['popupmodeof_trasnport'] ) ? $this->db->escape_str($_POST['popupmodeof_trasnport']) : "LTL";

        $reference_ids                 = isset( $_POST['quickbookreference_ids'] ) ? $this->db->escape_str($_POST['quickbookreference_ids']) : "0";
        $quickbook_order_reference_ids = isset( $_POST['quickbook_order_reference_ids'] ) ? $this->db->escape_str($_POST['quickbook_order_reference_ids']) : "0";
        $order_cargo_id                = isset( $_POST['quickbookorder_cargo_id'] ) ? $this->db->escape_str($_POST['quickbookorder_cargo_id']) : "";
        $inv_parties                   = array( $_POST['quickbookshipper_id'], $_POST['quickboookconsignee_id'] );
        $pickup                        = isset( $_POST['quickbookpickup_id'] ) ? $this->db->escape_str($_POST['quickbookpickup_id']) : "0";
        if ( $pickup == "" ) {
            $pickup = 0;
        }
        $delivery       = $this->db->escape_str($_POST['quickboookconsignee_id']);
        $drop_id        = $pickup_custid = 0;
        $pickup_name    = $pickup_country = $pickup_street = $pickup_state = $drop_state = $pickup_pincode = $pickup_city = $drop_name = $drop_country = $drop_street = $drop_pincode = $drop_city = $drop_latitude = $drop_longitude = $pickup_latitude = $pickup_longitude = "";
        $getdrop_custid = $this->db->query( "SELECT name,country,state,street,customeridentifier,pincode,location_id as city,latitude,longitude FROM tbl_party_master WHERE id='" . $delivery . "'" );
        if ( $getdrop_custid->num_rows() > 0 ) {
            $drop_id      = $getdrop_custid->row()->customeridentifier;
            $drop_name    = $getdrop_custid->row()->name;
            $drop_country = $getdrop_custid->row()->country;
            $drop_state   = $getdrop_custid->row()->state;
            $drop_street  = $getdrop_custid->row()->street;
            $drop_pincode = $getdrop_custid->row()->pincode;
            $drop_city    = $getdrop_custid->row()->city;
            $drop_latitude = $getdrop_custid->row()->latitude;
            $drop_longitude = $getdrop_custid->row()->longitude;
        }
        $getshippercustid = $this->db->query( "SELECT name,country,state,street,customeridentifier,pincode,location_id as city,latitude,longitude FROM tbl_party_master WHERE id='" . $_POST['quickbookshipper_id'] . "'" );
        if ( $getshippercustid->num_rows() > 0 ) {
            $pickup_custid  = $getshippercustid->row()->customeridentifier;
            $pickup_name    = $getshippercustid->row()->name;
            $pickup_country = $getshippercustid->row()->country;
            $pickup_state   = $getshippercustid->row()->state;
            $pickup_street  = $getshippercustid->row()->street;
            $pickup_pincode = $getshippercustid->row()->pincode;
            $pickup_city    = $getshippercustid->row()->city;
            $pickup_latitude = $getshippercustid->row()->latitude;
            $pickup_longitude = $getshippercustid->row()->longitude;
        }
        $tname            = "Full Truck Load";
        $tid              = "FTL";
        $enddate          = date( 'Y-m-d H:i:s', strtotime( "+1 day" ) );
        $tid              = 1;
        $tname            = "";
        $gettrasnportmode = $this->db->query( "SELECT id,name FROM tb_transportmode WHERE code LIKE '" . $popupmodeof_trasnport . "'" );
        if ( $gettrasnportmode->num_rows() > 0 ) {
            $tid   = $gettrasnportmode->row()->id;
            $tname = $gettrasnportmode->row()->name;
        }
        if ( $shipment_id == "" ) {
            $shipment_id = "SVK" . time();
        }
        $ship_row_id = 0;
        $ship_arr    = array(
            'shipid'           => $shipment_id,
            'txnid'            => $shipment_id,
            'trucktype'        => $tname,
            'pickupcnt'        => '1',
            'dropcnt'          => '1',
            'insertusr'        => $pickup_custid,
            'carrier'          => '0',
            'insertuserdate'   => $cdate,
            'enddate'          => $enddate,
            'insdate'          => $cdate,
            'upddate'          => $cdate,
            'reason'           => 'SHIPMENT',
            'purpose'          => 'SEND INTEGRATION',
            'ship_object'      => 'SHIPMENT',
            'logdate'          => $cdate,
            'transport_mode'   => $popupmodeof_trasnport,
            'domainname'       => $branch_code,
            'company_code'     => $company_code,
            'branch_code'      => $branch_code,
            'product'          => $product,
            'freight_term'     => '60',
            'freight_termname' => 'Free of Charge',
            'incoterm'         => $incoterm,
            'modeoftransport'  => $tid,
            'unitspec'         => 1
        );
        $chk_shipid  = $this->db->query( "SELECT id FROM tb_shipments WHERE shipid LIKE '" . $shipment_id . "'" );

        if ( $chk_shipid->num_rows() > 0 ) {
            $ship_row_id = $chk_shipid->row()->id;
            $this->db->where( array( 'id' => $ship_row_id ) )->update( "tb_shipments", $ship_arr );
        } else {

            $ship_arr['createdon'] = $cdate;
            $ship_ins              = $this->db->insert( "tb_shipments", $ship_arr );
            $ship_row_id           = $this->db->insert_id();
        }
        /* Remove API check to get the lat and long if they are entered in bussiness partners */
        if ($pickup_latitude != "" && $pickup_longitude != "" && $drop_latitude != "" && $drop_longitude != "") {
            $lat1 = $pickup_latitude;
            $lng1 = $pickup_longitude;
            $lat2 = $drop_latitude;
            $lng2 = $drop_longitude;
        } else {
            $add1 = implode(",", [$pickup_street, $pickup_city, $pickup_country, $pickup_pincode]);
            $add2 = implode(",", [$drop_street, $drop_city, $drop_country, $drop_pincode]);
            $data = getlatlngsbyplace($add1);
            $lat1 = @$data[0];
            $lng1 = @$data[1];
            $data = getlatlngsbyplace($add2);
            $lat2 = @$data[0];
            $lng2 = @$data[1];
        }
        $customer_id = $pickup;
        if ( $customer_id == "0" || $customer_id == "" ) {
            if ( $popupcustomer_id != "" && $popupcustomer_id != "0" ) {
                $getcustomerid = $this->db->select( "id" )->get_where( "tb_customers", array( 'code' => $popupcustomer_id, 'user_id' => $user_id, 'status' => '1' ) );
                if ( $getcustomerid->num_rows() > 0 ) {
                    $customer_id = $getcustomerid->row()->id;
                }
            }
        }
        if ( $this->session->userdata( 'company_code' ) == 'NZKN' ) {
            if ( $product == "" ) {
                $product = "KN AsiaLink";
            }
            if ( $popupmodeof_trasnport == "" ) {
                $popupmodeof_trasnport = "LTL";
            }
            if ( $service == "" ) {
                $service = "19";
            }
        }
        $curtz                   = $this->session->userdata( "usr_tzone" )['timezone'];
        $logdate                 = date( 'Y-m-d H:i:s' );
        $getactual               = getdatetimebytimezone( DFLT_TZ, $logdate, $curtz );
        $logdate                 = $getactual['datetime'];
        $getpickup               = getdatetimebytimezone( DFLT_TZ, $earlyquickbook_pickup, $curtz );
        $earlyquickbook_pickup   = $getpickup['datetime'];
        $getlpickup              = getdatetimebytimezone( DFLT_TZ, $latequickbook_pickup, $curtz );
        $latequickbook_pickup    = $getlpickup['datetime'];
        $getdelivery             = getdatetimebytimezone( DFLT_TZ, $earlyquickbook_delivery, $curtz );
        $earlyquickbook_delivery = $getdelivery['datetime'];
        $getldelivery            = getdatetimebytimezone( DFLT_TZ, $latequickbook_delivery, $curtz );
        $latequickbook_delivery  = $getldelivery['datetime'];
        $childid                 = 0;
        if ( $this->session->userdata( 'childid' ) ) {
            $childid = $this->session->userdata( 'childid' );
        }
        $created_source = '3';
        if($branch_code == "INCL"){
            $created_source = '15';
            $ordtypechk = $this->common->gettblrowdata(array("id"=>$order_type),"ordtype_code","tb_order_types",0,0);
            if(count($ordtypechk)>0){
                if($ordtypechk['ordtype_code'] == "Return"){
                    $created_source = '16';
                }
            }
        }
        $orderinfo    = array(
            'goods_value'       => '0.00',
            'shipment_id'       => $ship_row_id,
            'customer_id'       => $customer_id,
            'product'           => $product,
            'company_code'      => $company_code,
            'branch_code'       => $branch_code,
            'createdon'         => $cdate,
            'pickup_datetime'   => $earlyquickbook_pickup,
            'delivery_datetime' => $earlyquickbook_delivery,
            'pickup_endtime'    => $latequickbook_pickup,
            'drop_endtime'      => $latequickbook_delivery,
            'goods_value'       => $goods_value,
            'currency'          => $currency,
            'drop_custid'       => $drop_id,
            'drop_partyid'      => $drop_id,
            'user_id'           => $user_id,
            'sub_uid'           => $childid,
            'pickup_custid'     => $pickup_custid,
            'pickup_partyid'    => $pickup_custid,
            'pickup_country'    => $pickup_country,
            'pickup_city'       => $pickup_city,
            'pickup_pincode'    => $pickup_pincode,
            'pickup_company'    => $pickup_name,
            'pickup_address1'   => $pickup_street,
            'pickup_address2'   => $pickup_state,
            'delivery_country'  => $drop_country,
            'delivery_city'     => $drop_city,
            'delivery_pincode'  => $drop_pincode,
            'delivery_company'  => $drop_name,
            'delivery_address1' => $drop_street,
            'delivery_address2' => $drop_state,
            'transport_mode'    => $popupmodeof_trasnport,
            'plat'              => $lat1,
            'plng'              => $lng1,
            'dlat'              => $lat2,
            'dlng'              => $lng2,
            'is_created'        => '1',
            'modeoftransport'   => $tid,
            'created_source'    => $created_source,
            'createdon'         => $logdate

        );
        $ins_order    = $this->db->insert( "tb_orders", $orderinfo );
        $order_id     = $this->db->insert_id();
        $get_country  = $this->db->select( 'country_code,company_code' )->get_where( "tb_users", array( 'id' => $user_id ) );
        $country_code = $get_country->row()->country_code;
        $company_code = $get_country->row()->company_code;
        $genord       = array( "user_id" => $user_id, "order_id" => $order_id, "country_code" => $country_code, "company_code" => $company_code );
        $booking_id   = generatebookingid( $genord );
        $invtypes     = makeorderinvolvedpartiestype( $customer_id, $order_id, "CUSTOMER" );
        insertOrdersRefFileLineIdentifier(['pickupCity' => $pickup_city, 'pickupState' => $pickup_state, 'pickupCountry' => $pickup_country, 'dropCity' => $drop_city, 'dropState' => $drop_state, 'dropCountry' => $drop_country, 'companyCode' => $company_code, 'branchCode' => $branch_code, 'orderRowId' => $order_id, 'date' => $logdate]);
        $upd          = $this->db->where( array( 'id' => $order_id ) )->update( "tb_orders", array( 'order_id' => $booking_id ) );
        $details      = array(
            'shipper_id'      => $_POST['quickbookshipper_id'],
            'service'         => $service,
            'delivery_term'   => $delivery_terms,
            'incoterm'        => $incoterm,
            /*'purchase_order'  => $porder,*/
            'notify_party'    => $notify_party,
            'department_code' => $department_code,
            'createdon'       => $cdate,
            'order_row_id'    => $order_id,
            'order_id'        => $booking_id,
            'order_type'      => $popuporder_type
        );
        $this->db->insert( 'tb_order_details', $details );
        /**
         * AU delivery note
         */
        if($this->session->userdata('company_code') == 'KNAU'){
            $this->load->helper('aumacpac_helper');
            au_deliverynote_customer_specific($order_id,$booking_id);
        }

        $order_shipper_id   = isset( $_POST['quickbookshipper_id'] ) ? $_POST['quickbookshipper_id'] : "";
        $pickup_address     = $pickup_street . "," . $pickup_city . "," . $pickup_state;
        $shipper_address    = array( 'order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'location_id' => $pickup_city, 'street' => $pickup_street, 'state' => $pickup_state, 'address' => $pickup_address, 'pincode' => $pickup_pincode, 'country' => $pickup_country, 'user_id' => $user_id );
        $chk_shipperaddress = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'status' => '1' ) );
        if ( $chk_shipperaddress->num_rows() > 0 ) {
            $shipperadd_id = $chk_shipperaddress->row()->id;
            $upd_add       = $this->db->where( array( 'id' => $shipperadd_id ) )->update( "tbl_orderparty_address", $shipper_address );
        } else {
            $shipper_address['createdon'] = $cdate;
            $this->db->insert( "tbl_orderparty_address", $shipper_address );
            $shipperadd_id = $this->db->insert_id();
        }
        $drop_address        = $drop_street . "," . $drop_city . "," . $drop_state;
        $delivery_address    = array( 'order_id' => $order_id, 'party_master_id' => $delivery, 'location_id' => $drop_city, 'street' => $drop_street, 'state' => $drop_state, 'address' => $drop_address, 'pincode' => $drop_pincode, 'country' => $drop_country, 'user_id' => $user_id );
        $chk_deliveryaddress = $this->db->select( "id" )->get_where( "tbl_orderparty_address", array( 'order_id' => $order_id, 'party_master_id' => $delivery, 'status' => '1' ) );
        if ( $chk_deliveryaddress->num_rows() > 0 ) {
            $dropadd_id = $chk_deliveryaddress->row()->id;
            $upd_add    = $this->db->where( array( 'id' => $dropadd_id ) )->update( "tbl_orderparty_address", $delivery_address );
        } else {
            $delivery_address['createdon'] = $cdate;
            $this->db->insert( "tbl_orderparty_address", $delivery_address );
            $dropadd_id = $this->db->insert_id();
        }
        $shipment_name = "BOXES";
        if ( $order_cargo_id != "" ) {
            $cargo_ids = array();
            $cargo_ids = explode( ',', $order_cargo_id );

            for ( $i = 0; $i < count( $cargo_ids ); $i ++ ) {
                $length   =
                $width = $height = $weight = $volume = $ldm = $second_weight = $second_volume = 0;
                $quantity = 1;
                if ( $cargo_ids[ $i ] != "" ) {
                    $getcargo_details = $this->db->query( "SELECT cargo_type,goods_description,length,width,height,weight,volumetric_weight,ldm,volume,second_weight,second_volume,quantity FROM tb_cargo_details WHERE id='" . $cargo_ids[ $i ] . "'" );
                    $length           = $width = $height = $weight = $volume = $quantity = $cargo_type = $description = "";
                    if ( $getcargo_details->num_rows() > 0 ) {
                        $length            = $getcargo_details->row()->length;
                        $width             = $getcargo_details->row()->width;
                        $height            = $getcargo_details->row()->height;
                        $weight            = $getcargo_details->row()->weight;
                        $volumetric_weight = $getcargo_details->row()->volumetric_weight;
                        $volume            = $getcargo_details->row()->volume;
                        $quantity          = $getcargo_details->row()->quantity;
                        $shipment_name     = $cargo_type = $getcargo_details->row()->cargo_type;
                        $description       = $getcargo_details->row()->goods_description;
                        $ldm               = $getcargo_details->row()->ldm;
                        $second_weight     = $getcargo_details->row()->second_weight;
                        $second_volume     = $getcargo_details->row()->second_volume;
                    }
                    $gethandling_unit = $this->db->query( "SELECT id FROM tbl_shipunit_types WHERE unit_name LIKE '" . $cargo_type . "'" );
                    $handling_unit    = "";
                    if ( $gethandling_unit->num_rows() > 0 ) {
                        $handling_unit = $gethandling_unit->row()->id;
                    } else {
                        $handlingunit_ar = array( 'unit_name' => $cargo_type, 'description' => $cargo_type, 'user_id' => $user_id, 'created_at' => $cdate, 'status' => '1' );
                        $this->db->insert( "tbl_shipunit_types", $handlingunit_ar );
                        $handling_unit = $this->db->insert_id();
                    }
                    $cargo = array(
                        'order_id'          => $order_id,
                        'cargo_id'          => $cargo_ids[ $i ],
                        'status'            => '1',
                        'length'            => $length,
                        'width'             => $width,
                        'height'            => $height,
                        'weight'            => $weight,
                        'volume'            => $volume,
                        'quantity'          => $quantity,
                        'cargo_content'     => $description,
                        'quantity_type'     => $cargo_type,
                        'handling_unit'     => $handling_unit,
                        'volumetric_weight' => $volumetric_weight,
                        'volweight_uom'     => 'kg',
                        'ldm'               => $ldm,
                        'second_weight'     => $second_weight,
                        'second_volume'     => $second_volume
                    );
                    $orderCargoId = $this->common->insertTableData("tb_order_cargodetails", $cargo);
                    $checkDgGoods = $this->common->gettbldata(['order_cargo_id' => $cargo_ids[$i], 'status' => '1'], "id", "tb_order_dg_goods", 0, 0);
                    foreach ($checkDgGoods as $eachLine) {
                        $this->common->updatetbledata("tb_order_dg_goods", ['order_cargo_id' => $orderCargoId, 'order_id' => $order_id], ['id' => $eachLine['id']]);
                    }
                }
            }
        }
        $total_weight = $total_volume = $total_quantity = 0;
        $gettotal     = $this->db->query( "SELECT sum(weight) as total_weight,sum(volume) as total_volume,sum(quantity) as total_quantity FROM tb_order_cargodetails WHERE order_id='" . $order_id . "'" );
        if ( $gettotal->num_rows() > 0 ) {
            $total_volume   = $gettotal->row()->total_volume;
            $total_weight   = $gettotal->row()->total_weight;
            $total_quantity = $gettotal->row()->total_quantity;
        }
        $cargo_forship = array();
        $getcargos     = $this->db->query( "SELECT quantity_type FROM tb_order_cargodetails WHERE order_id ='" . $order_id . "'" );
        if ( $getcargos->num_rows() > 0 ) {
            foreach ( $getcargos->result() as $res ) {
                $cargo_forship[] = $res->quantity_type;
            }
        }
        $unitspec = "";
        if ( ! empty( $cargo_forship ) ) {
            $unitspec = implode( ',', $cargo_forship );
        }
        $updship   = $this->db->where( array( 'id' => $ship_row_id ) )->update( "tb_shipments", array( 'unitspec' => $unitspec, 'txncode' => $booking_id ) );
        $upd_order = $this->db->where( array( 'id' => $order_id ) )->update( "tb_orders", array( 'volume' => $total_volume, 'weight' => $total_weight, 'quantity' => $total_quantity ) );
        $ids       = array();
        if ( $reference_ids != "0" ) {
            $refids = explode( ',', $reference_ids );
        }
        $order_ref_ids = array();
        if ( $quickbook_order_reference_ids != "0" ) {
            $order_ref_ids = explode( ',', $quickbook_order_reference_ids );
        }
        if ( ! empty( $order_ref_ids ) ) {
            for ( $i = 0; $i < count( $order_ref_ids ); $i ++ ) {
                if ( $order_ref_ids[ $i ] != "" ) {
                    $upd = $this->db->where( array( 'id' => $order_ref_ids[ $i ] ) )->update( "tb_order_references", array( 'order_id' => $order_id ) );
                }
            }
        }
        if ( $shipment_id != "" && $this->session->userdata('company_code') != 'KNAU') {
            $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'DQ', 'ref_value' => $shipment_id, 'createdon' => $cdate );
            $ins     = $this->db->insert( 'tb_order_references', $ins_ref );

        }
        if ( $driverdelivery_popup != "" ) {
            $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'ORD_DLVINST', 'ref_value' => $driverdelivery_popup, 'createdon' => $cdate );
            $ins     = $this->db->insert( 'tb_order_references', $ins_ref );

        }
        if ( $driverpickup_popup != "" ) {
            $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'ORD_PIKINST', 'ref_value' => $driverpickup_popup, 'createdon' => $cdate );
            $ins     = $this->db->insert( 'tb_order_references', $ins_ref );

        }
        if ( $porder != "" ) {
            $ins_ref = array( 'order_id' => $order_id, 'reference_id' => 'PO', 'ref_value' => $porder, 'createdon' => $cdate );
            $ins     = $this->db->insert( 'tb_order_references', $ins_ref );

        }
        if (checkAccessConditions("CHECK_STS_REFERENCE_COUNTRIES", $company_code )) {
            $ins_ref = ['order_id' => $order_id, 'reference_id' => 'STS'];
            $checkSTSRef = $this->common->gettblrowdata($ins_ref, "id", "tb_order_references", 0, 0);
            if (count($checkSTSRef) == 0) {
                $ins_ref['ref_value'] = "Pending";
                $this->common->insertTableData("tb_order_references", $ins_ref);
            }
        }

        $sub_cut_parties = array();
        $sub_cut_parties['0'] = $order_shipper_id;
        $sub_cut_parties['1'] = $delivery;
        $sub_cut_parties['2'] = '0';
        $sub_cut_parties['3'] = '0';
        if (!empty($sub_cut_parties)) {
            subcustpartiesinsert($order_id, $booking_id, $sub_cut_parties);
        }
        $pref_arr = array(
            'pickup'         => strtoupper( $pickup_country ),
            'pickup_state'   => strtoupper( $pickup_state ),
            'pickup_city'    => strtoupper( $pickup_city ),
            'pickup_pincode' => $pickup_pincode,
            'drop'           => strtoupper( $drop_country ),
            'drop_state'     => strtoupper( $drop_state ),
            'drop_city'      => strtoupper( $drop_city ),
            'drop_pincode'   => $drop_pincode,
            'customer_id'    => $popupcustomer_id,
            'service'        => $service,
            'product'        => $product,
            'user_id'        => $user_id,
            'company_code'   => $company_code,
            'order_id'       => $order_id,
            'order_type'     => $popuporder_type,
            'customer_row_id'=> $customer_id,
        );
        $post = $this->input->post(null, true);
        $customerProfileId = $post['customerProfileId'] ?? 0;
        $rateServiceRowId = $post['rateServiceRowId'] ?? 0;
        $rateOfferingRowId = $post['rateOfferingRowId'] ?? 0;
        $rateRecordRowId = $post['rateRecordRowId'] ?? 0;
        $laneRowId = $post['laneRowIdForBook'] ?? 0;
        if (!in_array(0, [$customerProfileId, $rateServiceRowId, $rateOfferingRowId, $rateRecordRowId, $laneRowId], true)) {
            $this->ratemanagement->addratesForOrderFromRateEnquiry(
                ['customerId' => $popupcustomer_id, 'orderRowId' => $order_id, 'customerProfile' => $customerProfileId, 'rateServiceRowId' => $rateServiceRowId, 'rateOfferingRowId' => $rateOfferingRowId, 'rateRecordRowId' => $rateRecordRowId, 'currency' => $this->session->userdata("usr_tzone")['currency'], 'userId' => $user_id, 'laneRowId' => $laneRowId, 'vendorIdFromProfile' => $post['vendorIdFromProfile'] ?? 0, 'vendorCodeFromProfile' => $post['vendorCodeFromProfile'] ?? ""]
            );
        } else {
            $this->ratemanagement->addrecodfororderinsertion($pref_arr);
        }
        /*if($this->session->userdata('usr_tzone')['country'] == "RU"){*/

        if ( $order_id != "" && $customer_id != "" ) {
            $pickupinfo['country']       = trim( $pickup_country );
            $pickupinfo['state']         = trim( $pickup_state );
            $pickupinfo['city']          = trim( $pickup_city );
            $pickupinfo['region']        = trim( $pickup_street );
            $pickupinfo['zipcode']       = trim( $pickup_pincode );
            $pickupinfo['order_country'] = trim( $pickup_country );
            $pickupinfo['order_city']    = trim( $pickup_city );
            $pickupinfo['order_zipcode'] = trim( $pickup_pincode );
            $pickupinfo['stoptype']      = "P";
            $dropinfo['country']         = trim( $drop_country );
            $dropinfo['order_country']   = trim( $drop_country );
            $dropinfo['order_city']      = trim( $drop_city );
            $dropinfo['order_zipcode']   = trim( $drop_pincode );
            $dropinfo['state']           = trim( $drop_state );
            $dropinfo['city']            = trim( $drop_city );
            $dropinfo['region']          = trim( $drop_street );
            $dropinfo['zipcode']         = trim( $drop_pincode );

            $dropinfo['stoptype'] = "D";
            $pickupgeocode        = checkgeocode( $pickupinfo );
            $dropgeocode          = checkgeocode( $dropinfo );
            if ( ! empty( $pickupgeocode ) && ! empty( $dropgeocode ) ) {
                $pickupgeocode['stoptype']      = "P";
                $dropgeocode['stoptype']        = "D";
                $pickupgeocode['order_country'] = trim( $pickup_country );
                $pickupgeocode['order_city']    = trim( $pickup_city );
                $pickupgeocode['order_zipcode'] = trim( $pickup_pincode );
                $dropgeocode['order_country']   = trim( $drop_country );
                $dropgeocode['order_city']      = trim( $drop_city );
                $dropgeocode['order_zipcode']   = trim( $drop_pincode );

                //-------------------------------- //for auto route
                $pickupgeocode['cargo'] = $cargo;
                $dropgeocode['cargo'] =  $cargo;
                //--------------------------------
                $pickuproute                    = getcust_routeautomate( $customer_id, $pickupgeocode );
                $droproute                      = getcust_routeautomate( $customer_id, $dropgeocode );
                if ( ! empty( $pickuproute ) && ! empty( $droproute ) ) {
                    $orderinfo['id']             = $order_id;
                    $orderinfo['order_id']       = $booking_id;
                    $orderinfo['shipment_name']  = $shipment_name;
                    $orderinfo['customer_phone'] = $customer_phone;
                    $orderinfo['customer_email'] = $customer_email;
                    $orderinfo['volume']         = $total_volume;
                    $orderinfo['weight']         = $total_weight;
                    $orderinfo['quantity']       = $total_quantity;
                    $orderinfo['quantity']       = $total_quantity;
                    $shipment                    = createshipmentbyorder( $pickuproute, $orderinfo );
                } else {
                    //-------------------------------- //for auto route
                    $pickupinfo['cargo'] = $cargo;
                    $dropinfo['cargo'] =  $cargo;
                    //--------------------------------
                    $pickuproute1 = getcust_routeautomate( $customer_id, $pickupinfo );
                    $droproute1   = getcust_routeautomate( $customer_id, $dropinfo );
                    if ( ! empty( $pickuproute1 ) && ! empty( $droproute1 ) ) {
                        $orderinfo['id']             = $order_id;
                        $orderinfo['order_id']       = $booking_id;
                        $orderinfo['shipment_name']  = $shipment_name;
                        $orderinfo['customer_phone'] = $customer_phone;
                        $orderinfo['customer_email'] = $customer_email;
                        $orderinfo['volume']         = $total_volume;
                        $orderinfo['weight']         = $total_weight;
                        $orderinfo['quantity']       = $total_quantity;
                        $orderinfo['quantity']       = $total_quantity;
                        $shipment                    = createshipmentbyorder( $pickuproute1, $orderinfo );
                    }
                }
            } else {

                //-------------------------------- //for auto route
                $pickupinfo['cargo'] = $cargo;
                $dropinfo['cargo'] =  $cargo;
                //--------------------------------

                $pickuproute1 = getcust_routeautomate( $customer_id, $pickupinfo );
                $droproute1   = getcust_routeautomate( $customer_id, $dropinfo );
                if ( ! empty( $pickuproute1 ) && ! empty( $droproute1 ) ) {
                    $orderinfo['id']             = $order_id;
                    $orderinfo['order_id']       = $booking_id;
                    $orderinfo['shipment_name']  = $shipment_name;
                    $orderinfo['customer_phone'] = $customer_phone;
                    $orderinfo['customer_email'] = $customer_email;
                    $orderinfo['volume']         = $total_volume;
                    $orderinfo['weight']         = $total_weight;
                    $orderinfo['quantity']       = $total_quantity;
                    $orderinfo['quantity']       = $total_quantity;
                    $shipment                    = createshipmentbyorder( $pickuproute1, $orderinfo );
                }
            }
            $checkTripForOrder = $this->common->gettblrowdata("id='" . $order_id . "' AND shift_id >0", "id,shift_id", "tb_orders", 0, 0);
            if (!empty($checkTripForOrder)) {
                $this->load->library('notifytrigger');
                $this->notifytrigger->sendNotificationToCarrier($checkTripForOrder['shift_id'], $company_code, 'CR');
            }
        }
        /*}*/
        $this->ordernotify( 'booking_create', $order_id );
        if ( $order_id != "" && $order_id != '0' ) {
            try {
                $this->altovaordercreation->sendOrderToAltova($order_id);
            } catch (Exception $ex) {
                log_message("error", "Some Problem occured!, While Sending Order to Altova ".$ex->getMessage());
            }
            $this->session->set_flashdata( 'success_msg', 'Order Created Successfully - ' . $booking_id );
            if ($cust_id !=""){
                 redirect( 'orders/orderslist/' . $order_id );
            }
            else
            {
                 redirect( 'orders/orderslist/' . $order_id );
            }
        } else {
            redirect( "orders" );
        }

    }

    public function addreferencedetails() {
        $companyCode = $this->session->userdata("company_code");
        $branchCode = $this->session->userdata("branch_code");
        $id    = $this->db->escape_str($this->input->post( 'reference_id' ));
        $name  = $this->db->escape_str($this->input->post( 'reference_name' ));
        $value = $this->db->escape_str($this->input->post( 'reference_value' ));
        if ( $id == "ETA" ) {
            $chkrtime = getdatetimebytimezone( DFLT_TZ, $value, $this->session->userdata( 'usr_tzone' )['timezone'] );
            $value    = $chkrtime['datetime'];
        }
        $row_id       = isset( $_POST['ref_row_id'] ) ? $this->db->escape_str($_POST['ref_row_id']) : "";
        $order_id     = isset( $_POST['order_id'] ) ? $this->db->escape_str($_POST['order_id']) : "0";
        $order_ref_id = isset( $_POST['order_ref_id'] ) ? $this->db->escape_str($_POST['order_ref_id']) : "0";
        $cdate        = date( 'Y-m-d H:i:s' );
        $ins_id       = $order_ins_id = 0;
        if ( $row_id == "" ) {
            $ins_arr = array( 'name' => $id, 'description' => $name, 'createdon' => $cdate );
            $chk_ar  = $this->db->select( 'id' )->get_where( 'tb_reference_master', array( 'name' => $id, 'status' => '1' ) );
            if ( $chk_ar->num_rows() == 0 ) {
                $ins    = $this->db->insert( "tb_reference_master", $ins_arr );
                $ins_id = $this->db->insert_id();
            } else {
                $ins_id = $chk_ar->row()->id;
            }

            if ( $ins_id != "" ) {
                $ins_order    = array( 'reference_id' => $id, 'ref_value' => $value, 'createdon' => $cdate, 'order_id' => $order_id );
                $ins          = $this->db->insert( "tb_order_references", $ins_order );
                $order_ins_id = $this->db->insert_id();
                $orderReferenceValueInsert = xbdrNotificationInsert($id, $companyCode, $value, $order_id, $branchCode);
            }
        } else {
            $upd_ar = array( 'name' => $id, 'description' => $name );
            if ( $id == 'PO' ) {
                $po_val = $value;
                $upd    = $this->db->where( array( 'order_row_id' => $order_id ) )->update( "tb_order_details", array( 'purchase_order' => $po_val ) );
            }
            if ( $id == 'DQ' ) {
                $dq_val      = $value;
                $chkshipment = $this->db->query( "SELECT s.id FROM tb_shipments s,tb_orders o WHERE o.id='" . $order_id . "' AND o.shipment_id=s.id" );
                if ( $chkshipment->num_rows() > 0 ) {
                    $shipment_id = $chkshipment->row()->id;
                    $upd         = $this->db->where( array( 'id' => $shipment_id ) )->update( "tb_shipments", array( 'shipid' => $dq_val, 'txnid' => $dq_val ) );
                }
            }
            $this->db->where( array( 'id' => $row_id ) )->update( "tb_reference_master", $upd_ar );
            if ( $order_id != "" ) {
                $ins_ar = array( 'order_id' => $order_id, 'reference_id' => $id, 'ref_value' => $value, 'createdon' => $cdate );
                $chk    = $this->db->select( 'id' )->get_where( 'tb_order_references', array( 'order_id' => $order_id, 'reference_id' => $id, 'status' => '1' ) );
                if ( $chk->num_rows() == 0 ) {
                    $ins_ar['createdon'] = $cdate;
                    $order_ins           = $this->db->insert( "tb_order_references", $ins_ar );
                    $order_ins_id        = $this->db->insert_id();
                } else {
                    $this->db->where( array( 'id' => $chk->row()->id ) )->update( "tb_order_references", $ins_ar );
                }
            } else {
                $chk    = $this->db->select( 'id' )->get_where( 'tb_order_references', array( 'reference_id' => $id, 'status' => '1' ) );
                $ins_ar = array( 'order_id' => '0', 'reference_id' => $id, 'ref_value' => $value, 'createdon' => $cdate );
                if ( $chk->num_rows() == 0 ) {
                    $order_ins    = $this->db->insert( "tb_order_references", $ins_ar );
                    $order_ins_id = $this->db->insert_id();
                } else {
                    $order_ins_id = $chk->row()->id;
                    $upd          = $this->db->where( array( 'id' => $order_ins_id ) )->update( "tb_order_references", $ins_ar );
                }
            }
            $ins_id = $row_id;

        }
        if ((checkAccessConditions('CHECK_STATUS_RETRIGGER_COMPANY', $companyCode)) && (checkAccessConditions('CHECK_STATUS_RETRIGGER_REFERENCE', $id))) {
            log_message("error", "Edited Order Reference " . $order_id . " - " . $id . " - " . $value);
            try {
                $this->load->library('orderstatusretriggertoedi214');
                $this->orderstatusretriggertoedi214->retriggeredPreviousStatus($order_id);
            } catch (Exception $ex) {
                log_message("error", "Some Problem occured!, While Sending Order Referene to Altova " . $ex->getMessage());
            }
        }
        $arr = array( 'ins_id' => $ins_id, 'order_ins_id' => $order_ins_id );
        echo json_encode( $arr );
    }

    public function addpopupreferencedetails() {
        $companyCode = $this->session->userdata("company_code");
        $branchCode = $this->session->userdata("branch_code");
        $id           = $this->db->escape_str($this->input->post( 'reference_id' ));
        $name         = $this->db->escape_str($this->input->post( 'reference_name' ));
        $value        = $this->db->escape_str($this->input->post( 'reference_value' ));
        $row_id       = isset( $_POST['ref_row_id'] ) ? $this->db->escape_str($_POST['ref_row_id']) : "";
        $order_id     = isset( $_POST['order_id'] ) ? $this->db->escape_str($_POST['order_id']) : "0";
        $order_ref_id = isset( $_POST['order_ref_id'] ) ? $this->db->escape_str($_POST['order_ref_id']) : "0";
        $cdate        = date( 'Y-m-d H:i:s' );
        $ins_id       = $order_ins_id = 0;
        if ($row_id == "" && $id != 'DQ') {
            $ins_arr = array( 'name' => $id, 'description' => $name, 'createdon' => $cdate );
            $chk_ar  = $this->db->select( 'id' )->get_where( 'tb_reference_master', array( 'name' => $id, 'status' => '1' ) );
            if ( $chk_ar->num_rows() == 0 ) {
                $ins    = $this->db->insert( "tb_reference_master", $ins_arr );
                $ins_id = $this->db->insert_id();
            } else {
                $ins_id = $chk_ar->row()->id;
            }
            if ( $ins_id != "" ) {
                $ins_order    = array( 'reference_id' => $id, 'ref_value' => $value, 'createdon' => $cdate, 'order_id' => $order_id );
                $ins          = $this->db->insert( "tb_order_references", $ins_order );
                $order_ins_id = $this->db->insert_id();
                $orderReferenceValueInsert = xbdrNotificationInsert($id, $companyCode, $value, $order_id, $branchCode);
            }
        } else {
            $upd_ar = array( 'name' => $id, 'description' => $name );

            $this->db->where( array( 'id' => $row_id ) )->update( "tb_reference_master", $upd_ar );
            if ( $order_id != "" ) {
                $ins_ar = array( 'order_id' => $order_id, 'reference_id' => $id, 'ref_value' => $value, 'createdon' => $cdate );
                $chk    = $this->db->select( 'id' )->get_where( 'tb_order_references', array( 'order_id' => $order_id, 'reference_id' => $id, 'status' => '1', 'id' => $order_ref_id ) );
                if ( $chk->num_rows() == 0 ) {
                    $ins_ar['createdon'] = $cdate;
                    $order_ins           = $this->db->insert( "tb_order_references", $ins_ar );
                    $order_ins_id        = $this->db->insert_id();
                } else {
                    $this->db->where( array( 'id' => $chk->row()->id ) )->update( "tb_order_references", $ins_ar );
                }
            } else {
                $chk    = $this->db->select( 'id' )->get_where( 'tb_order_references', array( 'reference_id' => $id, 'status' => '1', 'id' => $order_ref_id ) );
                $ins_ar = array( 'order_id' => '0', 'reference_id' => $id, 'ref_value' => $value, 'createdon' => $cdate );
                if ( $chk->num_rows() == 0 ) {
                    $order_ins    = $this->db->insert( "tb_order_references", $ins_ar );
                    $order_ins_id = $this->db->insert_id();
                } else {
                    $order_ins_id = $chk->row()->id;
                    $upd          = $this->db->where( array( 'id' => $order_ins_id ) )->update( "tb_order_references", $ins_ar );
                }
            }
            $ins_id = $row_id;

        }
        $arr = array( 'ins_id' => $ins_id, 'order_ins_id' => $order_ins_id );
        echo json_encode( $arr );
    }

	public function deleteorderreferencedetails()
    {
        $order_id = isset($_POST['order_id']) ? $this->db->escape_str($_POST['order_id']) : "0";
        $ref_id = isset($_POST['ref_id']) ? $this->db->escape_str($_POST['ref_id']) : "0";
        if ($order_id != '0' && $ref_id != '0') {
            $getref_name = $this->db->select('name')->get_where("tb_reference_master", ['id' => $ref_id
            ]);
            if ($getref_name->num_rows() > 0) {
                $ref_id = $getref_name->row()->name;
            }
            $chkdetails = $this->db->select('id')->get_where("tb_order_references", [
                'order_id' => $order_id,
                'id' => $ref_id,
                'status' => '1'
            ]);
            if ($chkdetails->num_rows() > 0) {
                $upd = $this->db->where([
                    'id' => $chkdetails->row()->id
                ])
                    ->update("tb_order_references", [
                        'status' => '0'
                    ]);
                if ($upd) {
                    echo "1";
                } else {
                    echo "0";
                }
            }
        }
    }

    public function getotherreferencedetails() {
        $post = array();
        $post = $this->input->post(NULL,TRUE);
        $order_id = isset($post['order_id']) ? $this->db->escape_str($post['order_id']) : "";
        
        $type = isset($post['type']) ? $this->db->escape_str($post['type']) : "";
        $ref_ids = isset($post['ref_ids']) ? $this->db->escape_str($post['ref_ids']) : array();
        $getrefer_rows = 0;
        $refer = $refids = array();
        $whr = "";
        $action = "";
        //log_message("error","order_id:".$order_id);
        if ($order_id != "") {
            $getrefer = $this->db->query("SELECT r.id,r.name,r.description,o.order_shortNo,o.id as order_ref_id,o.reference_id,o.ref_value as order_value FROM tb_reference_master r,tb_order_references o WHERE o.order_id='" . $order_id . "' AND o.reference_id =r.name  AND r.status='1' AND o.status='1' GROUP BY o.id ORDER BY r.createdon DESC");
            log_message("error","getrefer:".$this->db->last_query());
            $getrefer_rows = $getrefer->num_rows();
        } else {
            $whr = "";
            if ($ref_ids != "") {
                $refids = implode(',', $ref_ids);
                if (!empty($refids)) {
                    $whr .= " AND r.id IN (" . $refids . ") ";
                }
            }
            if (!empty($refids)) {
                $getrefer = $this->db->query("SELECT r.id,r.name,r.description,o.order_shortNo,o.id as order_ref_id,o.ref_value as order_value FROM tb_reference_master r,tb_order_references o WHERE r.name=o.reference_id  AND  o.status='1' AND r.status ='1' " . $whr . " GROUP BY r.id ORDER BY r.createdon DESC");
                log_message("error","getrefer1:".$this->db->last_query());
                $getrefer_rows = $getrefer->num_rows();
            }
        }
        //log_message("error","getrefer_rows:".$getrefer_rows);
        if ($getrefer_rows > 0) {
            foreach ($getrefer->result() as $res) {
                $order_shortNo = $res->order_shortNo;
                if ($type == 'popup') {
                    $action = "<button id=" . $res->id . " class='btn btn-primary btn-xs' onclick='editpopupreferencedetails(" . $res->id . "," . $res->order_ref_id . ",event)'><small><i class='glyphicon glyphicon-pencil'></i></small></button> <button id=" . $res->id . " class='btn btn-danger btn-xs' onclick='deletepopupreferencedetails(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>";
                } else {
                    if ($order_id != "") {
                        $info = array('id' => $res->id, 'name' => htmlentities($res->name,ENT_QUOTES), 'desc' => htmlentities($res->description,ENT_QUOTES), 'value' => htmlentities($res->order_value, ENT_QUOTES));
                        $info = htmlentities(json_encode($info));
                        $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft'> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='editreferencedetails(this," . $info . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='deletereferencedetailsbyorder(" . $res->order_ref_id . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowRefAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Reference</a></li>";
                    } else {
                        $action = "<button id=" . $res->id . " class='btn btn-primary btn-xs editparties' onclick='editreferencedetails(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-pencil'></i></small></button> <button id=" . $res->id . " class='btn btn-danger btn-xs deleteround' onclick='deletereferencedetails(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>";
                    }
                }
                $res_val = $res->order_value;
                if ($res_val != "") {
                    if (DateTime::createFromFormat('Y-m-d H:i:s', $res_val) !== FALSE) {
                        $chkrtime = getdatetimebytimezone($this->session->userdata('usr_tzone')['timezone'], $res_val, DFLT_TZ);
                        $res_val = $chkrtime['datetime'];
                    } else {
                        $res_val = $res_val;
                    }
                }
                $refer[] = array(
                    'id' => $res->name,
                    'name' => $res->description,
                    'value' => $res_val,
                    'order_shortNo' => $order_shortNo,
                    'action' => $action
                );
            }
        }
        //log_message("error","refer:".json_encode($refer));
        echo json_encode($refer);
    }

    public function getotherpopupreferencedetails() {
        $order_id          = isset( $_POST['order_id'] ) ? $this->db->escape_str($_POST['order_id']) : "";
        $type              = isset( $_POST['type'] ) ? $this->db->escape_str($_POST['type']) : "";
        $ref_ids           = isset( $_POST['ref_ids'] ) ? $this->db->escape_str($_POST['ref_ids']) : "";
        $popupref_order_id = isset( $_POST['popupref_order_id'] ) ? $this->db->escape_str($_POST['popupref_order_id']) : "";
        $getrefer_rows     = 0;
        $refer             = $popupref_order_ids = $refids = array();
        $whr               = "";
        $action            = "";
        if ( $order_id != "" ) {
            $getrefer      = $this->db->query( "SELECT r.id,r.name,r.description,o.reference_id,o.ref_value as order_value FROM tb_reference_master r,tb_order_references o WHERE o.order_id='" . $order_id . "' AND o.reference_id =r.name AND r.status='1' AND o.status='1' ORDER BY r.createdon DESC" );
            $getrefer_rows = $getrefer->num_rows();

        } else {
            if ( $ref_ids != "" ) {
                $refids = implode( ',', $ref_ids );
                if ( $popupref_order_id != "" ) {
                    $popupref_order_ids = implode( ',', $popupref_order_id );
                    if ( ! empty( $popupref_order_ids ) ) {
                        $whr = " AND o.id IN (" . $popupref_order_ids . ") ";
                    }
                }

                if ( ! empty( $refids ) ) {
                    $whr           .= " AND r.id IN (" . $refids . ") ";
                    $getrefer      = $this->db->query( "SELECT r.id,r.name,r.description,o.id as order_ref_id,o.ref_value as order_value FROM tb_reference_master r,tb_order_references o WHERE r.name=o.reference_id AND o.status='1' AND r.status ='1' " . $whr . " GROUP BY r.id ORDER BY r.createdon DESC" );
                    $getrefer_rows = $getrefer->num_rows();
                }
            }
        }
        if ( $getrefer_rows > 0 ) {
            foreach ( $getrefer->result() as $res ) {
                if ( $type == 'popup' ) {
                    $action = "<button id=" . $res->id . " class='btn btn-primary btn-xs' onclick='editpopupreferencedetails(" . $res->id . "," . $res->order_ref_id . ",event)'><small><i class='glyphicon glyphicon-pencil'></i></small></button> <button id=" . $res->id . " class='btn btn-danger btn-xs' onclick='deletepopupreferencedetails(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>";
                } else {
                    if ( $order_id != "" ) {
                        $action = "<button id=" . $res->id . " class='btn btn-primary btn-xs editparties' onclick='editreferencedetails(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-pencil'></i></small></button> <button id=" . $res->id . " class='btn btn-danger btn-xs deleteround' onclick='deletereferencedetailsbyorder(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>";
                    } else {
                        $action = "<button id=" . $res->id . " class='btn btn-primary btn-xs editparties' onclick='editreferencedetails(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-pencil'></i></small></button> <button id=" . $res->id . " class='btn btn-danger btn-xs deleteround' onclick='deletereferencedetails(" . $res->id . ",event)'><small><i class='glyphicon glyphicon-trash'></i></small></button>";
                    }

                }
                $refer[] = array( 'id' => $res->name, 'name' => $res->description, 'value' => $res->order_value, 'action' => $action );
            }
        }
        echo json_encode( $refer );
    }

    public function editreferencedetails() {
        $id          = $this->db->escape_str($this->input->post( 'id' ));
        $refer       = array();
        $get_details = $this->db->query( "SELECT r.*,o.ref_value as order_value FROM tb_reference_master r,tb_order_references o WHERE r.id='" . $id . "' AND r.name=o.reference_id" );
        if ( $get_details->num_rows() > 0 ) {
            $refer = array( 'id' => $get_details->row()->id, 'ref_id' => $get_details->row()->name, 'name' => $get_details->row()->description, 'value' => $get_details->row()->order_value );
        }
        echo json_encode( $refer );
    }

    public function editpopupreferencedetails() {
        $id           = $this->input->post( 'id' );
        $order_ref_id = isset( $_POST['order_ref_id'] ) ? $this->db->escape_str($_POST['order_ref_id']) : "";
        $refer        = array();
        $whr          = "";
        if ( $order_ref_id != "" ) {
            $whr .= " AND o.id='" . $order_ref_id . "'";
        }
        $get_details = $this->db->query( "SELECT r.*,o.ref_value as order_value FROM tb_reference_master r,tb_order_references o WHERE r.id='" . $id . "' AND r.name=o.reference_id " . $whr );
        if ( $get_details->num_rows() > 0 ) {
            $refer = array( 'order_ref_id' => $order_ref_id, 'id' => $get_details->row()->id, 'ref_id' => $get_details->row()->name, 'name' => $get_details->row()->description, 'value' => $get_details->row()->order_value );
        }
        echo json_encode( $refer );
    }

    public function viewpartylist()
    {
        //log_message("error","ViewPartyList:".json_encode($_POST));
        $parties     = [];
        $user_id     = $this->session->userdata('user_id');
        $type        = isset($_POST['type']) ? $_POST['type'] : "0";
        $party_type  = isset($_POST['party']) ? $_POST['party'] : "";
        $company_code  = isset($_POST['company_code']) ? $_POST['company_code'] : "";
        $branch_code  = isset($_POST['branch_code']) ? $_POST['branch_code'] : "";
        $customer_id = isset($_POST['customer_id']) ? $_POST['customer_id'] : "0";
        $check       = "";
        $custid      = "0";
        $whr         = $usrwhr         = "";
        if ($customer_id == "") {
            $customer_id = 0;
        }
        $chkcompanycode = $this->session->userdata('company_code');
        $permission     = checkuserpermissions();
        //log_message("error","permission:".json_encode($permission));
        if (in_array("businesspartners", $permission)) {
            if($company_code != ""){
                 $usrwhr = " AND m.company_code LIKE '" . $company_code . "' "; 
                 if($branch_code != ""){
                 $usrwhr = " AND m.branch_code LIKE '" . $branch_code . "' "; 
                }
            }else{
                $usrwhr = " AND m.company_code LIKE '" . $chkcompanycode . "' ";
            }

        } else {
            $usrwhr = " AND m.user_id='" . $user_id . "' ";
        }

        if ($this->session->userdata('cust_id') !== false) {
            $custid = $this->session->userdata('cust_id');
        }
        $subcusts = [];
        if ($custid != 0) {
            if ($this->session->userdata('sub_cust') !== false) {
                if ($this->session->userdata('sub_cust') != "") {
                    $subcusts = $this->session->userdata('sub_cust');
                }

                if (! empty($subcusts) && sizeof($subcusts) > 0) {
                    array_push($subcusts, $custid);
                } else {
                    array_push($subcusts, $custid);
                }
            } else {
                array_push($subcusts, $custid);
            }
        }
        $customer_code = [];
        if (! empty($subcusts)) {
            $select          = "code";
            $table           = "tb_customers";
            $customerdetails = $this->Order->getcustomercodebyids($select, $table, $subcusts);
            if (! empty($customerdetails)) {
                foreach ($customerdetails as $cust) {
                    $customer_code[] = $cust['code'];
                }
            }
        }
        /*if (! empty($customer_code)) {
            $whr = "AND m.customer_code IN ('" . implode("','", $customer_code) . "') ";
        }*/

        $party_type_whr = " ";
        if ($party_type != "") {
            $party_type_whr = " AND t.name = '" . $party_type . "' ";
        }

        $contact_ids = $master_ids = [];
        if ($customer_id != '0') {
            $getid = $this->common->gettblrowdata(['code' => $customer_id], "id", 'tbl_party_master', 0, 0);
            if (! empty($getid)) {
                $customer_row_id = $getid['id'];
                $get_custparties = $this->db->query("SELECT m.id as master_id,m.name as master_name,m.email as master_email_id,m.mobile as master_mobile,m.code,m.company_code,m.branch_code,m.location_id as city,m.country,m.street,t.name as party_name FROM tbl_party_master m,tbl_party_types t WHERE  m.company_code != '' AND m.company_code IS NOT NULL  AND m.branch_code != '' AND m.branch_code IS NOT NULL " . $usrwhr . " AND m.parent_id ='" . $customer_row_id . "' AND m.status=1 ANd m.code != '' AND m.code is NOT NULL AND m.code != '0' AND t.id=m.party_type_id  GROUP BY m.id ORDER BY m.id DESC");
                //log_message("error","Qry11:".$this->db->last_query());
                if ($get_custparties->num_rows() > 0) {
                    foreach ($get_custparties->result() as $res) {
                        if ($type == '1') {
                            $check = "<input type='radio' name='consigneelist' id='consigneelist_" . $res->master_id . "' class='consigneelist' onchange='selectparty(" . $res->master_id . ")' value='" . $res->master_id . "'>";
                        } else {
                            $check = "<input type='radio' name='consigneelist' id='consigneelist_" . $res->master_id . "' class='consigneelist' onchange='selectparty(" . $res->master_id . ")' value='" . $res->master_id . "'>";
                        }
                        $contact_ids[] = $res->master_id;
                        $master_ids[]  = $res->master_id;
                        $parties[]     = [
                            'check'        => $check,
                            'id'           => $res->code,
                            'name'         => $res->master_name,
                            'email'        => $res->master_email_id,
                            'mobile'       => $res->master_mobile,
                            'party_name'   => $res->party_name,
                            'company_code' => $res->company_code,
                            'branch_code'  => $res->branch_code,
                            'party_type'   => $party_type,
                            'city'         => $res->city,
                            'country'      => $res->country,
                            'street'       => $res->street,
                        ];
                    }
                }
            }
        }

        $get_parties = $this->db->query("SELECT m.id as master_id,m.name as master_name,
        m.email as master_email_id,m.mobile as master_mobile,m.code,m.company_code,
        m.branch_code,m.location_id as city,m.country,m.street,t.name as party_name
        FROM tbl_party_master m,tbl_party_types t WHERE m.company_code != ''
        AND m.company_code IS NOT NULL  AND m.branch_code != '' AND m.branch_code
        IS NOT NULL " . $whr . " " . $usrwhr . " AND m.parent_id ='0'  AND m.status=1 ANd m.code != ''
        AND m.code is NOT NULL AND m.code != '0' AND t.id=m.party_type_id " . $party_type_whr . " GROUP BY m.id ORDER BY m.id DESC");
        //log_message("error","Qry222:".$this->db->last_query());
        if ($get_parties->num_rows() > 0) {
            foreach ($get_parties->result() as $res) {
                if ($type == '1') {
                    $check = "<input type='radio' name='consigneelist' id='consigneelist_" . $res->master_id . "' class='consigneelist' onchange='selectparty(" . $res->master_id . ")' value='" . $res->master_id . "'>";
                } else {
                    $check = "<input type='radio' name='consigneelist' id='consigneelist_" . $res->master_id . "' class='consigneelist' onchange='selectparty(" . $res->master_id . ")' value='" . $res->master_id . "'>";
                }
                $master_ids[] = $res->master_id;
                $parties[]    = [
                    'check'        => $check,
                    'id'           => $res->code,
                    'name'         => $res->master_name,
                    'email'        => $res->master_email_id,
                    'mobile'       => $res->master_mobile,
                    'party_name'   => $res->party_name,
                    'company_code' => $res->company_code,
                    'branch_code'  => $res->branch_code,
                    'city'         => $res->city,
                    'country'      => $res->country,
                    'street'       => $res->street,
                ];
            }
        }
        $master_whr     = "";
        $additional_ids = $party_types = [];
        if (! empty($master_ids)) {
            $master_whr = "AND m.id NOT IN (" . implode(',', $master_ids) . ")  ";
        }
        $getmultipleparties = $this->db->query("SELECT m.id as master_id,m.party_types FROM tbl_party_master m WHERE m.code IS NOT NULL " . $master_whr . " " . $whr . " " . $usrwhr . " AND m.party_types IS NOT NULL");
        if ($getmultipleparties->num_rows() > 0) {
            foreach ($getmultipleparties->result() as $res) {
                if ($res->party_types != "" && $res->party_types != '0') {
                    $party_types = explode(',', $res->party_types);
                    if (end($party_types) == "") {
                        array_pop($party_types);
                    }
                    if (is_array($party_types)) {
                        if (! empty($party_types)) {
                            $chkshipper = $this->db->query("SELECT id FROM tbl_party_types WHERE id IN (" . implode(',', $party_types) . ") AND name LIKE '" . $party_type . "'");
                            if ($chkshipper != null && $chkshipper->num_rows() > 0) {
                                $additional_ids[] = $res->master_id;
                            }
                        }
                    }
                }
            }
        }

        if (! empty($additional_ids)) {
            $get_addids = $this->db->query("SELECT m.id as master_id,m.name as master_name,m.email as master_email_id,m.mobile as master_mobile,m.code,m.company_code,m.branch_code,m.location_id as city,m.country,m.street FROM tbl_party_master m WHERE m.id IN (" . implode(',', $additional_ids) . ") AND m.company_code != '' AND m.company_code IS NOT NULL AND m.company_code LIKE '" . $chkcompanycode . "' AND m.branch_code != '' AND m.branch_code IS NOT NULL  " . $usrwhr . " AND m.parent_id ='0'  AND m.status=1 ANd m.code != '' AND m.code is NOT NULL AND m.code != '0' GROUP BY m.id ORDER BY m.id DESC");
            if ($get_addids->num_rows() > 0) {
                foreach ($get_addids->result() as $res) {
                    if ($type == '1') {
                        $check = "<input type='radio' name='consigneelist' id='consigneelist_" . $res->master_id . "' class='consigneelist' onchange='selectparty(" . $res->master_id . ")' value='" . $res->master_id . "'>";
                    } else {
                        $check = "<input type='radio' name='consigneelist' id='consigneelist_" . $res->master_id . "' class='consigneelist' onchange='selectparty(" . $res->master_id . ")' value='" . $res->master_id . "'>";
                    }
                    $master_ids[] = $res->master_id;
                    $parties[]    = [
                        'check'        => $check,
                        'id'           => $res->code,
                        'name'         => $res->master_name,
                        'email'        => $res->master_email_id,
                        'mobile'       => $res->master_mobile,
                        'party_name'   => $party_type,
                        'company_code' => $res->company_code,
                        'branch_code'  => $res->branch_code,
                        'party_name'   => $party_type,
                        'city'         => $res->city,
                        'country'      => $res->country,
                        'street'       => $res->street,
                    ];
                }
            }
        }

        echo json_encode($parties);

    }

    public function getshipperdetailslistbyID() {
        $parties      = array();
        $code         = $this->input->post( 'id' );
        $company_code = $this->session->userdata( "company_code" );
        $user_id      = $this->session->userdata( 'user_id' );

        $permission = checkuserpermissions();

        if(in_array("businesspartners", $permission)){
            $whr = " AND c.company_code = '" . $company_code . "' ";
        } else {
            $whr = " AND c.user_id = '" . $user_id . "' ";
        }

        $sql = "SELECT c.id,c.name,c.phone,c.address,c.street,c.location as city,c.state,c.pincode,c.code,c.country,c.email_id,c.fax,c.company_code,c.branch_code
                FROM tb_customers c
                WHERE c.code LIKE ? " . $whr . "
                GROUP BY c.id
                ORDER BY c.id DESC";

        $chkqry = $this->db->query($sql, ['%' . $code . '%']);

        if ( $chkqry->num_rows() > 0 ) {
            foreach ( $chkqry->result() as $res ) {
                $parties[] = [
                    'check'        => "<input class='shipperlist' type='radio' name='selectshipper' id='shipperlist_" . $res->id . "' value='" . $res->code . "' onchange=selectshipper(" . $res->id . ")>",
                    'id'           => $res->id,
                    'party_id'     => $res->code,
                    'name'         => $res->name,
                    'phone'        => $res->phone,
                    'email'        => $res->email_id,
                    'company_code' => $res->company_code,
                    'branch_code'  => $res->branch_code,
                    'city'         => $res->city,
                    'country'      => $res->country,
                    'street'       => $res->street
                ];
            }
        }

        echo json_encode( $parties );
    }

    public function getshipperListID()
    {
        $parties      = [];
        $user_id      = $this->session->userdata('user_id');
        $company_code = $this->session->userdata('company_code');
        $permission   = checkuserpermissions();
        $company_code2  = isset($_POST['company_code']) ? $_POST['company_code'] : "";
        $branch_code  = isset($_POST['branch_code']) ? $_POST['branch_code'] : "";
        if (in_array("businesspartners", $permission)) {
            if($company_code2 != ""){
                 $whr = " AND c.company_code LIKE '" . $company_code2 . "' "; 
                 if($branch_code != ""){
                 $whr = " AND c.branch_code LIKE '" . $branch_code . "' "; 
               }
            }else{
               $whr = " AND c.company_code LIKE '" . $company_code . "' ";
            }
        } else {
            $whr = " AND c.user_id ='" . $user_id . "' ";
        }
        $sql = "SELECT c.id,c.name,c.phone,c.code,c.country,c.street,c.location as city,c.email_id,c.company_code,c.branch_code
                FROM tb_customers c
                WHERE  c.status ='1' AND  c.company_code != '' AND c.company_code IS NOT NULL " . $whr . "
                GROUP BY c.id
                ORDER BY c.createdon DESC";
        $chkqry = $this->db->query($sql);
        if ($chkqry->num_rows() > 0) {
            foreach ($chkqry->result() as $res) {
                $parties[] = [
                    'check'        => "<input class='shipperlist' type='radio' name='selectshipper' id='shipperlist_" . $res->id . "' value='" . $res->id . "' onchange=selectshipper(" . $res->id . ")>",
                    'id'           => $res->id,
                    'party_id'     => $res->code,
                    'name'         => $res->name,
                    'phone'        => $res->phone,
                    'email'        => wordwrap($res->email_id, 25, "<br />\n"),
                    'company_code' => $res->company_code,
                    'branch_code'  => $res->branch_code,
                    'city'         => $res->city,
                    'country'      => $res->country,
                    'street'       => $res->street,
                ];
            }
        }
        echo json_encode($parties);
    }

    public function getConsigneeDetailsListbyID()
    {
        $parties = [];
        $code = $this->input->post('id');
        $company_code = $this->session->userdata('company_code');
        $user_id = $this->session->userdata('user_id');
        $permission = checkuserpermissions();

        $partyWhereData = [];
        $partyWhereData["pm.status"] = 1;
        if (in_array("businesspartners", $permission)) {
            $partyWhereData["pm.company_code"] = $company_code;
        } else {
            $partyWhereData["pm.user_id"] = $user_id;
        }
        if($code != ""){
            $partyWhereData["pm.id"] = $code;
        }
        $getSelectedConsigneeDetails = $this->Order->getSelectedConsigneeDetails($partyWhereData);
        if (!empty($getSelectedConsigneeDetails)) {
            $parties[] = [
                'id' => $getSelectedConsigneeDetails['id'],
                'name' => $getSelectedConsigneeDetails['name'],
                'phone' => $getSelectedConsigneeDetails['mobile'],
                'street' => $getSelectedConsigneeDetails['street'],
                'city' => $getSelectedConsigneeDetails['city'],
                'pincode' => $getSelectedConsigneeDetails['pincode'],
                'code' => $getSelectedConsigneeDetails['code'],
                'country' => $getSelectedConsigneeDetails['country'],
                'email_id' => $getSelectedConsigneeDetails['email'],
                'fax' => $getSelectedConsigneeDetails['fax'],
                'state' => $getSelectedConsigneeDetails['state'],
                'address' =>$getSelectedConsigneeDetails['address'],
                'party_type_id' => $getSelectedConsigneeDetails['party_type_id'],
                'delivery_instructions' =>$getSelectedConsigneeDetails['delivery_instructions'],
                'pickup_instructions' => $getSelectedConsigneeDetails['pickup_instructions'],
                'role_name' => $getSelectedConsigneeDetails['partytype']
            ];
            echo json_encode($parties);
        }
    }

    public function getpartydetailsListbyID() {
        $parties      = array();
        $code         = $this->input->post( 'id' );
        $type         = isset( $_POST['type'] ) ? $_POST['type'] : "";
        $user_id      = $this->session->userdata( 'user_id' );
        $company_code = $branch_code = $whr = "";
        $company_code = $this->session->userdata( 'company_code' );
        $branch_code  = $this->session->userdata( 'branch_code' );
        $whr          = "";
        if ( $company_code != "" ) {
            $whr .= " AND m.company_code LIKE '" . $company_code . "'";
        }
        if ( $branch_code != "" ) {
            $whr .= " AND m.branch_code LIKE '" . $branch_code . "'";
        }
        $custid = "0";
        $whr1   = "";
        if ( $company_code != 'NZKN' ) {
            if ( $this->session->userdata( 'cust_id' ) !== FALSE ) {
                $custid = $this->session->userdata( 'cust_id' );
            }
            $subcusts = array();
            if ( $custid != 0 ) {
                if ( $this->session->userdata( 'sub_cust' ) !== FALSE ) {
                    $subcusts = $this->session->userdata( 'sub_cust' );
                    if ( count( $subcusts ) > 0 ) {
                        array_push( $subcusts, $custid );
                    } else {
                        $subcusts = $custid;
                    }
                } else {
                    $subcusts = $custid;
                }
            }
            $customer_code = array();
            if ( ! empty( $subcusts ) ) {
                $select          = "code";
                $table           = "tb_customers";
                $customerdetails = $this->Order->getcustomercodebyids( $select, $table, $subcusts );
                if ( ! empty( $customerdetails ) ) {
                    foreach ( $customerdetails as $cust ) {
                        $customer_code[] = $cust['code'];
                    }
                }
            }
            if ( ! empty( $customer_code ) ) {
                $whr1 = "AND m.customer_code IN ('" . implode( "','", $customer_code ) . "') ";
            }
        }
        $chkqry = $this->db->query( "SELECT m.id,m.name,m.email,m.street,m.location_id as city,m.state,m.mobile,m.address,m.country,m.pincode,m.country,m.code,m.company_code,m.branch_code,m.location_id as city,m.country,m.street,m.fax,t.id as partytype_id,t.name as role FROM tbl_party_master m,tbl_party_types t WHERE m.code LIKE '%" . $code . "%' " . $whr . " AND m.code Is NOT NULL AND m.code != '0' AND m.code != '' " . $whr1 . " AND t.id=m.party_type_id AND m.company_code != '' AND m.company_code IS NOT NULL AND m.branch_code != '' AND m.branch_code IS NOT NULL GROUP BY m.id ORDER BY m.id DESC" );

        if ( $chkqry->num_rows() > 0 ) {
            foreach ( $chkqry->result() as $res ) {
                if ( $type == 'inv' ) {
                    $check = "<input type='radio' name='partylist' id='partylist_" . $res->id . "' class='partylist' onchange='selectparty(" . $res->id . ")' value='" . $res->id . "'>";
                } else {
                    $check = "<input type='radio' name='consigneelist' id='consigneelist_" . $res->id . "' class='consigneelist' onchange='selectparty(" . $res->id . ")' value='" . $res->id . "'>";
                }
                $parties[] = array( 'check' => $check, 'id' => $res->code, 'name' => $res->name, 'email' => $res->email, 'mobile' => $res->mobile, 'party_name' => $res->role, 'company_code' => $res->company_code, 'branch_code' => $res->branch_code, 'city' => $res->city, 'country' => $res->country, 'street' => $res->street );
            }

        }
        echo json_encode( $parties );
    }

    public function getchargedesc( $id ) {
        $data['desc'] = "";
        if ( $id != "" ) {
            $getdesc = $this->db->query( "SELECT description FROM tb_charge_codes WHERE id=$id AND status=1" );
            if ( $getdesc->num_rows() > 0 ) {
                $data['desc'] = $getdesc->row()->description;
            }
        }
        echo json_encode( $data );
    }

    /* code for trip management */
    public function gettripcarinfo( $id ) {
        $result = array();
        if ( $id != "" ) {
            $vendor_list = $this->db->select( "code" )->get_where( "tb_vendors", array( 'id' => $id ) );
            if ( $vendor_list->num_rows() > 0 ) {
                $result['carrier_name'] = $vendor_list->row()->code;
            }
            $drivers = '<select class="add_company Txtfld tripcar_id form-control" name="vehicle_id" id="tdri_name" onchange="getdrid()"
        form="tripcreation" style="margin-top:4px;">
        <option value="">--Select--</option>';
            if ( $this->session->userdata( 'business_type' ) == "Carrier" ) {
                $drivers_list = $this->db->select( "id,name" )->get_where( "tb_truck_drivers", array( 'vendor_id' => $id, 'status' => 'Active' ) );
            } else {
                $drivers_list = $this->db->select( "id,name" )->get_where( "tb_truck_drivers", array( 'vendor_id' => $id, 'status' => 'Active' ) );
                if ( $drivers_list->num_rows() == 0 ) {
                    $user_id      = $this->session->userdata( 'user_id' );
                    $drivers_list = $this->db->select( "id,name" )->get_where( "tb_truck_drivers", array( 'user_id' => $user_id, 'status' => 'Active' ) );
                }
            }
            if ( $drivers_list->num_rows() > 0 ) {
                foreach ( $drivers_list->result() as $row ) {
                    $drivers .= '<option value="' . $row->id . '">' . $row->name . '</option>';
                }
            }
            $drivers           .= '</select>';
            $result['drivers'] = $drivers;
        }
        echo json_encode( $result );
    }

    public function gettripvelinfo() {
        $result    = array();
        $post      = $this->input->post();
        $id        = $post['vtype'];
        $carrierid = $post['carrierid'];
        $res       = '';
        $vtypename = $this->db->select( "description" )->get_where( "tb_trucktypes",
            array( 'id' => $id ) );
        if ( $vtypename->num_rows() > 0 ) {
            $res = $vtypename->row()->description;
        }
        $result['typename'] = $res;
        $vehres             = '<select name="tvehnum" id="tvehnum" onchange="myfun()"
    form="tripcreation" class="Txtfld tripcar_id form-control" style="margin-top:4px;"><option value="">--Select--</option>';


        $vehile_list        = $this->Order->getvehicleinfo($id, $carrierid);
        
        if ( $vehile_list->num_rows() > 0 ) {
            foreach ( $vehile_list->result() as $vehi ) {
                $vehres .= '<option value="' . $vehi->id . '">' . $vehi->truck_number . '</option>';
            }
        }
        $vehres               .= '</select>';
        $result['vehiclenum'] = $vehres;
        echo json_encode( $result );
    }

    public function getvelinfo( $id ) {
        $result            = array();
        $result['transit'] = 0;
        if ( $id != "" ) {
            $vendor_list = $this->db->select( "truck_number" )->get_where( "tb_trucks_data", array( 'id' => $id ) );
            if ( $vendor_list->num_rows() > 0 ) {
                $result['vehid'] = $vendor_list->row()->truck_number;
            }
            $trip_transit = $this->db->select( "id" )->get_where( "tb_trips", array( 'vehicle_id' => $id, 'status' => 1 ) );
            if ( $trip_transit->num_rows() > 0 ) {
                $result['vehid']   = '';
                $result['transit'] = 1;
            }
        }
        echo json_encode( $result );

    }

    public function getdriverid( $id ) {
        $res = '';
        if ( $id != "" ) {
            $driver_list = $this->db->select( "contact_num" )->get_where( "tb_truck_drivers", array( 'id' => $id ), 1, 0 );
            if ( $driver_list->num_rows() > 0 ) {
                $res = $driver_list->row()->contact_num;
            }
        }
        echo $res;
    }

    /**
     *  This method is used to create trip for multiple orders
     *  @param  array input
     * 	return : response int (1 => Trip Created,0 => Trip Failed)
     */

    public function tripcreatemultiorder($ordInput): int
    {

        $response = 0;
        $sessionCompanyCode = $ordInput['company_code'];
        $vendorId = $ordInput['carrierid'];
        $this->db->select(
            'o.*, TRUNCATE(sum(
                             Case When cd.weight_unit IN ("G", "Gms", "gms", "grm") Then ocd.weight / 1000
                             Else (Case When cd.weight_unit IN ("Kg", "kg") Then ocd.weight
                             Else (Case  When cd.weight_unit IN ("Tons", "tons") Then ocd.weight * 1000
                             Else 0 End) End) End), 3) as total_weight'
        );
        $this->db->from('tb_orders AS o');
        $this->db->join('tb_order_cargodetails AS ocd', 'ocd.order_id = o.id', 'LEFT');
        $this->db->join('tb_cargo_details AS cd', 'cd.id = ocd.cargo_id', 'LEFT');
        $this->db->where_in('o.id', explode(',', $ordInput['ordid']));
        $this->db->group_by('o.id');
        $orders = $this->db->get()->result_array();
        $response = $this->tripcreatefromorders->createMultiTripFromOrdersPage($orders, $ordInput);
        if (!empty($orders)) {
            foreach ($orders as $eachOrder) {
                $this->ordernotify('trip_create', $eachOrder['id']);
            }
        }
        return $response;

    }

    public function triporderintoshipment() {
        $response  = 0;
        $userid    = $this->session->userdata( 'user_id' );
        $curtz     = $this->session->userdata( "usr_tzone" )['timezone'];
        $logdate   = date( 'Y-m-d H:i:s' );
        $getactual = getdatetimebytimezone( DFLT_TZ, $logdate, $curtz );
        $curdt     = $getactual['datetime'];
        $input     = $this->input->post( NULL, TRUE );
        $error_msg             = "";
        $edi_res               = array();
        $input['user_id']      = $userid;
        $input['curtz']        = $curtz;
        $input['curdt']        = $curdt;
        $input['company_code'] = $this->session->userdata( 'company_code' );
        $input['branch_code']  = $this->session->userdata( 'branch_code' );
        $ordeschk              = explode( ",", $input['ordid'] );
        if ( count( $ordeschk ) > 1 ) {
            if ( $input['trip_type'] == 'multi' ) {
                $response = $this->tripcreatemultiorder( $input );
            } else {
                $getref = $this->db->query( "SELECT GROUP_CONCAT(order_id) as orders FROM tb_order_references WHERE order_id IN(" . $input['ordid'] . ") AND reference_id='ROT' AND status=1 GROUP BY ref_value" );
                if ( $getref->num_rows() > 0 ) {
                    foreach ( $getref->result_array() as $reford ) {
                        $input['ordid'] = $reford['orders'];
                        $response       = $this->tripcreatemultiorder( $input );
                    }
                } else {
                    $response = $this->eachordercreatetrip( $input );
                }
            }
        } else {
            $response = $this->eachordercreatetrip( $input );
        }
        if ($this->session->userdata('company_code') != "CNKN") {
            $this->ratemanagement->addrecodfortripinsertion($input);
        }
        if ( $response == 1 ) {
            $this->session->set_flashdata( 'success_msg', 'Trip Created Successfully.' );
        } else if ( $response == 2 ) {
            $this->session->set_flashdata( 'error_msg', 'Your selected orders are not in same root.(example: Ref. ID (ROT))' );
        } else {
            $this->session->set_flashdata( 'error_msg', 'Oops..Something Went Wrong.' );
        }
        if ( ! empty( $error_msg ) ) {
            $this->session->set_flashdata( 'edierror_msg', $error_msg );
        }
        redirect( 'orders' );
    }

    /**
     *  This method is used to create trip for single order
     *  @param  array ordInput
     * 	return : response int (1 => Trip Created,0 => Trip Failed)
     */

    public function eachordercreatetrip($ordInput): int
    {
        $response = 0;
        $ordesChk = explode(",", $ordInput['ordid']);
        foreach ($ordesChk as $chkOrd) {
            $this->db->select(
                'o.*, TRUNCATE(sum(
                             Case When cd.weight_unit IN ("G", "Gms", "gms", "grm") Then ocd.weight / 1000
                             Else (Case When cd.weight_unit IN ("Kg", "kg") Then ocd.weight
                             Else (Case  When cd.weight_unit IN ("Tons", "tons") Then ocd.weight * 1000
                             Else 0 End) End) End), 3) as total_weight'
            );
            $this->db->from('tb_orders AS o');
            $this->db->join('tb_order_cargodetails AS ocd', 'ocd.order_id = o.id', 'LEFT');
            $this->db->join('tb_cargo_details AS cd', 'cd.id = ocd.cargo_id', 'LEFT');
            $this->db->where('o.id', $chkOrd);
            $order = $this->db->get()->row_array();
            if (!empty($order)) {
                $order['currentTime'] = $ordInput['curdt'];
                if ($order['shift_id'] > 0) {
                    $this->session->set_flashdata('error_msg', 'Trip already created for this order. Please check details.');
                    redirect('orders');
                }
                $response = $this->tripcreatefromorders->createTripFromOrdersPage($order, $ordInput);
                $orderDetails = $this->common->gettblrowdata(['id' => $order['id']], "id,order_id,user_id,customer_id,vendor_id,company_code,shift_id", "tb_orders", 0, 0);
                if ($orderDetails['shift_id'] > 0) {
                    $this->ordernotify('trip_create', $orderDetails['id']);
                    if (checkAccessConditions('CHECK_DELHIVERY_LIMITED_CARRIER', $orderDetails['vendor_id'])) {
                        $this->load->library("DelhiveryB2BEDIServices");
                        $this->delhiveryb2bediservices->triggerDelhiveryAPI($orderDetails['shift_id']);
                    }
                    if ($orderDetails['user_id'] == '244') {
                        $this->load->library("uniqloediservices");
                        if ($orderDetails['vendor_id'] == "310") {
                            $sendTrip = $this->uniqloediservices->getdelverywaybillnumber($orderDetails['shift_id']);
                        } elseif ($orderDetails['vendor_id'] == "311") {
                            $sendTrip1 = $this->uniqloediservices->forwardmanifestation($orderDetails['shift_id']);
                        } elseif ($orderDetails['vendor_id'] == "312") {
                            $sendTrip2 = $this->uniqloediservices->xbordercreatemanifestation($orderDetails['shift_id']);
                        } elseif (checkAccessConditions('CHECK_BLOWHORN_CARRIER', $orderDetails['vendor_id'])) {
                            $sendTrip4 = $this->carriercommonedilib->shipmentdata($orderDetails['shift_id']);
                        } else {
                            $sendTrip3 = $this->uniqloediservices->senddocketnumber($orderDetails['id']);
                        }
                    }
                    if ($orderDetails['vendor_id'] != "") {
                        if ($orderDetails['company_code'] == "INKN" && $orderDetails['vendor_id'] == 194) {
                            $this->GetOrderIntoapi($orderDetails['order_id']);
                        }
                    }
                }
            }
        }
        $this->load->helper('pushnotification_helper');
        mobilePushNotification($ordInput);
        return $response;
    }
    public function printLabel($label)
    {
        ini_set('max_execution_time', '300');
        $pipaddr = '10.91.191.50';
        $pport = 9100;
        try {
            $labelpath = "./assets/swiftlog/docketlabel/".$label;
            $newimgpath = './assets/swiftlog/eTNLabel.png';
            $im = new Imagick();
            $im->setResolution(360, 360);
            $im->readImage($labelpath);
            $im->setImageFormat('png');
            $im->setImageCompression(Imagick::COMPRESSION_JPEG);
            $im->setImageCompressionQuality(100);
            $im->writeImage($newimgpath);
            $im->clear();
            $im->destroy();
            $decoder = GdDecoder::fromPath($newimgpath);
            $image = new Image($decoder);
            $zpl = new Builder();
            $zpl->fo(10, 10)
                ->gf($image)
                ->fs();
            $client = new Client($pipaddr, $pport);
            $client->send($zpl);
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    /* code for trip management */
    public function orderlabel( int $order_id, int $checkCustomer = 0 ): void {
        if($this->session->userdata('branch_code') == "INCL" && $order_id != ""){
            $ordinfo = array("order_id"=>$order_id);
            $refs = $this->common->gettblrowdata(array("order_id"=>$order_id,"reference_id"=>'AWB',"ref_value <>"=>'',"status"=>1),"id","tb_order_references",0,0);
            if(count($refs)>0){
                $this->load->library("uniqloediservices");
                $lbl = $this->uniqloediservices->generatedocketlabel($ordinfo);
                if($lbl != ""){
                    $chkprint = $this->printLabel($lbl);
                }
            }
        }else{
            $data = $order_types = array();
            require 'vendor/autoload.php';
            $reference            = $shipmentnumber = $communication_reference = $date = "";
            $drop_details['name'] = $drop_details['street'] = $drop_details['country'] = $drop_details['pincode'] = $shipper_details['name'] = $shipper_details['street'] = $shipper_details['country'] = $shipper_details['pincode'] = $shipper_details['city'] = $data['count'] = $data['weight'] = $data['qty'] = $data['cargoHandlingUnit'] = $data['qr_code'] = "";
            $cargos               = $drop_details = $shipper_details = $order_type = array();
            if ( $order_id != "" ) {
                if ($this->session->userdata('company_code') == 'NZKN' || $this->session->userdata( 'cust_id' ) == TRUE) {
                    $upd_orderstatus = $this->db->where( array( 'id' => $order_id ) )->update( "tb_orders", array( 'order_status' => 'READY' ) );

                    $autoRoute = $this->verifyRouting($order_id);
                    if (!empty($autoRoute)) {
                        $this->inserttripdata([$autoRoute]);
                    }
                }
                $chkorder = $this->Order->getordertoedit( $order_id );
                if ( $chkorder->num_rows() > 0 ) {
                    $date      = $chkorder->row()->pickup_datetime;
                    $reference = $chkorder->row()->shipment_id;
                    if ( $reference != "" && $reference != 0 ) {

                        $getshipment_number = $this->db->select( "shipid" )->get_where( "tb_shipments", array( 'id' => $reference ) );
                        if ( $getshipment_number->num_rows() > 0 ) {
                            $reference = $getshipment_number->row()->shipid;
                        }
                    }
                    $shipmentnumber          = $chkorder->row()->order_id;
                    $communication_reference = $chkorder->row()->purchase_order;

                    $drop_id     = $chkorder->row()->drop_custid;
                    $drop_row_id = 0;
                    $chekparty   = $this->db->query( "SELECT p.id,p.party_type_id, p.name, p.mobile, p.email,p.code,p.fax,p.house_number,o.party_type FROM tbl_party_master p INNER JOIN tb_order_parties o ON p.id=o.party_id AND o.status=1  WHERE p.status=1 AND o.order_id='$order_id' GROUP BY o.party_type" );
                    if ( $chekparty->num_rows() > 0 ) {
                        foreach ( $chekparty->result() as $rr ) {
                            $ptype   = $rr->party_type;
                            $chktype = $this->db->select( "name" )->get_where( "tbl_party_types", array( "id" => $ptype ), 1, 0 );
                            if ( $chktype->num_rows() > 0 ) {
                                if ( $chktype->row()->name == "Consignee" ) {
                                    $drop_details = array( 'id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code,'houseNumber'=> $rr->house_number);
                                } else if ( $chktype->row()->name == "Shipper" ) {
                                    $shipper_details = array( 'id' => $rr->id, 'name' => $rr->name, 'phone' => $rr->mobile, 'email' => $rr->email, 'fax' => $rr->fax, 'party_id' => $rr->code,'houseNumber'=> $rr->house_number);
                                }
                            }
                        }
                    }

                    $ordertype = $chkorder->row()->order_type;
                    if($ordertype!="" || $ordertype!=null){
                        $chktype = $this->db->select( "type_name" )->get_where( "tb_order_types", array( "id" => $ordertype ), 1, 0 );
                        if ( $chktype->num_rows() > 0 ) {
                            $order_type['name'] =  $chktype->row()->type_name;
                        }
                    }
                    $data['order_type']            = $order_type;

                    $shipper_details['name']    = $chkorder->row()->pickup;
                    $shipper_details['street']  = $chkorder->row()->pickup_address1;
                    $shipper_details['state']   = $chkorder->row()->pickup_address2;
                    $shipper_details['city']    = $chkorder->row()->pickup_city;
                    $shipper_details['country'] = $chkorder->row()->pickup_country;
                    $shipper_details['pincode'] = $chkorder->row()->pickup_pincode;

                    $drop_details['name']    = $chkorder->row()->delivery;
                    $drop_details['street']  = $chkorder->row()->delivery_address1;
                    $drop_details['state']   = $chkorder->row()->delivery_address2;
                    $drop_details['city']    = $chkorder->row()->delivery_city;
                    $drop_details['country'] = $chkorder->row()->delivery_country;
                    $drop_details['pincode'] = $chkorder->row()->delivery_pincode;

                    $qry = $this->db->query( "SELECT c.*,o.handling_unit as cargoHU FROM tb_cargo_details c,tb_order_cargodetails o WHERE o.order_id ='" . $order_id . "' AND o.cargo_id=c.id AND o.status='1' GROUP BY c.id ORDER BY c.id DESC" );
                    if ( $qry->num_rows() > 0 ) {
                        //log_message("error","qryRes:".json_encode($qry->result()));
                        foreach ( $qry->result() as $res ) {
                            $units = $res->weight_unit;
                            if ( $units == "" ) {
                                $units = "Kg";
                            }
                            $qty = $res->quantity;
                            $cargoHandlingUnit = $res->cargoHU;
                            $cargoType = $res->cargo_type;
                            
                            $wt  = @round( ( $res->weight / $qty ), 2 );
                            $vol  = @round( ( $res->volume / $qty ), 2 );
                            for ( $i = 1; $i <= $qty; $i ++ ) {
                                $cargos[] = array( 'id' => $res->id, 'qty' => $qty, 'cargoHandlingUnit' => $cargoHandlingUnit, 'cargoType' => $cargoType, 'weight' => $wt . " " . $units, 'volume'=>$vol . " M3" );
                            }
                        }
                    }
                }
                $data['drop_details']            = $drop_details;
                $data['shipper_details']         = $shipper_details;
                $data['reference']               = $reference;
                $data['shipmentnumber']          = $shipmentnumber;
                $data['communication_reference'] = $communication_reference;
                if ( $date != "" ) {
                    $timestamp    = strtotime( $date );
                    $data['date'] = date( 'd M Y', $timestamp );
                } else {
                    $data['date'] = $date;
                }
                $data['cargos'] = $cargos;
                $ordernumber    = $chkorder->row()->order_id;
                $data['generator'] = new Picqer\Barcode\BarcodeGeneratorPNG();

                $orderRefs = $this->common->gettblrowdata(["order_id" => $order_id, "reference_id" => 'ORD_DLVINST', "status" => 1], "ref_value", "tb_order_references", 0, 0);
                $data['driver_delivery_ins'] = $orderRefs['ref_value'] ?? '';

                if ( $this->session->userdata( 'company_code' ) == "NZPG" ) {
                    $customer_details=array('id'=>'','name'=>'');
                    $data['trucknumber']='';
                    $data['destination_branch']='';
                    if($order_id!=''){
                        $sql="select c.id,name,o.shift_id,o.destination_branch from tb_orders o
					inner join tb_customers c on c.id=o.customer_id
					where o.id='$order_id';
					";
                        $sql=$this->db->query($sql);
                        if ( $sql->num_rows() > 0 ) {
                            $customer_details=array('id'=>$sql->row()->id,'name'=>$sql->row()->name);
                            $data['customer_details']=$customer_details;
                            $shiftId=$sql->row()->shift_id;
                            $data['destination_branch']=$sql->row()->destination_branch;
                        }
                    }

                    $mpdf           = new \Mpdf\Mpdf( [
                        'mode'          => 'utf-8',
                        'tempDir' 		=> FCPATH .'assets/tmp',
                        'format'  => [ 100, 160 ],
                        'margin_left'   => 0,
                        'margin_right'  => 0,
                        'margin_top'    => 0,
                        'margin_bottom' => 0,
                        'margin_header' => 0,
                        'margin_footer' => 0,
                    ] );

                }else{
                    $mpdf           = new \Mpdf\Mpdf( [
                        'mode'          => 'utf-8',
                        'tempDir' 		=> FCPATH .'assets/tmp',
                        'format'        => [ 100, 110 ],
                        'margin_left'   => 0,
                        'margin_right'  => 0,
                        'margin_top'    => 0,
                        'margin_bottom' => 0,
                        'margin_header' => 0,
                        'margin_footer' => 0,
                    ] );
                }

                $vendor = $this->common->gettblrowdata([
                    'id' => $chkorder->row()->vendor_id
                ], 'name', 'tb_vendors', 0, 0);
                $data['vendorName'] = $vendor['name'] ?? '';
                /*$data['sendRef'] = getorderreftypeinfo('DQ', $order_id);
                $data['receiverRef'] = getorderreftypeinfo('PO', $order_id);*/
                $data['deliveryIns'] = getorderreftypeinfo('ORD_DLVINST', $order_id);
                $data['pickupIns'] = getorderreftypeinfo('ORD_PIKINST', $order_id);
                $html           = "";
                $i              = 1;
                $data['count']  = count( $cargos );
                $data['sendRef']=getorderreftypeinfo('DQ',$order_id);
                $data['receiverRef']=getorderreftypeinfo('PO',$order_id);
                //log_message("error","receiverRef:".$data['receiverRef']);
                $data['receiverDORef']=getorderreftypeinfo('DO',$order_id);
                //log_message("error","receiverDORef:".$data['receiverDORef']);
                $data['tknRef']=getorderreftypeinfo('TKN',$order_id);
                //log_message("error","tknRef:".$data['tknRef']);
                $data['checkCustomer'] = $checkCustomer;
                $checkCustomer = 1;
                $this->load->library('barcode');
               // log_message("error","Cargos:".json_encode($cargos));
                foreach ( $cargos as $cargo ) {
                    $data['weight'] = $cargo['weight'];
                    $data['cargoType'] = $cargo['cargoType'];
                    $data['volume'] = $cargo['volume'];
                    $data['no']     = $i;
                    $data['qty'] = $cargo['qty'];
                    $data['cargoHandlingUnit'] = $cargo['cargoHandlingUnit'];
                    
                   
                    //log_message("error","cargoHandlingUnit:". $data['cargoHandlingUnit']);
                    //log_message("error","qty:". $data['qty']);
                    $data['qr_code'] = $this->barcode->generate(json_encode([
                        "cargo_id" => $data['cargoHandlingUnit'],
                        "quantity" => 1//$data['qty']
                    ]));
                    //log_message("error","Qrcode:". $data['qr_code']);
                    //log_message("error","Qrcode:". $data['qr_code']);
                    
                    if ( $this->session->userdata( 'company_code' ) == "NZPG" ) {
                        $html.= $this->load->view( 'orders/orderlabel_pact', $data, TRUE );
                    }else{
                        $html.= $this->load->view( 'orders/orderlabel', $data, TRUE );
                    }
                    $i ++;
                }
                $data1['labelcontent'] = $html;
                $output = $this->load->view( 'orders/order_label', $data1, TRUE );
                $mpdf->WriteHTML( $output );
                $mpdf->Output( $ordernumber . "_" . date( 'YmdHis' ) . ".pdf", 'D' );
            }
        }
    }

    public function getorderdetails( $order_id ) {
        if ( $order_id != "" ) {
            $cdate        = date( 'Y-m-d H:i:s' );
            $chkorder     = $this->Order->getordertoedit( $order_id );
            $tripsts      = "Pending";
            $order_status = "PENDING";
            $shipperdetail = $vendordetails = $consignedetail = $consignordetail = $pfdetails = $customerdetails = array();
            if ( $chkorder->num_rows() > 0 ) {
                $status   = $chkorder->row()->status;
                $trip_sts = $chkorder->row()->trip_sts;
                $trip_id  = $chkorder->row()->trip_id;
                if ( $trip_id != 0 && $trip_sts == 0 ) {
                    $order_status = 'ACTIVE';
                    $tripsts      = 'ACTIVE';
                }
                if ( $trip_id != 0 && $trip_sts == 1 ) {
                    $order_status = 'ACTIVE';
                    $tripsts      = 'ACTIVE';
                }
                $curtz     = $this->session->userdata( "usr_tzone" )['timezone'];
                $createdon = $chkorder->row()->createdon;
                $updatedon = $chkorder->row()->updatedon;
                $curdt = $cdate;
                $upddt = $cdate;
                $parties   = array();
                $vendor_id = $chkorder->row()->vendor_id;
                if ( $vendor_id != 0 ) {
                    $getvendor = $this->db->query( "SELECT name,mobile,location,address,pincode,country,email,code FROM tb_vendors where id ='" . $vendor_id . "'" );
                    if ( $getvendor->num_rows() > 0 ) {
                        $vendordetails = array(
                            'name'     => $getvendor->row()->name,
                            'party_id' => $getvendor->row()->code,
                            'address'  => $getvendor->row()->address,
                            'pincode'  => $getvendor->row()->pincode,
                            'country'  => $getvendor->row()->country,
                            'street'   => "",
                            'city'     => $getvendor->row()->location,
                            'state'    => "",
                            'phone'    => $getvendor->row()->mobile,
                            'email'    => $getvendor->row()->email
                        );
                    }
                }
                $pickup_id        = $chkorder->row()->customer_id;
                $customerReferences = $this->common->getPartyReferences($pickup_id);
                $getpickupdetails = $this->db->query( "SELECT name,phone,state,street,location,pincode, address, email_id, code,country FROM tb_customers WHERE id='" . $pickup_id . "' AND status=1 LIMIT 1" );
                if ( $getpickupdetails->num_rows() > 0 ) {
                    $customerdetails = array(
                        'name'     => $getpickupdetails->row()->name,
                        'party_id' => $getpickupdetails->row()->code,
                        'address'  => $getpickupdetails->row()->address,
                        'pincode'  => $getpickupdetails->row()->pincode,
                        'country'  => $getpickupdetails->row()->country,
                        'street'   => $getpickupdetails->row()->street,
                        'city'     => $getpickupdetails->row()->location,
                        'state'    => $getpickupdetails->row()->state,
                        'phone'    => $getpickupdetails->row()->phone,
                        'email'    => $getpickupdetails->row()->email_id,
                        'references' => $customerReferences
                    );
                }
                $consignee_mobile = $consignor_mobile = $shipper_mobile = $carrier_mobile = "";
                $chekparty        = $this->db->query( "SELECT p.id,p.party_type_id, p.name, p.mobile, p.email,p.code, p.location_id, p.address, p.country,p.state, p.street, p.pincode, o.party_type, a.party_master_id, a.location_id as plocation_id,a.street as pstreet,a.state as pstate,a.address as paddress,a.pincode as ppincode,a.country as pcountry,p.latitude,p.longitude FROM tbl_party_master p INNER JOIN tb_order_parties o ON p.id=o.party_id AND o.status=1 LEFT JOIN tbl_orderparty_address a ON o.party_id=a.party_master_id AND o.order_id=a.order_id AND a.status=1 WHERE p.status=1 AND o.order_id='$order_id' GROUP BY o.party_type" );if ( $chekparty->num_rows() > 0 ) {
                    foreach ( $chekparty->result() as $rr ) {
                        $pdetail = array();
                        $ptype   = $rr->party_type;
                        $ptypeid = $rr->id;
                        $getpartyinfo = $this->common->gettbldata(["partner_id" => $ptypeid], "*", "tb_party_reference", 0, 0);
                        $chktype = $this->db->select( "name" )->get_where( "tbl_party_types", array( "id" => $ptype ), 1, 0 );
                        if ( $chktype->num_rows() > 0 ) {
                            if ( $rr->party_master_id != "" ) {
                                $pdetail = array( 'name' => $rr->name, 'party_id' => $rr->code, 'address' => $rr->paddress, 'pincode' => $rr->ppincode, 'country' => $rr->pcountry, 'street' => $rr->pstreet, 'city' => $rr->plocation_id, 'state' => $rr->pstate, 'phone' => $rr->mobile, 'email' => $rr->email,'latitude' => $rr->latitude,'longitude' => $rr->longitude,'party_references' => $getpartyinfo );
                            } else {
                                $pdetail = array( 'name' => $rr->name, 'party_id' => $rr->code, 'address' => $rr->address, 'pincode' => $rr->pincode, 'country' => $rr->country, 'street' => $rr->street, 'city' => $rr->location_id, 'state' => $rr->state, 'phone' => $rr->mobile, 'email' => $rr->email,'latitude' => $rr->latitude,'longitude' => $rr->longitude,'party_references' => $getpartyinfo );
                            }


                            if ( $chktype->row()->name == "Consignee" ) {
                                $pdetail['type']  = "Consignee";
                                $consignee_mobile = $rr->mobile;
                                $consignee_id = $rr->code;
                                $delivery_state = $rr->state;
                                $delivery_email = $rr->email;
                            }

                            if ( $chktype->row()->name == "Consignor" ) {
                                $consignor_mobile = $rr->mobile;
                                $consigneer_id = $rr->code;
                                $delivery_states = $rr->state;

                            }

                            if ( $chktype->row()->name == "Shipper" ) {
                                $shipper_mobile  = $rr->mobile;
                                $shipper_id = $rr->code;
                                $pickup_state = $rr->state;
                                $pickup_email = $rr->email;
                            }
                            if ( $chktype->row()->name == "Carrier" ) {
                                $carrier_mobile  = $rr->mobile;
                            }

                            $pdetail['type']  = $chktype->row()->name;
                            $parties[] = $pdetail;
                        }
                    }
                }
                $code         = "";
                $areacodes    = array( "1", "2", "3", "10", "11", "12", "673", "653", "645", "644", "635", "629", "628", "627", "624", "6", "5", "4", "29", "28", "27", "26", "25", "24", "23", "22", "21", "20", "19", "18", "17", "16", "15", "14", "13", "675", "676", "677", "678", "7", "8", "9" );
                $zonecode     = $this->session->userdata( "usr_tzone" );
                $currency     = isset( $zonecode['currency'] ) ? $zonecode['currency'] : "SGD";
                $company_code = $this->session->userdata( "company_code" );
                $branch_code  = $this->session->userdata( "branch_code" );
                if ( isset( $zonecode['phone_code'] ) ) {
                    $code = $zonecode['phone_code'];
                } else {
                    if ( $company_code == "THKN" ) {
                        $code = "66";
                    }
                    if ( $company_code == "SGKN" ) {
                        $code = "65";
                    }
                    if ( $company_code == "INKN" ) {
                        $code = "91";
                    }
                }
                $cargos = [];
                $total_volume = $total_weight = 0;

                $weight_unit = "KG";
                        $volume_unit = "CBM";
                        $volume = 0;
                        $weight = 0;
                    $total_quantity = 0;
                $getcargos = $this->db->query("SELECT p.handling_unit,p.length,p.cargo_id,p.width,
                p.height,p.weight,p.volume,p.quantity,p.quantity_type,p.cargo_content,p.second_weight,
				p.second_volume,p.scanned_quantity,p.ldm,p.volumetric_weight,
                o.cargo_type,
                o.handling_unit,o.weight_unit,o.volume_unit,o.length_unit,o.width_unit,
                o.height_unit,o.goods_description,o.marks_numbers,o.item_id,o.secondweight_uom,o.secondvolume_uom,
                o.grounded,o.stackable,o.splittable,o.dg_goods,o.volweight_uom

                FROM tb_order_cargodetails p LEFT OUTER JOIN `tb_cargo_details` o ON o.id=p.cargo_id
                WHERE p.status=1 AND p.order_id=?", [$order_id]);
                if ( $getcargos->num_rows() > 0 ) {
                    foreach ( $getcargos->result() as $res ) {

                        $volume = $res->volume;
                        $weight = $res->weight;
                        if($volume == ""){ $volume = 1; }
                        if($weight == ""){ $weight = 1; }

                        $content = $res->cargo_content;
                        if($content == ""){ $content = "Dummy"; }

                        $inner_cargo_res = $this->common->gettbldata(["cargo_id"=> $res->cargo_id],
						"cargo_type,goods_description,quantity,length,length_unit,
						width,width_unit,height,height_unit,weight,weight_unit,volume,volume_unit",
						"tb_inner_cargo",0,0);

                        $total_volume += $volume;
                        if(strtoupper($res->weight_unit) == "TON" || strtoupper($res->weight_unit) == "TONS"){
                            $weight = $res->weight * 1000;
                        }
                        $total_weight += $weight;
                        $total_quantity += $res->quantity;

                        $cargos[] = [
                            'handling_unit'  =>$res->handling_unit,
                            'length'  =>$res->length,
                            'cargo_id'  =>$res->cargo_id,
                            'width'  =>$res->width,
                            'height'  =>$res->height,
                            'weight'  =>$res->weight,
                            'volume'  =>$res->volume,
                            'quantity'  =>$res->quantity,
                            'quantity_type'  =>$res->quantity_type,
                            'cargo_content'  =>$res->cargo_content,
                            'second_weight'  =>$res->second_weight,
                            'second_volume'  =>$res->second_volume,
                            'scanned_quantity'  =>$res->scanned_quantity,
                            'ldm'  =>$res->ldm,
                            'volumetric_weight'  =>$res->volumetric_weight,
                            'cargo_type'  =>$res->cargo_type,
                            'handling_unit'  =>$res->handling_unit,
                            'weight_unit'  =>$res->weight_unit,
                            'volume_unit'  =>$res->volume_unit,
                            'length_unit'  =>$res->length_unit,
                            'width_unit'  =>$res->width_unit,
                            'height_unit'  =>$res->height_unit,
                            'goods_description'  =>$res->goods_description,
                            'marks_numbers'  =>$res->marks_numbers,
                            'item_id'  =>$res->item_id,
                            'secondweight_uom'  =>$res->secondweight_uom,
                            'secondvolume_uom'  =>$res->secondvolume_uom,
                            'grounded'  =>$res->grounded,
                            'stackable'  =>$res->stackable,
                            'splittable'  =>$res->splittable,
                            'dg_goods'  =>$res->dg_goods,
                            'volweight_uom'  =>$res->volweight_uom,
                            'inner_cargo' => $inner_cargo_res

                        ];
                    }
                }
                if ( $chkorder->row()->company_code != "" ) {
                    $company_code = $chkorder->row()->company_code;
                }
                if ( $chkorder->row()->branch_code != "" ) {
                    $branch_code = $chkorder->row()->branch_code;
                }

                $order_type = $chkorder->row()->order_type;
                $service = $chkorder->row()->service;
                $getOrdertype = $this->db->query("SELECT type_name FROM tb_order_types WHERE status ='1' and id=?", [$order_type]);
                $orderType = $getOrdertype->row()->type_name;

                $getServicetype = $this->db->query("SELECT name FROM tb_service_master WHERE status ='1' and id=?", [$service]);
                $orderService = $getServicetype->row()->name;

                $cncontact     = $consignee_mobile;
                $cacontact     = $consignor_mobile;
                if ( $cacontact == "" ) {
                    $cacontact = $shipper_mobile;
                }
                $ValueAddondetail = [];
                $valueAddser = [];
                $getValueaddSer = $this->db->query("SELECT oc.quantity,im.vas_id,im.vas_name FROM tb_order_vas oc,tb_vas_master im WHERE oc.order_id = ? AND im.id = oc.vas_id", [$order_id]);
                if ($getValueaddSer->num_rows() > 0) {
                    foreach ($getValueaddSer->result() as $rese) {

                        $vas_name = $rese->vas_name;
                        $vas_id = $rese->vas_id;
                        $quantity = $rese->quantity;
                        $ValueAddondetail = ['quantity' => $quantity, 'vas_id' => $vas_id, 'vas_name' => $vas_name];
                        $valueAddser[] = $ValueAddondetail;
                    }
                }
                $getrefrnceid = $this->db->query("select reference_id,ref_value from tb_order_references where order_id =?", [$order_id]);
                if ($getrefrnceid->num_rows() > 0) {
                    foreach ($getrefrnceid->result() as $res) {
                        $refrences[] = ['reference_id' => $res->reference_id, 'ref_value' => $res->ref_value];
                    }
                }

                $curtz = $this->session->userdata("usr_tzone")['timezone'];
                $hrs = $this->session->userdata("usr_tzone")['hrs'];
                $sourceReferences = ($chkorder->row()->pickup_custid != "") ? $this->getPartyRefereces($chkorder->row()->pickup_custid) : [];
                $destinationReferences = ($chkorder->row()->drop_partyid != "") ? $this->getPartyRefereces($chkorder->row()->drop_partyid) : [];

                $delivery_term_id = $chkorder->row()->delivery_term;
                $delivery_term_name = "";
                if ( $delivery_term_id != "" ) {
                    //$getdelivery_term = $this->db->select( "term_id,name" )->get_where( "tb_delivery_terms", array( 'term_id' => $delivery_term_id ) );
                    $getdelivery_term = $this->db->select("term_id,name")->get_where("tb_delivery_terms",
                     ['term_id' => $delivery_term_id]);
                    if ( $getdelivery_term->num_rows() > 0 ) {
                        $delivery_term_name = $getdelivery_term->row()->name;
                    }
                }

                $LogicalSender = $chkorder->row()->logicalsender;
                $PhysicalReceiver =  $chkorder->row()->physicalreceiver;
                $LogicalReceiver =  $chkorder->row()->logicalreceiver;
                $PhysicalSender = $chkorder->row()->physicalsender;

                $logicalinfo=$this->common->gettblrowdata(array('branch_code'=>$branch_code),
                "logical_sender","tb_branch_master",0,0);
                if(count($logicalinfo)>0){
                    if($LogicalSender == "") {
                        $LogicalSender=$logicalinfo['logical_sender'];
                    }


                }

                $data = [
                    'SenderTransmissionNo' => $chkorder->row()->order_id,
                    'order_status' => $order_status,
                    'pickup_datetime' => $chkorder->row()->pickup_datetime,
                    'delivery_datetime' => $chkorder->row()->delivery_datetime,
                    'pickup_endtime' => $chkorder->row()->pickup_endtime,
                    'delivery_endtime' => $chkorder->row()->drop_endtime,
                    'createdon' => $curdt,
                    "delivery_company" => $chkorder->row()->delivery,
                    'shipper_id' => $shipper_id,
                    'delivery_contact' => $cncontact,
                    'delivery_city' => $chkorder->row()->delivery_city,
                    'delivery_country' => $chkorder->row()->delivery_country,
                    'delivery_address1' => $chkorder->row()->delivery_address1,
                    'delivery_address2' => $chkorder->row()->delivery_address2,
                    'delivery_pincode' => $chkorder->row()->delivery_pincode,
                    'branch_code' => $branch_code,
                    'company_code' => $company_code,
                    'transport_mode' => $chkorder->row()->transport_mode,
                    'pickup_country' => $chkorder->row()->pickup_country,
                    'pickup_pincode' => $chkorder->row()->pickup_pincode,
                    'country_code' => $code,
                    "pickup_company" => $chkorder->row()->pickup,
                    'pickup_contact' => $cacontact,
                    'pickup_city' => $chkorder->row()->pickup_city,
                    'pickup_address1' => $chkorder->row()->pickup_address1,
                    'pickup_address2' => $chkorder->row()->pickup_address2,
                    'cargos' => $cargos,
                    'tripsts' => $tripsts,
                    'ststime' => $upddt,
                    "area_code" => $areacodes[1],
                    "goods_value" => $chkorder->row()->goods_value,
                    "currency" => $currency,
                    "parties" => $parties,
                    "customerdetails" => $customerdetails,
                    'order_type' => $orderType,
                    'product' => $chkorder->row()->product,
                    'service' => $orderService,
                    'incoterm' => $chkorder->row()->incoterm,
                    'quantity' => $chkorder->row()->quantity,
                    'volume' => $chkorder->row()->volume,
                    'weight' => $chkorder->row()->weight,
                    'refrences' => $refrences,
                    'valueAddser' => $valueAddser,
                    'department_code' => $chkorder->row()->department_code,
                    "hrs" => $hrs,
                    "curtz" => $curtz,
                    'plat' => $chkorder->row()->plat,
                    'plng' => $chkorder->row()->plng,
                    'dlat' => $chkorder->row()->dlat,
                    'dlng' => $chkorder->row()->dlng,
                    'sourceReferences' => $sourceReferences,
                    'destinationReferences' => $destinationReferences,
                    'pickup_state' =>$pickup_state,
                    'pickup_email' =>$pickup_email,
                    'consignee_id' =>$consignee_id,
                    'delivery_state' =>$delivery_state,
                    'delivery_email' =>$delivery_email,
                    'delivery_term_id' => $delivery_term_id,
                    'delivery_term_name'=> $delivery_term_name,
                    'logicalreceiver'=>$LogicalReceiver,
                    'physicalreceiver'=>$PhysicalReceiver,
                    'physicalsender'=>$PhysicalSender,
                    'logicalsender'=>$LogicalSender,
                    'volume_unit' => $volume_unit,
                    'weight_unit' => $weight_unit,
                    'total_volume' => $total_volume,
                    'total_weight' => $total_weight
                ];
                $this->generateorderxml( $data );
            }
        }
    }

    public function generateorderxml( $data ) {
        $date      = date( 'Y-m-d H:i:s' );
        $timestamp = strtotime( $date );
        $request   = '';
        $request   .= '<TransmissionMessage>';
        $request   .= '<TransmissionHeader>';
        $request   .= '<Version>1.0</Version>';
        $request   .= '<UserName>INFD/PNQFD.INTEGRATION</UserName>';
        $request   .= '<Password>ALLIANCE</Password>';
        $request   .= '<SenderTransmissionNo>' . $timestamp . '_' . $data['SenderTransmissionNo'] . '</SenderTransmissionNo>';
        $request   .= '<AckSpec>';
        $request   .= '<ComMethodGid>transmission</ComMethodGid>';
        $request   .= '<ComType>';
        $request   .= '<Url>https://elog360.app/svkonekt_test/api/v1/edi</Url>';
        $request   .= '<EmailAddress>dummy@email.com</EmailAddress>';
        $request   .= '</ComType>';
        $request   .= '<AckOption>SUCCESS</AckOption>';
        $request   .= '</AckSpec>';
        $request   .= '<Source>ETN</Source>';
        $request   .= '<Destination>' . $data['branch_code'] . '</Destination>';
        $request   .= '<ReferenceId>' . $data['SenderTransmissionNo'] . '</ReferenceId>';
        $modetrans = "FTL";
        if ( isset( $data['transport_mode'] ) ) {
            if ( $data['transport_mode'] == "TL" ) {
                $modetrans = "FTL";
            } else {
                $modetrans = "LTL";
            }
        }
        $request .= '<ModeOfTransport>' . $modetrans . '</ModeOfTransport>';
        $request .= '<Action>BookingDetails</Action>';
        $request .= '</TransmissionHeader>';
        $request .= '<TransmissionBody>';
        $request .= '<InvolvedParties>';
        foreach ( $data['parties'] as $ptype ) {
            if ( isset( $ptype['type'] ) ) {
                if ( $ptype['type'] == "Shipper" ) {
                    $request .= '<Shipper>';
                }
                if ( $ptype['type'] == "Carrier" ) {
                    $request .= '<Carrier>';
                }
                if ( $ptype['type'] == "Consignor" ) {
                    $request .= '<Consignor>';
                }
                if ( $ptype['type'] == "Consignee" ) {
                    $request .= '<Consignee>';
                }
                $request .= '<ID>' . $ptype['party_id'] . '</ID>';
                $request .= '<FirstName>' . $ptype['name'] . '</FirstName>';
                $request .= '<LastName>' . $ptype['name'] . '</LastName>';
                $request .= '<FullName>' . $ptype['name'] . '</FullName>';
                if ( $ptype['type'] == "Shipper" ) {
                    $request .= '<UserName>ratchanee.limwatthana@kuehne-nagel.com</UserName>';
                    $request .= '<Password>$2a$11$7xOpu6cePv2sR4HrzWGyOui1evc5GyHE2/72UQjYK9OJOvIEyKZGW</Password>';
                }
                if ( $ptype['type'] == "Carrier" ) {
                    $request .= '<UserName>thananyas@jtclogistics.com</UserName>';
                    $request .= '<Password>$2a$11$NrwvCZ2E9RTMdQJSlUGCT.Jeb13bKWkJP.HQ6pOdcSWjV74Y.18c2</Password>';
                }
                $request .= '<ContactNo>';
                $request .= '<CountryCode>' . $data['country_code'] . '</CountryCode>';
                $request .= '<AreaCode>' . $data['area_code'] . '</AreaCode>';
                $request .= '<ContactNo>' . $ptype['phone'] . '</ContactNo>';
                $request .= '</ContactNo>';
                $request .= '<Company>';
                $request .= '<Name>' . $data['pickup_company'] . '</Name>';
                $request .= '<ContactNo>+' . $data['country_code'] . '' . $data['area_code'] . '' . $ptype['phone'] . '</ContactNo>';
                $request .= '<RegistrationNumber>' . $ptype['party_id'] . '</RegistrationNumber>';
                $request .= '<EmailAddress>' . $ptype['email'] . '</EmailAddress>';
                $request .= '</Company>';
                $request .= '<Address>';
                $request .= '<Country>' . $ptype['country'] . '</Country>';
                $request .= '<City>' . $ptype['city'] . '</City>';
                $request .= '<Postal>' . $ptype['pincode'] . '</Postal>';
                $request .= '<Address1>' . $ptype['address'] . '</Address1>';
                $request .= '<Address2>' . $ptype['street'] . '</Address2>';
                $request .= '</Address>';
                if ( $ptype['type'] == "Consignor" ) {
                    $request .= '<Comments></Comments>';
                }
                if ( $ptype['type'] == "Consignee" ) {
                    $request .= '<Comments></Comments>';
                }
                if ( $ptype['type'] == "Shipper" ) {
                    $request .= '</Shipper>';
                }
                if ( $ptype['type'] == "Carrier" ) {
                    $request .= '</Carrier>';
                }
                if ( $ptype['type'] == "Consignor" ) {
                    $request .= '</Consignor>';
                }
                if ( $ptype['type'] == "Consignee" ) {
                    $request .= '</Consignee>';
                }
            }
        }
        $request .= '</InvolvedParties>';
        /*$request .= '<VehicleDetails>';
      $request .= '<VehicleTypeCode>6WC</VehicleTypeCode>';
      $request .= '<VehicleModelCode>SIX_WHEELER</VehicleModelCode>';
      $request .= '<RegistrationNumber></RegistrationNumber>';
      $request .= '<License></License>';
      $request .= '<ApplicableForDangerousGoods></ApplicableForDangerousGoods>';
      $request .= '<CommodityType>6 Wheeler Cabinet</CommodityType>';
      $request .= '<Properties>';
      $request .= '</Properties>';
      $request .= '</VehicleDetails>';*/
        $request .= '<TripDetails>';
        $request .= '<PickUp>';
        $request .= '<Company>';
        $request .= '<Name>' . $data['pickup_company'] . '</Name>';
        $request .= '<ContactNo>' . $data['pickup_contact'] . '</ContactNo>';
        $request .= '</Company>';
        $request .= '<Address>';
        $request .= '<Country>' . $data['pickup_country'] . '</Country>';
        $request .= '<City>' . $data['pickup_city'] . '</City>';
        $request .= '<Postal>' . $data['pickup_pincode'] . '</Postal>';
        $request .= '<Address1>' . $data['pickup_address1'] . '</Address1>';
        $request .= '<Address2>' . $data['pickup_address2'] . '</Address2>';
        $request .= '</Address>';
        $request .= '<DateTime>';
        $request .= '<From>' . date( "Y-m-d", strtotime( $data['pickup_datetime'] ) ) . 'T' . date( "H:i:s", strtotime( $data['pickup_datetime'] ) ) . '.000</From>';
        $request .= '<To>' . date( "Y-m-d", strtotime( $data['pickup_endtime'] ) ) . 'T' . date( "H:i:s", strtotime( $data['pickup_endtime'] ) ) . '.000</To>';
        $request .= '</DateTime>';
        $request .= '</PickUp>';
        $request .= '<DropOff>';
        $request .= '<Company>';
        $request .= '<Name>' . $data['delivery_company'] . '</Name>';
        $request .= '<ContactNo>' . $data['delivery_contact'] . '</ContactNo>';
        $request .= '</Company>';
        $request .= '<Address>';
        $request .= '<Country>' . $data['delivery_country'] . '</Country>';
        $request .= '<City>' . $data['delivery_city'] . '</City>';
        $request .= '<Postal>' . $data['delivery_pincode'] . '</Postal>';
        $request .= '<Address1>' . $data['delivery_address1'] . '</Address1>';
        $request .= '<Address2>' . $data['delivery_address2'] . '</Address2>';
        $request .= '</Address>';
        $request .= '<DateTime>';
        $request .= '<From>' . date( "Y-m-d", strtotime( $data['delivery_datetime'] ) ) . 'T' . date( "H:i:s", strtotime( $data['delivery_datetime'] ) ) . '.000</From>';
        $request .= '<To>' . date( "Y-m-d", strtotime( $data['delivery_endtime'] ) ) . 'T' . date( "H:i:s", strtotime( $data['delivery_endtime'] ) ) . '.000</To>';
        $request .= '</DateTime>';
        $request .= '</DropOff>';
        $request .= '</TripDetails>';
        $request .= '<CargoDetails>';
        $request .= '<CargoType>GENERAL CATEGORY</CargoType>';
        $request .= '<ValueOfGoods>' . $data['goods_value'] . '</ValueOfGoods>';
        $request .= '<Items>';
        if ( ! empty( $cargos ) ) {
            foreach ( $cargos as $goods ) {
                $request .= '<Item>';
                $request .= '<HandlingUnit>' . $goods['cargo_type'] . '</HandlingUnit>';
                $request .= '<Length>';
                $request .= '<Value>' . $goods['length'] . '</Value>';
                $request .= '<UOM>m</UOM>';
                $request .= '</Length>';
                $request .= '<Width>';
                $request .= '<Value>' . $goods['width'] . '</Value>';
                $request .= '<UOM>m</UOM>';
                $request .= '</Width>';
                $request .= '<Height>';
                $request .= '<Value>' . $goods['height'] . '</Value>';
                $request .= '<UOM>m</UOM>';
                $request .= '</Height>';
                $request .= '<Weight>';

                $request .= '<Value>' . $goods['weight'] . '</Value>';
                $request .= '<UOM>m</UOM>';
                $request .= '</Weight>';
                $request .= '<TotalVolume>';
                $request .= '<Value>' . $data['total_volume'] . '</Value>';
                $request .= '<UOM>cbm</UOM>';
                $request .= '</TotalVolume>';
                $request .= '<TotalWeight>';
                $request .= '<Value>' . $data['total_weight'] . '</Value>';
                $request .= '<UOM>kg</UOM>';
                $request .= '</TotalWeight>';
                $request .= '<Quantity>' . $data['quantity'] . '</Quantity>';
                $request .= '</Item>';
            }
        }
        $request                 .= '</Items>';
        $request                 .= '</CargoDetails>';
        $request                 .= '<Rate>';
        $request                 .= '<BuyGroup>';
        $request                 .= '<Freights>';
        $request                 .= '<Freight>';
        $request                 .= '  <FreightBuyRate>2000</FreightBuyRate>';
        $request                 .= '<Description></Description>';
        $request                 .= '<RateUnit>trip</RateUnit>';
        $request                 .= '<Currency>' . $data['currency'] . '</Currency>';
        $request                 .= '<RevisedFreightBuyRate></RevisedFreightBuyRate>';
        $request                 .= '</Freight>';
        $request                 .= '</Freights>';
        $request                 .= '<Addons/>';
        $request                 .= '</BuyGroup>';
        $request                 .= '<SellGroup>';
        $request                 .= '<Freights>';
        $request                 .= '<Freight>';
        $request                 .= '<FreightBuyRate>2000</FreightBuyRate>';
        $request                 .= '<Description></Description>';
        $request                 .= '<RateUnit>trip</RateUnit>';
        $request                 .= '<Currency>' . $data['currency'] . '</Currency>';
        $request                 .= '<KNMarginPercentage>25</KNMarginPercentage>';
        $request                 .= '<KNMarginAbs></KNMarginAbs>';
        $request                 .= '<SellPrice>2500</SellPrice>';
        $request                 .= '</Freight>';
        $request                 .= '</Freights>';
        $request                 .= '<Addons/>';
        $request                 .= '<Discount>500</Discount>';
        $request                 .= '</SellGroup>';
        $request                 .= '</Rate>';
        $request                 .= '<Status>';
        $request                 .= '<Shipper>';
        $request                 .= '<StatusCode>READY_FOR_PICKUP</StatusCode>';
        $request                 .= '<StatusValue>READY_FOR_PICKUP</StatusValue>';
        $request                 .= '<DateTime>' . date( "Y-m-d", strtotime( $data['createdon'] ) ) . 'T' . date( "H:i:s", strtotime( $data['createdon'] ) ) . '.049Z</DateTime>';
        $request                 .= '</Shipper>';
        $request                 .= '<Carrier>';
        $request                 .= '<StatusCode>READY_FOR_PICKUP</StatusCode>';
        $request                 .= '<StatusValue>READY_FOR_PICKUP</StatusValue>';
        $request                 .= '<DateTime>' . date( "Y-m-d", strtotime( $data['createdon'] ) ) . 'T' . date( "H:i:s", strtotime( $data['createdon'] ) ) . '.049Z</DateTime>';
        $request                 .= '</Carrier>';
        $request                 .= '<Booking>';
        $request                 .= '<StatusCode>' . $data['tripsts'] . '</StatusCode>';
        $request                 .= '<StatusValue>' . $data['tripsts'] . '</StatusValue>';
        $request                 .= '<DateTime>' . date( "Y-m-d", strtotime( $data['ststime'] ) ) . 'T' . date( "H:i:s", strtotime( $data['ststime'] ) ) . '.049Z</DateTime>';
        $request                 .= '</Booking>';
        $request                 .= '</Status>';
        $request                 .= '<Remarks>';
        $request .= '<ShipperInstructions></ShipperInstructions>';
        $request .= '<AddressComments></AddressComments>';
        $request .= '<SpecialAddons></SpecialAddons>';
        $request .= '</Remarks>';
        $request .= '<KNOrgDetails>';
        $request .= '<KNCompanycode>' . $data['company_code'] . '</KNCompanycode>';
        $request .= '<KNBranchcode>' . $data['branch_code'] . '</KNBranchcode>';
        $request .= '</KNOrgDetails>';
        $request .= '</TransmissionBody>';
        $request .= '</TransmissionMessage>';
        $resname = date("Ymdhis");
        $dom = new DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->loadXML($request);
        $dom->save('xml/response' . $resname . '.xml');
        $serviceurl = BOOKING_ETRA_URL;
        $username = BOOKING_ETRA_USRNAME;
        $password = BOOKING_ETRA_PWD;
        /*$username = "ws_etra";
    $password = "4fh2drGs3n";*/
        $auth = base64_encode($username . ':' . $password);
        $headers = array(
            'Content-Type: application/xml',
            'Authorization: Basic ' . base64_encode( "$username:$password" )
        );
        $output  = thirdpartyservicecurl( $serviceurl, $headers, $request );
    }

    public function creditblock() {
        $post            = $this->input->post();
        $uid             = $this->session->userdata( 'user_id' );
        $data['status']  = 0;
        $curdt           = date( 'Y-m-d H:i:s' );
        $cb_orderid      = isset( $post['cb_orderid'] ) ? $post['cb_orderid'] : 0;
        $creditid        = isset( $post['creditid'] ) ? $post['creditid'] : 0;
        $cb_companycode  = isset( $post['cb_companycode'] ) ? $post['cb_companycode'] : "";
        $cb_branchcode   = isset( $post['cb_branchcode'] ) ? $post['cb_branchcode'] : "";
        $cb_departcode   = isset( $post['cb_departcode'] ) ? $post['cb_departcode'] : "";
        $stoppage_id     = isset( $post['stoppage_id'] ) ? $post['stoppage_id'] : 0;
        $stoppage_name   = isset( $post['stoppage_name'] ) ? $post['stoppage_name'] : "";
        $stoppage_remark = isset( $post['stoppage_remark'] ) ? $post['stoppage_remark'] : "";
        $remainder_date  = isset( $post['remainder_date'] ) ? $post['remainder_date'] : date( 'Y-m-d' );
        $return_date     = isset( $post['return_date'] ) ? $post['return_date'] : date( 'Y-m-d' );
        $resolution_id   = isset( $post['resolution_id'] ) ? $post['resolution_id'] : 0;
        $resolution_date = isset( $post['resolution_date'] ) ? $post['resolution_date'] : date( 'Y-m-d' );
        $extra_cost      = isset( $post['extra_cost'] ) ? $post['extra_cost'] : 0;
        $extracost_id    = isset( $post['extracost_id'] ) ? $post['extracost_id'] : "";
        $status_id       = isset( $post['status_id'] ) ? $post['status_id'] : 0;
        $status_dttime   = isset( $post['status_dttime'] ) ? $post['status_dttime'] : date( 'Y-m-d H:i:s' );
        $status_remark   = isset( $post['status_remark'] ) ? $post['status_remark'] : "";
        $remainder_date  = date( 'Y-m-d', strtotime( $remainder_date ) );
        $return_date     = date( 'Y-m-d', strtotime( $return_date ) );
        $resolution_date = date( 'Y-m-d', strtotime( $resolution_date ) );
        if ( $creditid == 0 ) {
            $insdata        = array(
                'order_id'         => $cb_orderid,
                'stoppage_id'      => $stoppage_id,
                'stoppage_name'    => $stoppage_name,
                'stoppage_remarks' => $stoppage_remark,
                'remainder_date'   => $remainder_date,
                'return_date'      => $return_date,
                'resolution_id'    => $resolution_id,
                'resolution_date'  => $resolution_date,
                'extra_cost'       => $extra_cost,
                'extracost_id'     => $extracost_id,
                'status_id'        => $status_id,
                'status_datetime'  => $status_dttime,
                'status_remark'    => $status_remark,
                'company_code'     => $cb_companycode,
                'branch_code'      => $cb_branchcode,
                'department_code'  => $cb_departcode,
                'user_id'          => $uid,
                'status'           => 1,
                'created_on'       => $curdt,
                'updated_on'       => $curdt
            );
            $ins            = $this->db->insert( "tbl_credit_blocked", $insdata );
            $creditblockid  = $this->db->insert_id();
            $data['status'] = 1;
        } else {
            $updata         = array(
                'order_id'         => $cb_orderid,
                'stoppage_id'      => $stoppage_id,
                'stoppage_name'    => $stoppage_name,
                'stoppage_remarks' => $stoppage_remark,
                'remainder_date'   => $remainder_date,
                'return_date'      => $return_date,
                'resolution_id'    => $resolution_id,
                'resolution_date'  => $resolution_date,
                'extra_cost'       => $extra_cost,
                'extracost_id'     => $extracost_id,
                'status_id'        => $status_id,
                'status_datetime'  => $status_dttime,
                'status_remark'    => $status_remark,
                'company_code'     => $cb_companycode,
                'branch_code'      => $cb_branchcode,
                'department_code'  => $cb_departcode,
                'user_id'          => $uid,
                'updated_on'       => $curdt
            );
            $updatecredit   = $this->db->where_in( "id", $creditid )->update( "tbl_credit_blocked", $updata );
            $data['status'] = 1;
        }
        echo json_encode( $data );
    }

    public function checkcreditblocked() {
        $post     = $this->input->post();
        $order_id = isset( $post['order_id'] ) ? $post['order_id'] : 0;
        $data     = array();
        if ( $order_id > 0 ) {
            $creditdata = $this->Order->getcreditdata( "tbl_credit_blocked", $order_id );
            if ( $creditdata->num_rows() > 0 ) {
                $data = array(
                    'creditid'        => $creditdata->row()->id,
                    'cb_orderid'      => $creditdata->row()->order_id,
                    'stoppage_id'     => $creditdata->row()->stoppage_id,
                    'stoppage_name'   => $creditdata->row()->stoppage_name,
                    'stoppage_remark' => $creditdata->row()->stoppage_remarks,
                    'remainder_date'  => $creditdata->row()->remainder_date,
                    'return_date'     => $creditdata->row()->return_date,
                    'resolution_id'   => $creditdata->row()->resolution_id,
                    'resolution_date' => $creditdata->row()->resolution_date,
                    'extra_cost'      => $creditdata->row()->extra_cost,
                    'extracost_id'    => $creditdata->row()->extracost_id,
                    'status_id'       => $creditdata->row()->status_id,
                    'status_dttime'   => $creditdata->row()->status_datetime,
                    'status_remark'   => $creditdata->row()->status_remark,
                    'cb_companycode'  => $creditdata->row()->company_code,
                    'cb_branchcode'   => $creditdata->row()->branch_code,
                    'cb_departcode'   => $creditdata->row()->department_code
                );
            }

        }
        echo json_encode( $data );
    }

    public function getstoppagename( $id ) {
        $data['name'] = "";
        if ( $id != "" ) {
            $getdesc = $this->db->query( "SELECT name FROM tbl_stoppage_master WHERE id=$id AND status=1" );
            if ( $getdesc->num_rows() > 0 ) {
                $data['name'] = $getdesc->row()->name;
            }
        }
        echo json_encode( $data );
    }

    public function getconinfo( $order_row_id ) {
        $this->load->model( 'truckwaybillmodel' );
        $serviceurl   = SPOTON_URL;
        $username     = SPOTON_USRNAME;
        $password     = SPOTON_PWD;
        $headers      = array(
            'Content-Type: application/json',
            'Authorization: Basic ' . base64_encode( "$username:$password" )
        );
        $requestinfo  = $req_in_arr = array();
        $where        = array( "id" => $order_row_id );
        $select       = "order_id,transport_mode,weight,delivery_city,pickup_city,pickup_datetime,pickup_pincode,delivery_pincode";
        $table        = "tb_orders";
        $order        = $this->common->gettblrowdata( $where, $select, $table, 0, 0 );
        $user_id      = $this->session->userdata( 'user_id' );
        $company_code = $this->session->userdata( 'company_code' );
        $branch_code  = $this->session->userdata( 'branch_code' );
        $order_number = '';
        $serviceurlorigin   = SPOTON_PIN_URL.'?pincode='.$order['pickup_pincode'].'&pincodeType=P';
        $serviceurldestin   = SPOTON_PIN_URL.'?pincode='.$order['delivery_pincode'].'&pincodeType=D';
        $request_id   = 0;
        // Enabled log
        $orgstatus = thirdparty_curl_get( $serviceurlorigin, $headers );
        $orgstatus = json_decode($orgstatus);

        $deststatus = thirdparty_curl_get( $serviceurldestin, $headers );
        $deststatus = json_decode($deststatus);
        if(isset($orgstatus->Serviceable) && isset($deststatus->Serviceable) && $orgstatus->Serviceable =='Y' && $deststatus->Serviceable=='Y'){

            // Kn LR reference number generation
            $chkqry = $this->db->query("SELECT reference_id, ref_value FROM `tb_order_references` WHERE `reference_id` = 'ELR' ORDER BY `id` DESC LIMIT 1")->result();

            $ins_arr = array(
                'order_id'     => $order_row_id,
                'reference_id' => 'ELR',
                'createdon'    => date('Y-m-d H:i:s'),
                'status'       => 1
            );
            if(count($chkqry) == 0){
                $ins_arr['ref_value'] = 'SVK'.$order['transport_mode'].'000001';
                $ins = $this->db->insert( 'tb_order_references', $ins_arr );
            }else{
                $val = sprintf('%06s', substr($chkqry[0]->ref_value,-6) + 1);
                $ins_arr['ref_value'] = 'SVK'.$order['transport_mode'].$val;
                $ins = $this->db->insert( 'tb_order_references', $ins_arr );
            }
            if ( count( $order ) > 0 ) {
                $reference_val   = $ins_arr['ref_value'];
                $where           = array( "order_id" => $order_row_id );
                $select          = "length,width,height,quantity";
                $table           = "tb_order_cargodetails";
                $dimensions      = array();
                $order_cargo     = $this->common->gettbldata( $where, $select, $table, 0, 0 );
                $pickupinfo      = $this->truckwaybillmodel->getshipper( $order_row_id, 'Shipper' );
                $receiverinfo    = $this->truckwaybillmodel->getshipper( $order_row_id, 'Consignee' );

                $raddress=$receiverinfo['address'];
                if($receiverinfo['address'] == ''){
                    $raddress= $receiverinfo['street'].','.$receiverinfo['location_id'];
                }

                $order_number    = $order['order_id'];
                $order_reference = $this->truckwaybillmodel->orderrefernce( $order_number );
                if ( count( $order_reference ) > 0 ) {
                    foreach ( $order_reference as $res ) {
                        $reference_val = $res['ref_value'] . ",";
                    }
                }
                $reference_val  = trim( $reference_val, "," );
                $total_packages = 0;
                if ( count( $order_cargo ) > 0 ) {
                    foreach ( $order_cargo as $info ) {
                        $dimensions[]   = [
                            'Length' => round(floatval($info['length'])),
                            'Breadth' => round(floatval($info['width'])),
                            'height' => round(floatval($info['height'])),
                            'Pieces' => round(floatval($info['quantity']))
                        ];
                        $total_packages = $total_packages + $info['quantity'];
                    }
                }
                $picklocationname = isset( $pickupinfo['location_id'] ) ? $pickupinfo['location_id'] : "";
                if ( $picklocationname == '' ) {
                    $picklocationname = $order['pickup_city'];
                }
                $pickpincode = isset( $pickupinfo['pincode'] ) ? $pickupinfo['pincode'] : "";

                $pickaddress = isset( $pickupinfo['address'] ) ? $pickupinfo['address'] : $pickupinfo['street'].$pickupinfo['location_id'];

                $pickmobile = isset( $pickupinfo['mobile'] ) ? $pickupinfo['mobile'] : "";
                $pickemail  = isset( $pickupinfo['email'] ) ? $pickupinfo['email'] : "";

                $pickup_datetime                   = date( "Y-m-d", strtotime( $order['pickup_datetime'] ) );
                $requestinfo['UniqueHashValue']    = '#@64@!$%3';
                $requestinfo['CustomerCode']       = $username;
                $requestinfo['PickupPincode']      = substr( $pickpincode, 0, 6 );
                $requestinfo['PickupDateTime']     = $pickup_datetime;
                $requestinfo['ReceiverPincode']    = substr( $receiverinfo['pincode'], 0, 6 );
                $requestinfo['PaymentMode']        = 'credit';
                $requestinfo['PickupLocationName'] = $picklocationname;
                $requestinfo['PickupAddress']      = $pickaddress;
                $requestinfo['PickupCity']         = $order['pickup_city'];
                $requestinfo['PickupContactPhone'] = $pickmobile;
                $requestinfo['PickupContactMail']  = $pickemail;
                $requestinfo['ReceiverName']          = $receiverinfo['name'];
                $requestinfo['ReceiverAddress']       = $raddress;
                $requestinfo['ReceiverCity']          = $order['delivery_city'];
                $requestinfo['ReceiverContactPerson'] = $receiverinfo['name'];
                $requestinfo['ReceiverContactPhone']  = $receiverinfo['mobile'];
                $requestinfo['ReceiverMail']          = $receiverinfo['email'];
                $requestinfo['TotalPackages']         = $total_packages;
                $requestinfo['TotalActualWeight']     = $order['weight'];
                $requestinfo['Remarks']               = 'Pickup and delivery notes';
                $requestinfo['SpecialInstruction']    = 'On time';
                $requestinfo['VTCApplicable']         = 'N';
                $requestinfo['VTCAmount']             = '0';
                $requestinfo['ReferenceNumber']       = $reference_val;
                $requestinfo['TINNumber']             = '';
                $requestinfo['AWBConsignmentValue']   = '0';
                $requestinfo['GstIn']                 = '';
                $requestinfo['ProductId']             = '';
                $requestinfo['SplInstruction']        = '';
                $requestinfo['Dimensions']            = $dimensions;
                //store value to con request table
                $req_in_arr = array(
                    'customer_code'         => $requestinfo['CustomerCode'],
                    'unique_value'          => $requestinfo['UniqueHashValue'],
                    'order_id'              => $order_number,
                    'order_rowid'           => $order_row_id,
                    'user_id'               => $user_id,
                    'company_code'          => $company_code,
                    'branch_code'           => $branch_code,
                    'pickup_pincode'        => $requestinfo['PickupPincode'],
                    'pickupdatetime'        => $requestinfo['PickupDateTime'],
                    'pickupreadytime'       => '',
                    'receiverpincode'       => $requestinfo['ReceiverPincode'],
                    'paymentmode'           => $requestinfo['PaymentMode'],
                    'pic_loc_name'          => $requestinfo['PickupLocationName'],
                    'pickupaddress'         => $requestinfo['PickupAddress'],
                    'pickupcity'            => $requestinfo['PickupCity'],
                    'pic_contactphone'      => $requestinfo['PickupContactPhone'],
                    'pic_contactmail'       => $requestinfo['PickupContactMail'],
                    'receivername'          => $requestinfo['ReceiverName'],
                    'receiveraddress'       => $requestinfo['ReceiverAddress'],
                    'receivercontactperson' => $requestinfo['ReceiverContactPerson'],
                    'receiver_cont_phone'   => $requestinfo['ReceiverContactPhone'],
                    'receivermail'          => $requestinfo['ReceiverMail'],
                    'totalpackages'         => $requestinfo['TotalPackages'],
                    'tot_actual_weight'     => $requestinfo['TotalActualWeight'],
                    'remarks'               => $requestinfo['Remarks'],
                    'special_instruction'   => $requestinfo['SpecialInstruction'],
                    'vtc_applicable'        => $requestinfo['VTCApplicable'],
                    'vtc_amount'            => $requestinfo['VTCAmount'],
                    'refe_number'           => $requestinfo['ReferenceNumber'],
                    'tin_number'            => $requestinfo['TINNumber'],
                    'awb_consig_value'      => $requestinfo['AWBConsignmentValue'],
                    'gst_in'                => $requestinfo['GstIn'],
                    'product_id'            => $requestinfo['ProductId'],
                    'spl_instruction'       => $requestinfo['SplInstruction'],
                    'eway_bill'             => '',
                    'invoice_no'            => '',
                    'invoice_amt'           => '0',
                    'dimensions'            => json_encode( $dimensions )
                );
                $request_id = $this->common->insertTableData( 'tb_getcon_request', $req_in_arr );

            }
            $json_request = json_encode( $requestinfo );
            $response = thirdpartyservicecurl( $serviceurl, $headers, $json_request );

            if ( $response ) {
                $response = (Object)$response;
                $startNo   = ( isset( $response->Pieces[0]['StartNo'] ) && ! empty( $response->Pieces[0]['StartNo'] ) ) ? (string) ( $response->Pieces[0]['StartNo'] ) : "0";
                $endNo     = ( isset( $response->Pieces[0]['EndNo'] ) && ! empty( $response->Pieces[0]['EndNo'] ) ) ? (string) ( $response->Pieces[0]['EndNo'] ) : "0";
                $res_array = array(
                    'request_id'      => $request_id,
                    'order_id'        => $order_number,
                    'order_rowid'     => $order_row_id,
                    'company_code'    => $company_code,
                    'branch_code'     => $branch_code,
                    'res_status'      => $response->Status,
                    'error_remarks'   => $response->ErrorRemarks,
                    'unique_value'    => $response->UniqueValue,
                    'customer_refno'  => $response->CustomerRefNo,
                    'con_num'         => $response->ConNo,
                    'pickup_sccode'   => $response->PickupScCode,
                    'delivery_sccode' => $response->DeliveryScCode,
                    'pickup_order_no' => $response->PickupOrderNo,
                    'pie_startno'     => $startNo,
                    'pie_endno'       => $endNo,
                    'error_code'      => $response->ErrorCode,
                    'user_id'         => $user_id
                );
                $con_resp_id=$this->common->insertTableData( 'tb_getcon_response', $res_array );

                $ins_ar = array(
                    'order_id'     => $order_row_id,
                    'reference_id' => 'BN',
                    'ref_value'    => $response->ConNo,
                    'status'       => 1,
                    'createdon'    =>date('Y-m-d H:i:s'),
                );
                $chkqry = $this->db->select( 'id' )->get_where( "tb_order_references", array( 'order_id' => $order_row_id, 'reference_id' => 'BN', 'ref_value' => $response->ConNo ) );
                if ( $chkqry->num_rows() == 0 ) {
                    $ins = $this->db->insert( 'tb_order_references', $ins_ar );
                }

                /* code for ABH - Pickuporder number */
                if ( $response->PickupOrderNo != '' ) {
                    $picins_ar = array(
                        'order_id'     => $order_row_id,
                        'reference_id' => 'ABH',
                        'ref_value'    => $response->PickupOrderNo,
                        'status'       => 1,
                        'createdon'    =>date('Y-m-d H:i:s'),
                    );
                    $chkqry    = $this->db->select( 'id' )->get_where( "tb_order_references", array( 'order_id' => $order_row_id, 'reference_id' => 'ABH', 'ref_value' => $response->PickupOrderNo ) );
                    if ( $chkqry->num_rows() == 0 ) {
                        $ins = $this->db->insert( 'tb_order_references', $picins_ar );
                    }
                }

                $lr_gen=$this->spotonlr($order_row_id);
                /* code for ABH - Pickuporder number */


            }
        }else{
            log_message( 'error', "Orders >> getconinfo(9905) >> Source or Destination pincodes are not available");
        }
    }

    public function check_trip(): void
    {
        $id = $this->input->post('order_id');
        $vendorcode = "";
        $res = 0;
        $userId = $this->session->userdata('user_id');
        $companyCode = $this->session->userdata('company_code');
        $getTripTemplates = $this->triptemplatemodel->getTripTemplatesByUser($companyCode);
        foreach ($getTripTemplates as $eachRow) {
            $templates[] = ['id' => $eachRow['id'], 'templateId' => $eachRow['template_id'], 'templateName' => $eachRow['template_name']];
        }
        $result = ['result' => 0, 'carrier_id' => 0, 'code' => "", 'templates' => $templates ?? []];
        if (!is_array($id)) {
            $where = ["id" => $id];
            $select = "vendor_id,shift_id,status";
            $table = "tb_orders";
            $order = $this->common->gettblrowdata($where, $select, $table, 0, 0);
            if (!empty($order)) {
                if ($order['shift_id'] > 0) {
                    $res = 1;
                }
                if ($order['vendor_id'] > 0) {
                    $vendor = $this->common->gettblrowdata(["id" => $order['vendor_id']], "code", "tb_vendors", 0, 0);
                    if (!empty($vendor)) {
                        $vendorcode = $vendor['code'];
                    }
                }
                $result = ['result' => $res, 'carrier_id' => $order['vendor_id'], 'code' => $vendorcode, 'templates' => $templates ?? [], 'status' => $order['status']];
            }
        } else {
            $bookids = implode(",", $id);
            $where = " id IN($bookids) AND shift_id != 0";
            $select = "id,vendor_id,status";
            $table = "tb_orders";
            $order = $this->common->gettblrowdata($where, $select, $table, 0, 0);
            if (!empty($order)) {
                $res = 1;
                if ($order['vendor_id'] > 0) {
                    $vendor = $this->common->gettblrowdata(["id" => $order['vendor_id']], "code", "tb_vendors", 0, 0);
                    if (!empty($vendor)) {
                        $vendorcode = $vendor['code'];
                    }
                }
                $result = ['result' => $res, 'carrier_id' => $order['vendor_id'], 'code' => $vendorcode, 'templates' => $templates ?? [], 'status' => $order['status']];
            }
        }
        echo json_encode($result);
    }

    public function GetOrderIntoapi( $order_id ) {
        $url     = "https://www.sevasetu.in/sp/index.php/api/tracking/track_v2";
        $headers = array(
            'Content-Type: application/json',
            'Username: maruticourier',
            'Password: 17322463b3e529f1ee3184444b7e0d61',
            'TOKEN: ABX78952-081E-41D4-8C86-FB410EF83123'
        );
        $where   = array(
            "order_id" => $order_id
        );
        $select  = "order_id,pickup_datetime,pickup_endtime,delivery_datetime,drop_endtime,pickup_company,delivery_company,pickup_country,delivery_country,pickup_city,delivery_city,pickup_pincode,delivery_pincode,pickup_address1,delivery_address1,pickup_address2,delivery_address2,quantity,weight,volume,goods_value,transport_mode,customer_name,customer_phone,customer_email,company_code,branch_code";

        $table      = "tb_orders";
        $data_order = $this->common->gettblrowdata( $where, $select, $table, 0, 0 );
        if ( count( $data_order ) > 0 ) {
            $postdata = array(
                'data' => $data_order
            );
            $getdata  = thirdpartyservicecurl( $url, $headers, $postdata );
            // assumption response array
            // {"success":"1","message":"Barcode successfully fetched.","data":{"barcode":{"order_id":"123","barcode_no":"589"}}}
            $json           = json_decode( $getdata, TRUE );
            $get_order_id   = $json['data']['barcode']['order_id'];
            $get_barcode_no = $json['data']['barcode']['barcode_no'];
            $where          = array(
                "order_id" => $get_order_id
            );
            $select         = "order_id,ref_value";
            $table          = "tb_order_references";
            $data_ref       = $this->common->gettblrowdata( $where, $select, $table, 0, 0 );
            if ( count( $data_ref ) == 0 ) {
                $insdata = array(
                    'order_id'     => $get_order_id,
                    'reference_id' => 'DQ',
                    'ref_value'    => $get_barcode_no,
                    'status'       => 1
                );
                $this->db->insert( "tbl_credit_blocked", $insdata );
            }
        }
    }

    public function ordernotify(string $action, int $orderId): void
    {
        $this->load->library('notifytrigger');
        $info['page_title']  = 'Booking Notification';
        $info['order_id'] = $orderId;
        $info['action'] = $action;
        $orderInfo = $this->common->gettblrowdata(['id' => $orderId], 'order_id,shift_id,shipmentid', 'tb_orders', 0, 0);
        if ($orderInfo) {
            $info['orderid'] = $bookingId = $orderInfo['order_id'];
            $orderDetails = $this->DeliveryDocumentModel->getOrderCustomerName(0, $bookingId);
            $info['subject'] = "Booking ID:" . $bookingId . " Customer Name: " . $orderDetails[$bookingId]['customerName'] . " Delivery Docs: " . $orderDetails[$bookingId]['reference'];
            $info['cargos'] = $this->common->gettbldata(['order_id' => $orderId], 'quantity_type,quantity', 'tb_order_cargodetails', 0, 0);
            if ($action != 'trip_create') {
                $info['body'] = $this->load->view('mail_forms/notifytrigger/' . $action, $info, TRUE);
                $this->notifytrigger->sendordernotify($info);
            } else {
                $info['shift_id'] = $orderInfo['shift_id'];
                $info['shiftid'] = $orderInfo['shipmentid'] ?: '';
                $info['body'] = $this->load->view('mail_forms/notifytrigger/' . $action, $info, TRUE);
                $this->notifytrigger->sendtripnotify($info);
            }
        }
    }

    /*  public function testprefer(){
        $order_id = '1';
        $company_code = 'PLKN';
        $pref_arr = array('pickup'=>'GERMANY','drop'=>'POLAND','customer_id'=>'1000739642','service'=>'11','product'=>'KN PharmaChain','user_id'=>'7','company_code'=>$company_code,'order_id'=>$order_id);
        if($company_code == 'PLKN'){
            $this->ratemanagement->addrecodfororderinsertion($pref_arr);
        }
    }*/

    /* Australia ASN order empty values check  */
    public function emptycheckasnorder( $id ) {
        $where    = array( "status" => 1, "id" => $id );
        $whr      = array( "status" => 1, "order_id" => $id );
        $keys     = "missing fields:\n";
        $checkval = 0;
        /* get order data */
        $order_array = $this->Order->getauasnorderdata( $where );
        /* get Cargo data */
        $cargo_array = $this->Order->getasncargodetails( $whr );
        if ( ! empty( $order_array ) ) {
            /* get order array empty values */
            $get_order_em = array_filter( $order_array, function ( $val ) {
                return ( empty( $val ) );
            } );
            if ( ! empty( $get_order_em ) ) {
                /* get order array only keys  */
                $get_order_em_keys = array_keys( $get_order_em );
                /* get order array convert string  */
                $key      = implode( "\n", $get_order_em_keys );
                $keys     .= $key . "\n";
                $checkval = 1;
            }
        }
        /* log_message("error","check val :::".$checkval); */
        /* cargo  empty field keys */
        $cargo_keys = $this->cargofieldscheck( $cargo_array );
        if ( ! empty( $cargo_keys ) ) {
            $keys     .= $cargo_keys;
            $checkval = 1;
        }
        /* log_message("error","check val1 :::".$checkval); */
        $get_array = array( "keys" => $keys, "check_val" => $checkval );

        /* log_message("error","order check:::".json_encode($get_array)); */

        return $get_array;
        /* echo "<pre>";
        print_r($order_array);
        print_r($cargo_array);
        print_r($get_array); */
    }

    /* cargo  empty field Check */
    private function cargofieldscheck( $cargo_array ) {
        $keys             = "";
        $cargo_keys       = "";
        $array_kyes_cargo = array();
        if ( ! empty( $cargo_array ) ) {
            /* cargo array loop */
            for ( $i = 0; $i < count( $cargo_array ); $i ++ ) {
                /* get cargo array Empty values */
                $cargo_emtty_val[] = array_filter( $cargo_array[ $i ], function ( $val ) {
                    return ( empty( $val ) || $val <= 0 );
                } );
                if ( ! empty( $cargo_emtty_val ) ) {
                    /* get cargo array keys only */
                    $array_kyes_cargo[] = array_keys( $cargo_emtty_val[ $i ] );
                }
            }
            if ( ! empty( $array_kyes_cargo ) ) {
                /* cargo array multidimensional array to single array */
                $single_array = $this->multiarraytosingle( $array_kyes_cargo );
                /* cargo array remove duplicate values */
                $cargo_reslut = array_unique( $single_array );
                /* cargo array convert into string */
                $cargo_keys .= implode( "\n", $cargo_reslut );
                $keys       .= $cargo_keys;
            }
        }

        //$get_array=array("keys"=>$keys,"check_val"=>$checkval);
        return $keys;
    }

    private function getDefaultFilters(): array
    {
        return [
            "fromdate" => (new DateTime())->format('d-m-Y'),
            "todate" => (new DateTime())->format('d-m-Y')
        ];
    }

    private function multiarraytosingle( $array ) {
        if ( ! is_array( $array ) ) {
            return FALSE;
        }
        $result = array();
        foreach ( $array as $key => $value ) {
            if ( is_array( $value ) ) {
                $result = array_merge( $result, $this->multiarraytosingle( $value ) );
            } else {
                $result[ $key ] = $value;
            }
        }

        return $result;
    }

    /* Australia save pallets  */
    public function savepallets() {
        $id          = $this->input->post( 'order_row_id' );
        $num_pallets = $this->input->post( 'num_pallets' );
        $num_pallets = isset( $num_pallets ) ? $num_pallets : 0;
        $num_pallets = ! empty( $num_pallets ) ? $num_pallets : 0;
        $upd         = $this->common->updatetbledata( "tb_order_details", array( 'num_of_pallets' => $num_pallets ), array( "order_row_id" => $id ) );
        /* log_message('error',"post data".json_encode($this->input->post())); */
        echo json_encode( $upd );
    }


    /* Get refrence numbers Advanced search */
    public function getrefnum($user_id, $post) {
        $res = array();

        if ( isset( $post['order_reftype'] ) && $post['order_reftype'] != "" ) {
            if ( isset( $post['ref_val'] ) && $post['ref_val'] != "" ) {
                $ref_id     = trim( $post['order_reftype'] );
                $ref_val    = trim( $post['ref_val'] );
                $where_like = array( 'r.ref_value' => $ref_val );
                $permission = checkuserpermissions();

                if (in_array("orders", $permission)) {
                    $company_code = $this->session->userdata('company_code');
                    $whr = array(
                        'o.status!=' => '0',
                        'o.company_code' => $company_code,
                        'r.reference_id' => $ref_id,
                        'r.status' => 1
                    );
                } else {
                    $whr = array(
                        'o.status!=' => '0',
                        'o.user_id' => $user_id,
                        'r.reference_id' => $ref_id,
                        'r.status' => 1
                    );
                }

                $result     = $this->Order->getrefvals( $whr, $where_like );

                if ( ! empty( $result ) ) {
                    $res = array_column( $result, "order_id" );
                }
            }
        }

        return $res;

    }

    /* get booking ids by using container number

     */
    private function GetContainernum($user_id, $country_userids, $branch_code) {
        $res = array();

        $post = $this->input->get(NULL, TRUE);

        if (isset( $post['container_no'] ) && $post['container_no'] != "") {
            $ref_val         = trim( $post['container_no'] );
            $where_like      = array( 'r.ref_value' => $ref_val );
            $refid = "CTR";

            if($branch_code == "INCL"){
                $refid = "AWB";
            }

            $whr = array( 'o.status!='=>'0','r.reference_id'=>$refid,'r.status' => 1);
            $result = $this->Order->getrefvals( $whr, $where_like, $user_id, $country_userids );

            if ( ! empty( $result ) ) {
                $res = array_column( $result, "order_id" );
            }
        }

        return $res;
    }

    public function ajaxListing() {
        $this->load->model( 'Datatables_model' );
        $draw  = $this->input->get( 'draw' );
        $start = $this->input->get( 'start' );
        $indexColumn   = 'c.id';

        $get              = $this->input->get( 'data' );
        $order_id         = $get['order_id'];
        $actionType       = $get['actionType'];
        $companyCode       = $get['company_code'];
        if($companyCode == "AUKN"){
            $indexColumn = 'o.id';
        }
        $marksAndNumbersCondition = checkAccessConditions('MARKS_AND_NUMBERS_OPTION', $companyCode);
        $selectColumns = [
            'c.id',
            'c.cargo_type',
            'c.length_unit',
            'c.width_unit',
            'c.height_unit',
            'c.weight_unit',
            'c.volume_unit',
            'c.secondweight_uom',
            'c.secondvolume_uom',
            'c.goods_description',
            'c.stackable',
            'c.grounded',
            'c.splittable',
            'c.dg_goods',
            'o.id as ordcargoid',
            'o.length',
            'o.width',
            'o.height',
            'o.weight',
            'o.second_weight',
            'o.volume',
            'o.second_volume',
            'o.volumetric_weight',
            'o.volweight_uom',
            'c.ldm',
            'o.quantity',
            'o.scanned_quantity',
            'o.qr_code',
            'o.reference_order_num',
            'o.marks_numbers'
        ];

        if ($actionType == 'Edit') {
            $dataTableSortOrdering = [
                'c.id',
                'c.cargo_type',
                'c.goods_description',
                'o.marks_numbers',
                'o.quantity',
                'o.scanned_quantity',
                'o.length',
                'o.width',
                'o.height',
                'o.weight',
                'o.second_weight',
                'o.volumetric_weight',
                'o.volume',
                'o.second_volume',
                'c.ldm',
                'c.stackable',
                'c.grounded',
                'c.splittable',
                'c.dg_goods',
                'c.id'
            ];
        } else {
            if ($companyCode == 'AUKN') {
                $selectColumns[] = 'cl.bar_code';
                $dataTableSortOrdering = [
                    'c.cargo_type',
                    'c.goods_description',
                    'o.qr_code',
                    'o.quantity',
                    'o.scanned_quantity',
                    'o.length',
                    'o.width',
                    'o.height',
                    'o.weight',
                    'o.second_weight',
                    'o.volumetric_weight',
                    'o.volume',
                    'o.second_volume',
                    'c.ldm',
                    'c.id',
                    'c.stackable',
                    'c.grounded',
                    'c.splittable',
                    'c.dg_goods',
                    'cl.bar_code',
                    'c.id'
                ];
                
            } else {
                $dataTableSortOrdering = [
                    'c.cargo_type',
                    'c.goods_description',
                    'o.marks_numbers',
                    'o.quantity',
                    'o.scanned_quantity',
                    'o.length',
                    'o.width',
                    'o.height',
                    'o.weight',
                    'o.second_weight',
                    'o.volumetric_weight',
                    'o.volume',
                    'o.second_volume',
                    'c.ldm',
                    'c.stackable',
                    'c.grounded',
                    'c.splittable',
                    'c.dg_goods',
                    'c.id'
                ];
            }
        }

        $table_name            = 'tb_cargo_details c,tb_order_cargodetails o';
        $joinsArray            = array();
        if($companyCode == "AUKN"){
            $joinsArray[]=array('table_name'=>'tb_order_cargo_labels as cl','condition'=>"cl.order_id = o.order_id AND cl.cargo_id = o.cargo_id ",'join_type'=>'left');
        }
        
        $wherecondition   = " o.order_id ='" . $order_id . "' AND o.cargo_id=c.id AND o.status='1'  ";
        $groupBy          = 'c.id';
        if(!$marksAndNumbersCondition){
            $selectColumns = array_diff($selectColumns,['o.marks_numbers']);
            $dataTableSortOrdering = array_diff($dataTableSortOrdering,['o.marks_numbers']);
        }
        $getRecordListing = $this->Datatables_model->datatablesQuery( $selectColumns, $dataTableSortOrdering, $table_name, $joinsArray, $wherecondition, $indexColumn, '', $groupBy );
        $totalRecords     = $getRecordListing['recordsTotal'];
        $recordsFiltered  = $getRecordListing['recordsFiltered'];

        $recordListing    = array();
        $i                = 0;
        $srNumber = $start;

        if ( ! empty( $getRecordListing ) ) {
            $actionContent = '';
            if(isset($getRecordListing['data'])){
                $totalqty=sizeof($getRecordListing['data']);
            }else{
                $totalqty='0';
            }
            foreach ( $getRecordListing['data'] as $res ) {
                $stackable = 'Off';
                if ( $res->stackable == 0 ) {
                    $stackable = 'Off';
                } else if ( $res->stackable == 1 ) {
                    $stackable = 'On';
                }
                $grounded = 'Off';
                if ( $res->grounded == 0 ) {
                    $grounded = 'Off';
                } else if ( $res->grounded == 1 ) {
                    $grounded = 'On';
                }
                $splittable = 'Off';
                if ( $res->splittable == 0 ) {
                    $splittable = 'Off';
                } else if ( $res->splittable == 1 ) {
                    $splittable = 'On';
                }
                $dg_goods = ($res->dg_goods == 1) ? "<span title='Click To Get Dgoods' onclick = getDangerousGoodsDetails(" . $res->dg_goods . "," . $res->ordcargoid . ",".$order_id.") style='cursor:pointer;'>On</span>" : 'No';
                $cargo_type       = '"' . $res->cargo_type . '"';
                $goods_desc       = '"' . $res->goods_description . '"';
                $length_unit      = '"' . $res->length_unit . '"';
                $width_unit       = '"' . $res->width_unit . '"';
                $height_unit      = '"' . $res->height_unit . '"';
                $weight_unit      = '"' . $res->weight_unit . '"';
                $volume_unit      = '"' . $res->volume_unit . '"';
                $volweight_uom    = '"' . $res->volweight_uom . '"';
                $secondweight_uom = '"' . $res->secondweight_uom . '"';
                $secondvolume_uom = '"' . $res->secondvolume_uom . '"';
                $scanned_quantity = $res->scanned_quantity;
                $second_weight    = $res->second_weight;
                $second_volume    = $res->second_volume;
                $qrcode           = $res->qr_code;
                $volumetric_weight= $res->volumetric_weight;
                $ldm              = $res->ldm;

                if ( $scanned_quantity == "" ) {
                    $scanned_quantity = 0;
                }
                if ( $second_volume == "" ) {
                    $second_volume = 0;
                }
                if ( $second_weight == "" ) {
                    $second_weight = 0;
                }
                if ( $volumetric_weight == "" ) {
                    $volumetric_weight = 0;
                }
                if ( $ldm == "" ) {
                    $ldm = 0;
                }
                if ($scanned_quantity == 0) {
                    $alertmsg = "'There is no Labels Scanned for this cargo..!'";
                    $label = '<a href="#" onclick="alert(' . $alertmsg . ')"><span class="icon tru-icon-pdf"></span></a>';
                } else {
                    $label = '<a href="' . base_url(
                            "aulabel/index?order_car_id=" . $res->ordcargoid . "&tot=" . $totalqty . "&cargo_row_id=" . $i
                        ) . '" target="_blank" title="' . $this->lang->line(
                            'print_label'
                        ) . '"><span class="icon tru-icon-pdf"></span></a>';
                }

                $empty = "";
                if ($actionType == 'Edit'&& !$marksAndNumbersCondition) {
                    //edit cargo details is same for all the countries
                    if (($this->session->userdata('company_code') == "NZKN" || $this->session->userdata(
                                'company_code'
                            ) == "NZPG") && $this->session->userdata('cust_id') != "") {
                        $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft '> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcuscargoEdit(this," . $res->id . "," . $cargo_type . "," . $goods_desc . "," . $res->quantity . "," . $res->length . "," . $res->width . "," . $res->height . "," . $res->weight . "," . $res->volume . "," . $volumetric_weight . "," . $res->stackable . "," . $res->grounded . "," . $res->splittable . "," . $res->dg_goods . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scanned_quantity . "," . $second_weight . "," . $secondweight_uom . "," . $second_volume . "," . $secondvolume_uom . "," . $order_id . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='deleteordercargodetails(" . $res->id . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $res->id . ")'><span class='fa fa-archive' > </span>Get Inner Cargos</a></li>";
                    } else {
                        //$action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft '> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a data-ordertype='editOrder' id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcargoEdit(this," . $res->id . "," . $cargo_type . "," . $goods_desc. "," . "0" . "," .$res->quantity . "," . $res->length . "," . $res->width . "," . $res->height . "," . $res->weight . "," . $res->volume . "," . $volumetric_weight . "," . $res->stackable . "," . $res->grounded . "," . $res->splittable . "," . $res->dg_goods . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scanned_quantity . "," . $second_weight . "," . $secondweight_uom . "," . $second_volume . "," . $secondvolume_uom . "," . (!empty($qrcode) ? $qrcode : 0) . "," . $order_id . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='deleteordercargodetails(" . $res->id . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $res->id . ")'><span class='fa fa-archive' > </span>Get Inner Cargos</a></li>";
                        $action = "<button  class='btn btn-primary btn-xs editparties' onclick='rowcargoEdit(this, {$res->id}, {$cargo_type}, {$goods_desc}, 0, {$res->quantity}, {$res->length}, {$res->width}, {$res->height}, {$res->weight}, {$res->volume}, {$volumetric_weight}, {$res->stackable}, {$res->grounded}, {$res->splittable}, {$res->dg_goods}, {$length_unit}, {$width_unit}, {$height_unit}, {$weight_unit}, {$volume_unit}, {$volweight_uom}, {$ldm}, {$scanned_quantity}, {$second_weight}, {$secondweight_uom}, {$second_volume}, {$secondvolume_uom}, " . (!empty($qrcode) ? $qrcode : 0) . ", {$order_id})'
                                        <small>
                                                <i class='glyphicon glyphicon-pencil'></i>
                                        </small>
                                </button>   
                                <button class='btn btn-danger btn-xs deleteround' onclick= onclick='deleteordercargodetails({$res->id})'>
                                    <small>
                                        <i class='glyphicon glyphicon-trash'></i>
                                    </small>
                                </button>
  
                                <button class='btn btn-danger btn-xs deleteround' title='Get Inner Cargo' onclick='getinnercargo(this, {$res->id})'>
                                    <small>
                                        <i class='iconSvk icon-ordertype-icon'></i>
                                    </small>
                                </button>"; 
                    }

                    $recordListing[$i][0] = $action;
                    $recordListing[$i][1] = $res->cargo_type;
                    $recordListing[$i][2] = $res->goods_description;
                    $recordListing[$i][3] = $res->quantity;
                    $recordListing[$i][4] = $qrcode;
                    $recordListing[$i][5] = $scanned_quantity;
                    $recordListing[$i][6] = uom_string($res->length, $res->length_unit);
                    $recordListing[$i][7] = uom_string($res->width, $res->width_unit);
                    $recordListing[$i][8] = uom_string($res->height, $res->height_unit);
                    $recordListing[$i][9] = uom_string($res->weight, $res->weight_unit, 3);
                    $recordListing[$i][10] = uom_string($second_weight, $res->secondweight_uom);
                    $recordListing[$i][11] = uom_string($volumetric_weight, $res->volweight_uom);
                    $recordListing[$i][12] = uom_string($res->volume, $res->volume_unit);
                    $recordListing[$i][13] = uom_string($second_volume, $res->secondvolume_uom);
                    $recordListing[$i][14] = $ldm;
                    $recordListing[$i][15] = $stackable;
                    $recordListing[$i][16] = $grounded;
                    $recordListing[$i][17] = $splittable;
                    $recordListing[$i][18] =  $dg_goods;
                    $recordListing[$i][19] = $res->id;
                } elseif ($actionType == 'Edit' && $marksAndNumbersCondition) {
                    $marks_numbers    = '"' . $res->marks_numbers . '"';
                    $action = "<ul class='nav nav-tabs'><li class='dropdown tablebtnrleft '> <a class='dropdown-toggle' data-toggle='dropdown' href='#''><span class='icon  tru-icon-action-setting'></span></a><ul class='dropdown-menu' role='menu'>" . "<li><a data-ordertype='editOrder' id='bEdit' type='button' class='btn btn-sm btn-default'  onclick='rowcargoEdit(this," . $res->id . "," . $cargo_type . "," . $goods_desc. "," . $marks_numbers . "," . $res->quantity . "," . $res->length . "," . $res->width . "," . $res->height . "," . $res->weight . "," . $res->volume . "," . $volumetric_weight . "," . $res->stackable . "," . $res->grounded . "," . $res->splittable . "," . $res->dg_goods . "," . $length_unit . "," . $width_unit . "," . $height_unit . "," . $weight_unit . "," . $volume_unit . "," . $volweight_uom . "," . $ldm . "," . $scanned_quantity . "," . $second_weight . "," . $secondweight_uom . "," . $second_volume . "," . $secondvolume_uom . "," . (!empty($qrcode) ? $qrcode : 0) . "," . $order_id . ")'><span class='glyphicon glyphicon-pencil' ></span>Edit</a></li><li><a id='bElim' type='button' class='btn btn-sm btn-default' onclick='deleteordercargodetails(" . $res->id . ")'><span class='glyphicon glyphicon-trash' > </span>Remove</a></li><li><a id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok' > </span>Update</a></li><li><a id='bAdd' type='button' class='btn btn-sm btn-default' onclick='rowAdd(this);'><span class='glyphicon glyphicon-plus' > </span>Add Cargo Details</a></li><li><a id='innerpacking' type='button' class='btn btn-sm btn-default' onclick='getinnercargo(this," . $res->id . ")'><span class='fa fa-archive' > </span>Get Inner Cargos</a></li>";
                    $recordListing[$i][0] = $action;
                    $recordListing[$i][1] = $res->cargo_type;
                    $recordListing[$i][2] = $res->goods_description;
                    $recordListing[$i][3] = $res->marks_numbers;
                    $recordListing[$i][4] = $res->quantity;
                    $recordListing[$i][5] = $qrcode;
                    $recordListing[$i][6] = $scanned_quantity;
                    $recordListing[$i][7] = uom_string($res->length, $res->length_unit);
                    $recordListing[$i][8] = uom_string($res->width, $res->width_unit);
                    $recordListing[$i][9] = uom_string($res->height, $res->height_unit);
                    $recordListing[$i][10] = uom_string($res->weight, $res->weight_unit, 3);
                    $recordListing[$i][11] = uom_string($second_weight, $res->secondweight_uom);
                    $recordListing[$i][12] = uom_string($volumetric_weight, $res->volweight_uom);
                    $recordListing[$i][13] = uom_string($res->volume, $res->volume_unit);
                    $recordListing[$i][14] = uom_string($second_volume, $res->secondvolume_uom);
                    $recordListing[$i][15] = $ldm;
                    $recordListing[$i][16] = $stackable;
                    $recordListing[$i][17] = $grounded;
                    $recordListing[$i][18] = $splittable;
                    $recordListing[$i][19] =  $dg_goods;
                    $recordListing[$i][20] = $res->id;
                } elseif ($actionType != 'Edit' && $marksAndNumbersCondition) {
                    $recordListing[$i][0] = $res->cargo_type;
                    $recordListing[$i][1] = $res->goods_description;
                    $recordListing[$i][2] = $res->marks_numbers;
                    $recordListing[$i][3] = $res->quantity;
                    $recordListing[$i][4] = $qrcode;
                    $recordListing[$i][5] = $scanned_quantity;
                    $recordListing[$i][6] = uom_string($res->length, $res->length_unit);
                    $recordListing[$i][7] = uom_string($res->width, $res->width_unit);
                    $recordListing[$i][8] = uom_string($res->height, $res->height_unit);
                    $recordListing[$i][9] = uom_string($res->weight, $res->weight_unit, 3);
                    $recordListing[$i][10] = uom_string($second_weight, $res->secondweight_uom);
                    $recordListing[$i][11] = uom_string($volumetric_weight, $res->volweight_uom);
                    $recordListing[$i][12] = uom_string($res->volume, $res->volume_unit);
                    $recordListing[$i][13] = uom_string($second_volume, $res->secondvolume_uom);
                    $recordListing[$i][14] = $ldm;
                    $recordListing[$i][15] = $stackable;
                    $recordListing[$i][16] = $grounded;
                    $recordListing[$i][17] = $splittable;
                    $recordListing[$i][18] =  $dg_goods;
                    $recordListing[$i][19] = $res->id;
                } elseif ($companyCode == 'AUKN') {
                    $recordListing[$i][0] = $i + 1;
                    $recordListing[$i][1] = $res->cargo_type;
                    $recordListing[$i][2] = $res->goods_description;
                    $recordListing[$i][3] = $qrcode;
                    $recordListing[$i][4] = $res->quantity;
                    $recordListing[$i][5] = $scanned_quantity;
                    $recordListing[$i][6] = uom_string($res->length, $res->length_unit);
                    $recordListing[$i][7] = uom_string($res->width, $res->width_unit);
                    $recordListing[$i][8] = uom_string($res->height, $res->height_unit);
                    $recordListing[$i][9] = uom_string($res->weight, $res->weight_unit, 3);
                    $recordListing[$i][10] = uom_string($second_weight, $res->secondweight_uom);
                    $recordListing[$i][11] = uom_string($volumetric_weight, $res->volweight_uom);
                    $recordListing[$i][12] = uom_string($res->volume, $res->volume_unit);
                    $recordListing[$i][13] = uom_string($second_volume, $res->secondvolume_uom);
                    $recordListing[$i][14] = $ldm;
                    $recordListing[$i][15] = $label;
                    $recordListing[$i][16] = $stackable;
                    $recordListing[$i][17] = $grounded;
                    $recordListing[$i][18] = $splittable;
                    $recordListing[$i][19] = $dg_goods;
                    $recordListing[$i][20] = $res->id;
                    $recordListing[$i][21] = $res->bar_code;
                } else {
                    $recordListing[$i][0] = $res->cargo_type;
                    $recordListing[$i][1] = $res->goods_description;
                    $recordListing[$i][2] = $res->quantity;
                    $recordListing[$i][3] = $qrcode;
                    $recordListing[$i][4] = $scanned_quantity;
                    $recordListing[$i][5] = uom_string($res->length, $res->length_unit);
                    $recordListing[$i][6] = uom_string($res->width, $res->width_unit);
                    $recordListing[$i][7] = uom_string($res->height, $res->height_unit);
                    $recordListing[$i][8] = uom_string($res->weight, $res->weight_unit, 3);
                    $recordListing[$i][9] = uom_string($second_weight, $res->secondweight_uom);
                    $recordListing[$i][10] = uom_string($volumetric_weight, $res->volweight_uom);
                    $recordListing[$i][11] = uom_string($res->volume, $res->volume_unit);
                    $recordListing[$i][12] = uom_string($second_volume, $res->secondvolume_uom);
                    $recordListing[$i][13] = $ldm;
                    $recordListing[$i][14] = $stackable;
                    $recordListing[$i][15] = $grounded;
                    $recordListing[$i][16] = $splittable;
                    $recordListing[$i][17] = $dg_goods;
                    $recordListing[$i][18] = $res->id;
                }
                $i++;
                $srNumber++;
            }

            $final_data = json_encode( $recordListing );
        } else {
            $final_data = '[]';
        }
        echo '{"draw":' . $draw . ',"recordsTotal":' . $recordsFiltered . ',"recordsFiltered":' . $recordsFiltered . ',"data":' . $final_data . '}';
    }



    public function spotonlr($order_id=""){

        if(isset($order_id) && strlen($order_id)>0){
            $orders = $this->db->where(array("id"=>$order_id))->get("tb_orders");
            if($orders->num_rows() > 0){
                $branch_code = $this->session->userdata("branch_code");
                $user_id = $this->session->userdata("user_id");
                $data["order"] = $order = $orders->row();
                $data["pickup"] = $order->pickup_company.", ".$order->pickup_address1.", ".$order->pickup_city.", ".$order->pickup_country.", ".$order->pickup_pincode;
                $data["delivery"] = $order->delivery_company.", ".$order->delivery_address1.", ".$order->delivery_city.", ".$order->delivery_country.", ".$order->delivery_pincode;

                $dwhr=" id = '".$order->drop_custid."' OR code = '".$order->drop_custid."' OR customeridentifier = '".$order->drop_custid."' ";
                $consignees = $this->common->gettblrowdata( $dwhr," id,name,street,location_id,state,address,country,pincode","tbl_party_master",0,0);


                if(!empty($consignees)){
                    $data["consignee"] = $consignees;
                    $consignee_address=$consignees['address'];
                    if($consignees['address'] = '' || $consignees['address'] = ' ' ){
                        $consignee_address=	$consignees['street'].','.$consignees['location_id'].','.$consignees['state'].','.$consignees['pincode'];
                    }else{
                        $consignee_address=$consignees['address'].','.$consignees['pincode'];
                    }

                }

                $consignors = $this->common->gettblrowdata( array('id' =>$order->customer_id  )," partner_id,name,address,pincode","tb_customers",0,0);

                if(!empty($consignors)){
                    $data["consignor"] = $consignors;
                }

                $data["user"] = $this->common->gettblrowdata(  array('id' =>$user_id)," name,domain_name,head_office,gstin","tb_users",0,0);
                $consigneegst='';
                $conwhr="partner_id = ".$consignees['id']." and gstin is not null and gstin !='' ";
                $congst = $this->common->gettblrowdata( $conwhr,"GROUP_CONCAT(gstin) as gst","tb_party_reference",0,0);
                if(!empty($congst)){
                    $consigneegst = $congst['gst'];
                }

                $consignorgst='';
                $cuswhr="partner_id = ".$consignors['partner_id']." and gstin is not null and gstin !='' ";
                $cusgst = $this->common->gettblrowdata( $cuswhr,"GROUP_CONCAT(gstin) as gst","tb_party_reference",0,0);
                if(!empty($cusgst)){
                    $consignorgst = $cusgst['gst'];
                }

                $docs_data = [];
                $docs_data["order_id"] = $order_id;
                $docs_data_records = $this->db->select("metadata")->where($docs_data)->get("tb_docs_data");
                if($docs_data_records->num_rows()>0){
                    $data["doc_data"] = json_decode($docs_data_records->row()->metadata);
                }
                $data["qr"] = $this->db->query("SELECT qr.path FROM tb_order_cargodetails cd,tb_order_cargo_qrdetails qr WHERE cd.order_id='$order_id' AND qr.order_cargo_details_id = cd.id AND cd.status='1' AND qr.status='1'");

                $data["spoton"] = $this->common->gettblrowdata(  array('order_rowid' =>$order_id),"con_num","tb_getcon_response",0,0);

                $kn_ref = $this->common->gettblrowdata(  array('reference_id' =>'ELR', 'order_id' => $order_id ),"ref_value","tb_order_references",0,0);

                $data['generator'] = new Picqer\Barcode\BarcodeGeneratorPNG();


                $data_arr=array(
                    'head_office' =>$data["user"]['head_office'],
                    'gstin' =>$data["user"]['gstin'],
                    'origin' =>$order->pickup_city,
                    'destination' =>$order->delivery_city,
                    'date' =>date('Y-m-d g:i a', strtotime($order->createdon)),
                    'order_id'=> $order->order_id,
                    'con_num'=> $data["spoton"]['con_num'],
                    'surface'=>$order->transport_mode,
                    'consignor'=> $consignors['name'],
                    'consignee'=>$consignees['name'],
                    'consignor_address'=>$consignors['address'].','.$consignors['pincode'],
                    'consignee_address'=>$consignee_address,
                    'weight'=>$order->weight,
                    'volumetric_weight'=>$order->volume,
                    'quantity'=>  ceil($order->quantity),
                    'consignor_gst'=>$consignorgst,
                    'consignee_gst'=>$consigneegst,
                    'qr'=>$data["qr"],
                    'kn_ref'=>$kn_ref['ref_value'],
                );

                // document_copy_type
                // kn_ref

                $doc_type_arr= array('0' => array('doc_type' =>'LSP Copy','doc_name'=>'Service_Provider','stamp'=>'RECEIVER SIGN & STAMP'),'1' => array('doc_type' =>'Accounts Copy','doc_name'=>'Accounts','stamp'=>'RECEIVER SIGN & STAMP'),'2' => array('doc_type' =>'Consignee Copy','doc_name'=>'Consignee','stamp'=>'RECEIVER SIGN & STAMP'),'3' => array('doc_type' =>'Consignor Copy','doc_name'=>'Consignor','stamp'=>'RECEIVER SIGN & STAMP'),'4' => array('doc_type' =>'Acknowledgement Copy','doc_name'=>'Acknowledgement','stamp'=>'Acknowledgement Area') );

                foreach ( $doc_type_arr as  $dtype) {
                    $data_arr['document_copy_type']=$dtype['doc_type'];
                    $data_arr['stamp']=$dtype['stamp'];
                    $dtype['doc_type'];
                    $pdf = new \Mpdf\Mpdf(['mode' => 'utf-8','tempDir' => FCPATH .'assets/tmp']);
                    $file_name = "KNLR-LTL-".$dtype['doc_name'].'-'.$order->order_id."_".date("Ymd");
                    $file_path = "./assets/poduploads/".$file_name;
                    $pdf_path = $file_path.".pdf";
                    $html = $this->load->view('lr_spoton_report_print',$data_arr,true);
                    $pdf->AddPage('L', // L - landscape, P - portrait
                        '', '', '', '',
                        8, // margin_left
                        8, // margin right
                        8, // margin top
                        8, // margin bottom
                        8, // margin header
                        8);
                    $pdf->WriteHTML($html);
                    $pdf->Output($pdf_path,'F');

                    # code...
                }
                $resp = 1;
            }
        }

        return $resp;

    }
    
    public function download($filename){
        $this->load->helper('download');
        $file = 'assets/poduploads/'.$filename;
        force_download($file, NULL);
    }

    public function mudhitaediservices($order_row_id){
        $this->load->model( 'truckwaybillmodel' );
        $access_token_request_url = MUDITA_ACCESS_TOKEN_URL.'?grant_type=refresh_token&refresh_token='.MUDITA_REFRESH_TOKEN.'&client_id='.MUDITA_CLIENT_ID.'&client_secret='.MUDITA_CLIENT_SECRET;
        $token = mudita_requestaccesstoken($access_token_request_url);
        if(isset($token['access_token'])){
            $access_token    = $token['access_token'];
            $response        = $postresponse = "no data";
            $requestinfo     = $req_in_arr   = array();
            $where           = array( "id" => $order_row_id );
            $select          = "order_id,transport_mode,weight,delivery_city,pickup_city,pickup_address1,pickup_address2,delivery_address1,delivery_address2,pickup_datetime,pickup_pincode,delivery_pincode,shipment_id,customer_id";
            $table           = "tb_orders";
            $order           = $this->common->gettblrowdata( $where, $select, $table, 0, 0 );
            $user_id         = $this->session->userdata( 'user_id' );
            $company_code    = $this->session->userdata( 'company_code' );
            $branch_code     = $this->session->userdata( 'branch_code' );
            $reference_val   = '';
            $where           = array( "order_id" => $order_row_id );
            $select          = "length,width,height,quantity";
            $table           = "tb_order_cargodetails";
            $dimensions      = array();
            $order_cargo     = $this->common->gettbldata( $where, $select, $table, 0, 0 );
            $pickupinfo      = $this->truckwaybillmodel->getshipper( $order_row_id, 'Shipper' );
            $receiverinfo    = $this->truckwaybillmodel->getshipper( $order_row_id, 'Consignee' );
            $customer_codes = $this->common->gettblrowdata( array( "customer_id" => $order['customer_id'] ), '*', 'tb_carrier_api_customer_codes', 0, 0 );
            $raddress        = $receiverinfo['address'];
            if($receiverinfo['address'] == ''){
                $raddress= $receiverinfo['street'].','.$receiverinfo['location_id'];
            }
            $order_number    = $order['order_id'];
            $order_reference = $this->truckwaybillmodel->orderrefernce( $order_number );
            if ( count( $order_reference ) > 0 ) {
                foreach ( $order_reference as $res ) {
                    $reference_val = $res['ref_value'] . ",";
                }
            }
            $reference_val  = trim( $reference_val, "," );
            $total_packages = 0;
            if ( count( $order_cargo ) > 0 ) {
                foreach ( $order_cargo as $info ) {
                    $dimensions[]   = [
                        'Length' => round(floatval($info['length'])),
                        'Breadth' => round(floatval($info['width'])),
                        'height' => round(floatval($info['height'])),
                        'Pieces' => round(floatval($info['quantity']))
                    ];
                    $total_packages = $total_packages + $info['quantity'];
                }
            }
            if($order['transport_mode'] == 'FTL' || $order['transport_mode'] == 'LTL' || $order['transport_mode'] == 'FCL' || $order['transport_mode'] == 'LCL'){
                $mode = 'Road';
            }else{
                $mode = 'Air';
            }
            $picklocationname = isset( $pickupinfo['location_id'] ) ? $pickupinfo['location_id'] : $order['pickup_city'];
            $pickpincode     = isset( $pickupinfo['pincode'] ) ? $pickupinfo['pincode'] : "";
            $pickaddress     = isset( $pickupinfo['address'] ) ? $pickupinfo['address'] : $pickupinfo['street'].$pickupinfo['location_id'];
            $deladdress      = isset( $receiverinfo['address'] ) ? $receiverinfo['address'] : $receiverinfo['street'].$receiverinfo['location_id'];
            $pickname        = isset( $pickupinfo['name'] ) ? $pickupinfo['name'] : "";
            $pickmobile      = isset( $pickupinfo['mobile'] ) ? $pickupinfo['mobile'] : "01140576384";
            $pickemail       = isset( $pickupinfo['email'] ) ? $pickupinfo['email'] : "customerservice@muditacargo.com";
            $delname         = isset( $receiverinfo['name'] ) ? $receiverinfo['name'] : "";
            $delmobile       = isset( $receiverinfo['mobile'] ) ? $receiverinfo['mobile'] : "01140576384";
            $delemail        = isset( $receiverinfo['email'] ) ? $receiverinfo['email'] : "customerservice@muditacargo.com";
            $pickup_datetime = date( "d-M-Y", strtotime( $order['pickup_datetime'] ) );
            $requestinfo['Date_of_Pickup']     		= isset($pickup_datetime) ? $pickup_datetime : '';
            $requestinfo['Pickup_Slot'] 	   		= '';
            $requestinfo['Customer_Account'] 		= $customer_codes['customer_code'];
            $requestinfo['Pickup_Address_Line_1']   = isset($pickaddress) ? $pickaddress : '';
            $requestinfo['Pickup_Address_Line_2'] 	= $order['pickup_address2'];
            $requestinfo['Pickup_Address_Line_3'] 	= '';
            $requestinfo['Pickup_City_Town']      	= isset($order['pickup_city']) ? $order['pickup_city'] : '';
            $requestinfo['Pickup_Pin_Code']       	= isset($pickpincode) ? substr( $pickpincode, 0, 6 ) : '';
            $requestinfo['Pickup_State'] 			= isset( $pickupinfo['state']) ?  str_replace(" And "," and ",ucwords(strtolower($pickupinfo['state']))) : '';
            $requestinfo['Pickup_Contact_Person'] 	= isset($pickname) ? $pickname : '';
            $requestinfo['Pickup_Contact_Number'] 	= isset($pickmobile) ? $pickmobile : '01140576384';
            $requestinfo['Pickup_Email_ID']  		= isset($pickemail) ? $pickemail : 'customerservice@muditacargo.com';
            $requestinfo['Pickup_Store_Code']  		= '';
            $requestinfo['Delivery_Address_Line_1'] = isset($order['delivery_address1']) ? $order['delivery_address1'] : '';
            $requestinfo['Delivery_Address_Line_2'] = isset($order['delivery_address2']) ? $order['delivery_address2'] : '';
            $requestinfo['Delivery_Address_Line_3'] = '';
            $requestinfo['Delivery_City_Town']      = isset($order['delivery_city']) ? $order['delivery_city'] : '';
            $requestinfo['Delivery_Pin_Code'] 		= isset($receiverinfo['pincode']) ? substr( $receiverinfo['pincode'], 0, 6 ) : '';
            $requestinfo['Delivery_State'] 			= isset($receiverinfo['state']) ?  str_replace(" And "," and ",ucwords(strtolower($receiverinfo['state']))) : '';
            $requestinfo['Delivery_Contact_Person'] = isset($delname) ? $delname : '';
            $requestinfo['Delivery_Contact_Number'] = isset($delmobile) ? $delmobile : '01140576384';
            $requestinfo['Delivery_Email_ID']       = isset($delemail) ? $delemail : 'customerservice@muditacargo.com';
            $requestinfo['Delivery_Store_Code'] 	= '';
            $requestinfo['Number_of_Boxes']         = isset($total_packages) ? $total_packages : '';
            $requestinfo['Box_Dimensions']          = isset($dimensions) ? $dimensions : '';
            $requestinfo['Commodity']        		= '';
            $requestinfo['Expected_Weight_in_Kg']   = isset($order['weight']) ? round(floatval($order['weight'])) : 0;
            $requestinfo['Invoice_Number']   		= '0';
            $requestinfo['Invoice_Value_Rs']        = '';
            $requestinfo['EwayBill_Number']         = '';
            $requestinfo['Mode']               		= isset($mode) ? $mode : '';
            $requestinfo['Special_Information']    	= 'On time';
            if( SYS_TYPE == 'TMS'){
                $requestinfo['Type']               	= 'API';
            }else{
                $requestinfo['Type']               	= 'Test API';
            }
            $requestinfo['Shipment_ID']       		= isset($order['shipment_id']) ? $order['shipment_id'] : '';
            $requestinfo['API_Details'] 			= '';
            $reqdata_new = '{"data":'.json_encode($requestinfo).'}';
            $reqdata_new = str_replace('\"','',$reqdata_new);

            $headers      = array(
                'Authorization: Zoho-oauthtoken ' . $access_token
            );
            $response = thirdpartyservicecurl( MUDITA_PICKUP_REQUEST_FORM, $headers, $reqdata_new );
            $reqdata = "format=json&data=".json_encode($requestinfo);
            $reqdata=str_replace('\"','',$reqdata);
            $edi_request = $reqdata;
            $edi_response = $response;
            $edi_id = '22';
            $status = 0;
            $edi_name = "Mudita";
            $params = array('edi_type' => 1,
                'transaction_id' => time(),
                'edi_id' => $edi_id,
                'edi_name' => $edi_name,
                'bounded_type' => 2,
                'edi_format_type' => 'json', 'status' => $status, 'obj_type' => 1, 'txn_obj_id' => $order_row_id,'user_id' => $user_id, 'company_code' => $company_code, 'branch_code' => $branch_code,'edi_request' => $edi_request, 'edi_response' => json_encode($edi_response));
            $edilogid = $this->db->insert('tb_etn_edi_transactions', $params);
            if(isset($response['data']['ID'])){
                $ins_ar = array(
                    'order_id'     => $order_row_id,
                    'reference_id' => 'BN',
                    'ref_value'    => $response['data']['ID'],
                    'status'       => 1,
                    'createdon'    =>date('Y-m-d H:i:s'),
                );
                $chkqry = $this->db->select( 'id' )->get_where( "tb_order_references", array( 'order_id' => $order_row_id, 'reference_id' => 'BN', 'ref_value' => $response['data']['ID'] ) );
                if ( $chkqry->num_rows() == 0 ) {
                    $ins = $this->db->insert( 'tb_order_references', $ins_ar );
                }
                $chkqry = $this->db->query("SELECT reference_id, ref_value FROM `tb_order_references` WHERE `reference_id` = 'ELR' ORDER BY `id` DESC LIMIT 1")->result();
                $ins_arr = array(
                    'order_id'     => $order_row_id,
                    'reference_id' => 'ELR',
                    'createdon'    => date('Y-m-d H:i:s'),
                    'status'       => 1
                );
                if(count($chkqry) == 0){
                    $ins_arr['ref_value'] = 'SVK'.$order['transport_mode'].'000001';
                    $ins = $this->db->insert( 'tb_order_references', $ins_arr );
                }else{
                    $val = sprintf('%06s', substr($chkqry[0]->ref_value,-6) + 1);
                    $ins_arr['ref_value'] = 'SVK'.$order['transport_mode'].$val;
                    $ins = $this->db->insert( 'tb_order_references', $ins_arr );
                }
                $lr_gen=$this->muditalr($order_row_id);
            }
        }else{
            log_message( 'error', " orders >> mudhitaediservices >> Access Token " .$token['error'] );
        }
    }
    
    public function muditalr($order_id=""){
        $resp = 0;
        if(isset($order_id) && strlen($order_id)>0){
            $orders = $this->db->where(array("id"=>$order_id))->get("tb_orders");
            if($orders->num_rows() > 0){
                $user_id = $this->session->userdata("user_id");
                $data["order"] = $order = $orders->row();
                $data["pickup"] = $order->pickup_company.", ".$order->pickup_address1.", ".$order->pickup_city.", ".$order->pickup_country.", ".$order->pickup_pincode;
                $data["delivery"] = $order->delivery_company.", ".$order->delivery_address1.", ".$order->delivery_city.", ".$order->delivery_country.", ".$order->delivery_pincode;
                $dwhr=" id = '".$order->drop_custid."' OR code = '".$order->drop_custid."' OR customeridentifier = '".$order->drop_custid."' ";
                $consignees = $this->common->gettblrowdata( $dwhr," id,name,street,location_id,state,address,country,pincode","tbl_party_master",0,0);
                if(!empty($consignees)){
                    $data["consignee"] = $consignees;
                    $consignee_address=$consignees['address'];
                    if(trim($consignees['address']) == ''  ){
                        $consignee_address=	$consignees['street'].','.$consignees['location_id'].','.$consignees['state'].','.$consignees['pincode'];
                    }else{
                        $consignee_address=$consignees['address'].','.$consignees['pincode'];
                    }
                }
                $consignors = $this->common->gettblrowdata( array('id' =>$order->customer_id  )," partner_id,name,address,pincode","tb_customers",0,0);
                if(!empty($consignors)){
                    $data["consignor"] = $consignors;
                }
                $data["user"] = $this->common->gettblrowdata(  array('id' =>$user_id)," name,domain_name,head_office,gstin","tb_users",0,0);
                $consigneegst='';
                $conwhr="partner_id = ".$consignees['id']." and gstin is not null and gstin !='' ";
                $congst = $this->common->gettblrowdata( $conwhr,"GROUP_CONCAT(gstin) as gst","tb_party_reference",0,0);
                if(!empty($congst)){
                    $consigneegst = $congst['gst'];
                }
                $consignorgst='';
                $cuswhr="partner_id = ".$consignors['partner_id']." and gstin is not null and gstin !='' ";
                $cusgst = $this->common->gettblrowdata( $cuswhr,"GROUP_CONCAT(gstin) as gst","tb_party_reference",0,0);
                if(!empty($cusgst)){
                    $consignorgst = $cusgst['gst'];
                }
                $docs_data = [];
                $docs_data["order_id"] = $order_id;
                $docs_data_records = $this->db->select("metadata")->where($docs_data)->get("tb_docs_data");
                if($docs_data_records->num_rows()>0){
                    $data["doc_data"] = json_decode($docs_data_records->row()->metadata);
                }
                $data["qr"] = $this->db->query("SELECT qr.path FROM tb_order_cargodetails cd,tb_order_cargo_qrdetails qr WHERE cd.order_id='$order_id' AND qr.order_cargo_details_id = cd.id AND cd.status='1' AND qr.status='1'");
                $kn_ref = $this->common->gettblrowdata(  array('reference_id' =>'ELR', 'order_id' => $order_id ),"ref_value","tb_order_references",0,0);
                $midita_ref = $this->common->gettblrowdata(  array('reference_id' =>'BN', 'order_id' => $order_id ),"ref_value","tb_order_references",0,0);
                $data['generator'] = new Picqer\Barcode\BarcodeGeneratorPNG();
                $data_arr=array(
                    'head_office' =>$data["user"]['head_office'],
                    'gstin' =>$data["user"]['gstin'],
                    'origin' =>$order->pickup_city,
                    'destination' =>$order->delivery_city,
                    'date' =>date('Y-m-d g:i a', strtotime($order->createdon)),
                    'order_id'=> $order->order_id,
                    'con_num'=> $midita_ref['ref_value'],
                    'surface'=>$order->transport_mode,
                    'consignor'=> $consignors['name'],
                    'consignee'=>$consignees['name'],
                    'consignor_address'=>$consignors['address'].','.$consignors['pincode'],
                    'consignee_address'=>$consignee_address,
                    'weight'=>$order->weight,
                    'volumetric_weight'=>$order->volume,
                    'quantity'=>  ceil($order->quantity),
                    'consignor_gst'=>$consignorgst,
                    'consignee_gst'=>$consigneegst,
                    'qr'=>$data["qr"],
                    'kn_ref'=>$kn_ref['ref_value'],
                );
                $doc_type_arr= array('0' => array('doc_type' =>'LSP Copy','doc_name'=>'Service_Provider','stamp'=>'RECEIVER SIGN & STAMP'),'1' => array('doc_type' =>'Accounts Copy','doc_name'=>'Accounts','stamp'=>'RECEIVER SIGN & STAMP'),'2' => array('doc_type' =>'Consignee Copy','doc_name'=>'Consignee','stamp'=>'RECEIVER SIGN & STAMP'),'3' => array('doc_type' =>'Consignor Copy','doc_name'=>'Consignor','stamp'=>'RECEIVER SIGN & STAMP'),'4' => array('doc_type' =>'Acknowledgement Copy','doc_name'=>'Acknowledgement','stamp'=>'Acknowledgement Area') );
                foreach ( $doc_type_arr as  $dtype) {
                    $data_arr['document_copy_type']=$dtype['doc_type'];
                    $data_arr['stamp']=$dtype['stamp'];
                    $dtype['doc_type'];
                    $pdf = new \Mpdf\Mpdf(['mode' => 'utf-8','tempDir' => FCPATH .'assets/tmp']);
                    $file_name = "KNLR-LTL-".$dtype['doc_name'].'-'.$order->order_id."_".date("Ymd");
                    $file_path = "./assets/poduploads/".$file_name;
                    $pdf_path = $file_path.".pdf";
                    $html = $this->load->view('lr_spoton_report_print',$data_arr,true);
                    $pdf->AddPage('L', // L - landscape, P - portrait
                        '', '', '', '',
                        8, // margin_left
                        8, // margin right
                        8, // margin top
                        8, // margin bottom
                        8, // margin header
                        8);
                    $pdf->WriteHTML($html);
                    $pdf->Output($pdf_path,'F');
                }
                $resp = 1;
            }
        }
        return $resp;
    }

    public function deleteorders(): void
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $ids = $this->input->post('deleteids');
            $billedOrderIds = [];
            $sql = "SELECT GROUP_CONCAT(order_id) as order_ids from tb_reveneus WHERE order_id IN ? AND bill_id > ? AND status = ?";
            $getBilledOrderIds = $this->db->query($sql, [$ids, 0, 1]);
            if ($getBilledOrderIds->num_rows() > 0) {
                $billedOrderIds = explode(',', $getBilledOrderIds->row()->order_ids);
            }
            $tables = [
                ['name' => 'tb_orders', 'column' => 'id'],
                ['name' => 'tb_order_details', 'column' => 'order_row_id'],
                ['name' => 'tb_order_parties', 'column' => 'order_id'],
                ['name' => 'tbl_orderparty_address', 'column' => 'order_id'],
                ['name' => 'tb_order_cargodetails', 'column' => 'order_id'],
                ['name' => 'tb_order_addons', 'column' => 'order_id'],
                ['name' => 'tb_order_references', 'column' => 'order_id'],
                ['name' => 'tb_reveneus', 'column' => 'order_id']
            ];
            $result = true;
            foreach ($tables as $table) {
                foreach ($ids as $id) {
                    if (!in_array($id, $billedOrderIds)) {
                        $data = $this->db->update($table['name'], ['status' => 0], [$table['column'] => $id]);
                        if (!$data) {
                            $result = false;
                        }
                    }
                }
            }
            echo $result ? "success" : "failed";
        }
    }

    private function getPartyRefereces(string $custdid): array
    {
        $pickup_custid =$custdid;
        $pickup = $this->common->gettblrowdata(["code" => $pickup_custid], "mobile,email,id", "tbl_party_master", 0, 0);
        $sourceID=$pickup['id'];
        $sourceReferences = $this->common->gettbldata(["partner_id" => $sourceID], "*", "tb_party_reference", 0, 0);
        return $sourceReferences;
    }
    
    public function viewInnerCargo()
    {
        $cargoId = $this->input->get('cargo_id');
        $getInnerCargo = $this->db->query("SELECT ic.cargo_type,ic.quantity, ic.weight, ic.volume, ic.length, ic.width, ic.height, ic.goods_description 
                                   FROM tb_inner_cargo ic
                                   WHERE ic.status = ? AND ic.cargo_id = ?", [1, $cargoId]);
        if ($getInnerCargo->num_rows() > 0) {
            $data['innercargo'] = $getInnerCargo->result();
            echo json_encode($data);
        }else { echo json_encode([]); }
    }
    
    public function maproute()
    {
        $sid  = $this->input->post('order_id');
        $response['stops'] = [];
        if ($sid != "") {
            $where = ["id" => $sid];
            $table = "tb_orders";
            $stops = $this->db->select("pickup_city,delivery_city,plat,plng,dlat,dlng")->get_where($table, $where);
            if ($stops->num_rows() > 0) {
                $orderData = $stops->result_array();               
                $response['stops'] = [ 
                    [
                        'stopname'=> $orderData[0]['pickup_city'],
                        'plat' =>  $orderData[0]['plat'],
                        'plng' =>  $orderData[0]['plng'],
                    ],[
                        'stopname'=> $orderData[0]['delivery_city'],
                        'plat' =>  $orderData[0]['dlat'],
                        'plng' =>  $orderData[0]['dlng'],
                    ]                   
                ];             
            }
        }
        echo $this->load->view("orders/map_order_route", $response, true);
    }
    
    public function getCarrierListID()
    {
        $parties      = [];
        $user_id      = $this->session->userdata('user_id');
        $company_code = $this->session->userdata('company_code');
        $permission   = checkuserpermissions();
        
        if (in_array("businesspartners", $permission)) {
            $whr = " AND v.company_code LIKE '" . $company_code . "' ";
        } else {
            $whr = " AND v.user_id ='" . $user_id . "' ";
        }
        
        $sql = "SELECT v.id,v.name,v.mobile,v.code,v.country,v.location as city,v.address,v.email,v.company_code,v.branch_code
                FROM tb_vendors v
                WHERE  v.status ='1' AND  v.company_code != '' AND v.company_code IS NOT NULL " . $whr . "
                GROUP BY v.id
                ORDER BY v.created_on DESC";
        $chkqry = $this->db->query($sql);
        if ($chkqry->num_rows() > 0) {
            foreach ($chkqry->result() as $res) {
                $parties[] = [
                     'check'        => "<input class='carrierlist' type='radio' name='selectcarrier' id='carrierlist_" . $res->id . "' value='" . $res->id . "' onchange=selectcarrier(" . $res->id . ")>",
                    'id'           => $res->id,
                    'party_id'     => $res->code,
                    'name'         => $res->name,
                    'phone'        => $res->mobile,
                    'email'        => wordwrap($res->email, 25, "<br />\n"),
                    'company_code' => $res->company_code,
                    'branch_code'  => $res->branch_code,
                    'city'         => $res->city,
                    'country'      => $res->country,
                ];
            }
        }
        echo json_encode($parties);
    }
    public function getcarrierdetailsbyID()
    {
        $parties      = [];
        $code         = $this->input->post('id');
        $customer_id  = "";
        $user_id      = $this->session->userdata('user_id');
        $company_code = $this->session->userdata('company_code');
        $permission = checkuserpermissions();
        if (in_array("businesspartners", $permission)) {
            $chk_vendors = $this->common->gettblrowdata(['id' => $code, 'company_code' => $company_code, 'status' => '1'], "id,name,mobile,location,address,pincode,code,country,email,company_code,branch_code", "tb_vendors", 0, 0);
        } else {
            $chk_vendors = $this->common->gettblrowdata(['id' => $code, 'user_id' => $user_id, 'status' => '1'], "id,name,mobile,location,address,pincode,code,country,email,company_code,branch_code", "tb_vendors", 0, 0);
        }
        if (! empty($chk_vendors)) {
            $vendor_id                   = $chk_vendors['id'];
            $parties['vendor_details'][] = [
                     'check'        => "<input class='carrierlist' type='radio' name='selectcarrier' id='carrierlist_" . $chk_vendors['id'] . "' value='" . $chk_vendors['code'] . "' onchange=selectcarrier(" . $chk_vendors['id'] . ")>",
                'id'           => $chk_vendors['id'],
                'name'         => $chk_vendors['name'],
                'code'         => $chk_vendors['code'],
                'phone'        => $chk_vendors['mobile'],
                'city'         => $chk_vendors['location'],
                'country'      => $chk_vendors['country'],
                'email_id'     => $chk_vendors['email'],
                'company_code' => $chk_vendors['company_code'],
                'branch_code'  => $chk_vendors['branch_code'],
            ];
            
        }
        echo json_encode($parties);
    }
    
    public function saveIndent()
    {
        log_message("error","Save POST:".json_encode($_POST));
        $cdate                = date('Y-m-d H:i:s');
        $currentdate          = date('d-m-Y');
        $user_id              = $this->session->userdata('user_id');
        $cust_id              = $this->session->userdata('cust_id');
        $company_code         = isset($_POST['popupcompany_code']) ? $this->db->escape_str($_POST['popupcompany_code']) : "";
        $branch_code          = isset($_POST['popupbranch_code']) ? $this->db->escape_str($_POST['popupbranch_code']) : "";
        $department_code      = isset($_POST['popupdepartment_code']) ? $this->db->escape_str($_POST['popupdepartment_code']) : "";
        $product              = isset($_POST['productpopup']) ? $this->db->escape_str($_POST['productpopup']) : "";
        $service              = isset($_POST['servicepopup']) ? $this->db->escape_str($_POST['servicepopup']) : "";
        $delivery_terms       = isset($_POST['popupdelivery_terms']) ? $this->db->escape_str($_POST['popupdelivery_terms']) : "";
        $incoterm             = isset($_POST['incoterm_popup']) ? $this->db->escape_str($_POST['incoterm_popup']) : "";
        $shipment_id          = isset($_POST['customerRef']) ? $this->db->escape_str($_POST['customerRef']) : "";
        $carrierRef          = isset($_POST['carrierRef']) ? $this->db->escape_str($_POST['carrierRef']) : "";
        $porder               = isset($_POST['purchaseorder_popup']) ? $this->db->escape_str($_POST['purchaseorder_popup']) : "";
        $notify_party         = isset($_POST['popupnotifyparty']) ? $this->db->escape_str($_POST['popupnotifyparty']) : "";
        $popuppickup          = isset($_POST['popuppickup']) ? $this->db->escape_str($_POST['popuppickup']) : "";
        $popupdelivery        = isset($_POST['popupdelivery']) ? $this->db->escape_str($_POST['popupdelivery']) : "";
        $customer_phone       = isset($_POST['popupshipper_phone']) ? $this->db->escape_str($_POST['popupshipper_phone']) : "";
        $customer_email       = isset($_POST['popupshipper_email']) ? $this->db->escape_str($_POST['popupshipper_email']) : "";
        $popupcustomer_id     = isset($_POST['indentpopupcustomer_id']) ? $this->db->escape_str($_POST['indentpopupcustomer_id']) : "";
        $driverdelivery_popup = isset($_POST['driverdelivery_popup']) ? $this->db->escape_str($_POST['driverdelivery_popup']) : "";
        $driverpickup_popup   = isset($_POST['driverpickup_popup']) ? $this->db->escape_str($_POST['driverpickup_popup']) : "";
        $carrierId          = isset($_POST['indentcarrier_id']) ? $this->db->escape_str($_POST['indentcarrier_id']) : "";
        $currency    = isset($_POST['currency']) ? $this->db->escape_str($_POST['currency']) : "";
        $goods_value = isset($_POST['goods_value']) ? $this->db->escape_str($_POST['goods_value']) : "0.00";
        /*if($_POST['indentpopupcarrier_id'] == "6098765789"){
            $authDetails = $this->db->common->gettblrowdata(['token_for' => 'FLIPKART', 'status' => 1], "auth_token", "tb_auth_tokens", 0, 0);
            log_message('error', "cURL Request URL:" . json_encode($authDetails));
            $authToken = $authDetails['auth_token'];
        }*/

        $earlyquickbook_delivery = $latequickbook_delivery = "";
        if ($popupdelivery != "") {
            $earlyquickbook_delivery = date('Y-m-d H:i:s', strtotime($popupdelivery));
            $latequickbook_delivery  = date('Y-m-d H:i:s', strtotime('+1 hour', strtotime($earlyquickbook_delivery)));
        }
        $earlyquickbook_pickup = $latequickbook_pickup = "";
        if ($popuppickup != "") {
            $earlyquickbook_pickup = date('Y-m-d H:i:s', strtotime($popuppickup));
            $latequickbook_pickup  = date('Y-m-d H:i:s', strtotime('+1 hour', strtotime($earlyquickbook_pickup)));
        }
        $popuporder_type       = isset($_POST['popuporder_type']) ? $this->db->escape_str($_POST['popuporder_type']) : "";
        $popupmodeof_trasnport = isset($_POST['popupmodeof_trasnport']) ? $this->db->escape_str($_POST['popupmodeof_trasnport']) : "LTL";

        $reference_ids                 = isset($_POST['quickbookreference_ids']) ? $this->db->escape_str($_POST['quickbookreference_ids']) : "0";
        $quickbook_order_reference_ids = isset($_POST['quickbook_order_reference_ids']) ? $this->db->escape_str($_POST['quickbook_order_reference_ids']) : "0";
        // $order_cargo_id                = isset($_POST['quickbookorder_cargo_id']) ? $this->db->escape_str($_POST['quickbookorder_cargo_id']) : "";
        $inv_parties                   = [$_POST['indentshipper_id'], $_POST['indentconsignee_id']];
        $pickup                        = isset($_POST['indentpickup_id']) ? $this->db->escape_str($_POST['indentpickup_id']) : "0";
        if ($pickup == "") {
            $pickup = 0;
        }
        $delivery       = $this->db->escape_str($_POST['indentconsignee_id']);
        
        $drop_id        = $pickup_custid        = 0;
        $pickup_name    = $pickup_country    = $pickup_street    = $pickup_state    = $drop_state    = $pickup_pincode    = $pickup_city    = $drop_name    = $drop_country    = $drop_street    = $drop_pincode    = $drop_city    = $drop_latitude    = $drop_longitude    = $pickup_latitude    = $pickup_longitude    = "";
        $getdrop_custid = $this->db->query("SELECT name,country,state,street,customeridentifier,pincode,location_id as city,latitude,longitude FROM tbl_party_master WHERE id='" . $delivery . "'");
        
        if ($getdrop_custid->num_rows() > 0) {
            $drop_id        = $getdrop_custid->row()->customeridentifier;
            $drop_name      = $getdrop_custid->row()->name;
            $drop_country   = $getdrop_custid->row()->country;
            $drop_state     = $getdrop_custid->row()->state;
            $drop_street    = $getdrop_custid->row()->street;
            $drop_pincode   = $getdrop_custid->row()->pincode;
            $drop_city      = $getdrop_custid->row()->city;
            $drop_latitude  = $getdrop_custid->row()->latitude;
            $drop_longitude = $getdrop_custid->row()->longitude;
        }
        $getshippercustid = $this->db->query("SELECT name,country,state,street,customeridentifier,pincode,location_id as city,latitude,longitude FROM tbl_party_master WHERE id='" . $_POST['indentshipper_id'] . "'");
        
        if ($getshippercustid->num_rows() > 0) {
            $pickup_custid    = $getshippercustid->row()->customeridentifier;
            $pickup_name      = $getshippercustid->row()->name;
            $pickup_country   = $getshippercustid->row()->country;
            $pickup_state     = $getshippercustid->row()->state;
            $pickup_street    = $getshippercustid->row()->street;
            $pickup_pincode   = $getshippercustid->row()->pincode;
            $pickup_city      = $getshippercustid->row()->city;
            $pickup_latitude  = $getshippercustid->row()->latitude;
            $pickup_longitude = $getshippercustid->row()->longitude;
        }
        $tname            = "Full Truck Load";
        $tid              = "FTL";
        $enddate          = date('Y-m-d H:i:s', strtotime("+1 day"));
        $tid              = 1;
        $tname            = "";
        $gettrasnportmode = $this->db->query("SELECT id,name FROM tb_transportmode WHERE code LIKE '" . $popupmodeof_trasnport . "'");
        if ($gettrasnportmode->num_rows() > 0) {
            $tid   = $gettrasnportmode->row()->id;
            $tname = $gettrasnportmode->row()->name;
        }
        if ($shipment_id == "") {
            $shipment_id = "SVK" . time();
        }
        
        $ship_row_id = 0;
        $ship_arr    = [
            'shipid'           => $shipment_id,
            'txnid'            => $shipment_id,
            'trucktype'        => $tname,
            'pickupcnt'        => '1',
            'dropcnt'          => '1',
            'insertusr'        => $pickup_custid,
            'carrier'          => '0',
            'insertuserdate'   => $cdate,
            'enddate'          => $enddate,
            'insdate'          => $cdate,
            'upddate'          => $cdate,
            'reason'           => 'SHIPMENT',
            'purpose'          => 'SEND INTEGRATION',
            'ship_object'      => 'SHIPMENT',
            'logdate'          => $cdate,
            'transport_mode'   => $popupmodeof_trasnport,
            'domainname'       => $branch_code,
            'company_code'     => $company_code,
            'branch_code'      => $branch_code,
            'product'          => $product,
            'freight_term'     => '60',
            'freight_termname' => 'Free of Charge',
            'incoterm'         => $incoterm,
            'modeoftransport'  => $tid,
            'unitspec'         => 1,
        ];
        $chk_shipid = $this->db->query("SELECT id FROM tb_shipments WHERE shipid LIKE '" . $shipment_id . "'");

        if ($chk_shipid->num_rows() > 0) {
            $ship_row_id = $chk_shipid->row()->id;
            $this->db->where(['id' => $ship_row_id])->update("tb_shipments", $ship_arr);
        } else {

            $ship_arr['createdon'] = $cdate;
            $ship_ins              = $this->db->insert("tb_shipments", $ship_arr);
            $ship_row_id           = $this->db->insert_id();
        }
        /* Remove API check to get the lat and long if they are entered in bussiness partners */
        if ($pickup_latitude != "" && $pickup_longitude != "" && $drop_latitude != "" && $drop_longitude != "") {
            $lat1 = $pickup_latitude;
            $lng1 = $pickup_longitude;
            $lat2 = $drop_latitude;
            $lng2 = $drop_longitude;
        } else {
            $add1 = implode(",", [$pickup_street, $pickup_city, $pickup_country, $pickup_pincode]);
            $add2 = implode(",", [$drop_street, $drop_city, $drop_country, $drop_pincode]);
            $data = getlatlngsbyplace($add1);
            $lat1 = @$data[0];
            $lng1 = @$data[1];
            $data = getlatlngsbyplace($add2);
            $lat2 = @$data[0];
            $lng2 = @$data[1];
        }
        $customer_id = $pickup;
        
        if ($customer_id == "0" || $customer_id == "") {
            if ($popupcustomer_id != "" && $popupcustomer_id != "0") {
                $getcustomerid = $this->db->select("id")->get_where("tb_customers", ['code' => $popupcustomer_id, 'user_id' => $user_id, 'status' => '1']);
                if ($getcustomerid->num_rows() > 0) {
                    $customer_id = $getcustomerid->row()->id;
                }
            }
        }
        if ($this->session->userdata('company_code') == 'NZKN') {
            if ($product == "") {
                $product = "KN AsiaLink";
            }
            if ($popupmodeof_trasnport == "") {
                $popupmodeof_trasnport = "LTL";
            }
            if ($service == "") {
                $service = "19";
            }
        }
        $curtz                   = $this->session->userdata("usr_tzone")['timezone'];
        $logdate                 = date('Y-m-d H:i:s');
        $getactual               = getdatetimebytimezone(DFLT_TZ, $logdate, $curtz);
        $logdate                 = $getactual['datetime'];
        $getpickup               = getdatetimebytimezone(DFLT_TZ, $earlyquickbook_pickup, $curtz);
        $earlyquickbook_pickup   = $getpickup['datetime'];
        $getlpickup              = getdatetimebytimezone(DFLT_TZ, $latequickbook_pickup, $curtz);
        $latequickbook_pickup    = $getlpickup['datetime'];
        $getdelivery             = getdatetimebytimezone(DFLT_TZ, $earlyquickbook_delivery, $curtz);
        $earlyquickbook_delivery = $getdelivery['datetime'];
        $getldelivery            = getdatetimebytimezone(DFLT_TZ, $latequickbook_delivery, $curtz);
        $latequickbook_delivery  = $getldelivery['datetime'];
        $childid                 = 0;
        if ($this->session->userdata('childid')) {
            $childid = $this->session->userdata('childid');
        }
        $created_source = '3';
        
        $orderinfo = [
            'goods_value'       => '0.00',
            'shipment_id'       => $ship_row_id,
            'customer_id'       => $customer_id,
            'product'           => $product,
            'company_code'      => $company_code,
            'branch_code'       => $branch_code,
            'createdon'         => $cdate,
            'pickup_datetime'   => $earlyquickbook_pickup,
            'delivery_datetime' => $earlyquickbook_delivery,
            'pickup_endtime'    => $latequickbook_pickup,
            'drop_endtime'      => $latequickbook_delivery,
            'goods_value'       => $goods_value,
            'currency'          => $currency,
            'drop_custid'       => $drop_id,
            'drop_partyid'      => $drop_id,
            'user_id'           => $user_id,
            'sub_uid'           => $childid,
            'pickup_custid'     => $pickup_custid,
            'pickup_partyid'    => $pickup_custid,
            'pickup_country'    => $pickup_country,
            'pickup_city'       => $pickup_city,
            'pickup_pincode'    => $pickup_pincode,
            'pickup_company'    => $pickup_name,
            'pickup_address1'   => $pickup_street,
            'pickup_address2'   => $pickup_state,
            'delivery_country'  => $drop_country,
            'delivery_city'     => $drop_city,
            'delivery_pincode'  => $drop_pincode,
            'delivery_company'  => $drop_name,
            'delivery_address1' => $drop_street,
            'delivery_address2' => $drop_state,
            'transport_mode'    => $popupmodeof_trasnport,
            'plat'              => $lat1,
            'plng'              => $lng1,
            'dlat'              => $lat2,
            'dlng'              => $lng2,
            'is_created'        => '1',
            'modeoftransport'   => $tid,
            'created_source'    => $created_source,
            'createdon'         => $logdate,
            'vendor_id'         => $carrierId

        ];
        $ins_order    = $this->db->insert("tb_orders", $orderinfo);
        $order_id     = $this->db->insert_id();
        $get_country  = $this->db->select('country_code,company_code')->get_where("tb_users", ['id' => $user_id]);
        $country_code = $get_country->row()->country_code;
        $company_code = $get_country->row()->company_code;
        $genord       = ["user_id" => $user_id, "order_id" => $order_id, "country_code" => $country_code, "company_code" => $company_code];
        $booking_id   = generatebookingid($genord);
        $invtypes     = makeorderinvolvedpartiestype($customer_id, $order_id, "CUSTOMER");
        $invCarriertype = makeorderinvolvedpartiestype($carrierId, $order_id, "CARRIER");
        insertOrdersRefFileLineIdentifier(['pickupCity' => $pickup_city, 'pickupState' => $pickup_state, 'pickupCountry' => $pickup_country, 'dropCity' => $drop_city, 'dropState' => $drop_state, 'dropCountry' => $drop_country, 'companyCode' => $company_code, 'branchCode' => $branch_code, 'orderRowId' => $order_id, 'date' => $logdate]);
        // shift insertion
        $startTime = date('H:i', strtotime($earlyquickbook_pickup));
        $endTime = date('H:i', strtotime($latequickbook_delivery));
        $year = date('y');
        $week = date('W');
        $countCode = substr($company_code, 0, 2);
        $orderNumber = $booking_id;
        $sequenceNumber = $countCode === 'UK' ? $orderNumber : substr($orderNumber, -6);
        $trip['shipmentId'] = "T" . $countCode . $week . $year . $sequenceNumber;
        $shiftarr = [
            'user_id' => $user_id,
            'stime' => $startTime,
            'etime' => $endTime,
            'splace' => $pickup_city,
            'slat' => $lat1,
            'slng' => $lng1,
            'eplace' => $drop_city,
            'elat' => $lat2,
            'elng' => $lng2,
            'scity' => $pickup_city,
            'dcity' => $drop_city,
            'zone_id' => 1,
            'empshift_start' => $startTime,
            'empshift_end' => $endTime,
            'trip_type' => 0,
            'startdate' => $earlyquickbook_pickup,
            'enddate' => $latequickbook_delivery,
            'shipment_name' => 'Boxes',
            'shipment_id' => 0,
            'transport_mode' => $tid,
            'customer_id' => $customer_id,
            'vendor_id' => $carrierId,
            'carrier_type' => 0,
            'shipmentid' => $trip['shipmentId'],
            'txnid' => $trip['shipmentId'],
            'company_code' => $company_code,
            'branch_code' => $branch_code,
            'status' => 1
        ];
        $shiftRowId = $this->common->insertTableData("tb_shifts", $shiftarr);
        $stopPickupAddress = $stopDropAddress = "";
                  
                        $stopPickupAddress .= $pickup_street;
                        $stopDropAddress .= $drop_street;
                        $stopPickupAddress .= ", " . $pickup_name;
                        $stopDropAddress .= ", " . $drop_name;
                        $stopPickupAddress .= ", " . $pickup_country;
                        $stopDropAddress .= ", " . $drop_country;
                        $stopPickupAddress .= ", " . $pickup_city;
                        $stopDropAddress .= ", " . $drop_city;
                        $stopPickupAddress .= ", " . $pickup_pincode;
                        $stopDropAddress .= ", " . $drop_pincode;
              $pickshipArr = [
                            'stopname' => $pickup_city,
                            'plat' => $lat1,
                            'plng' => $lng1,
                            'stopcity' => $pickup_city,
                            'address' => $stopPickupAddress,
                            'stoptype' => 'P',
                            'stopstatus' => 0,
                            'shipment_id' => $shiftRowId,
                            'ordernumber' => 1,
                            'startdate' => $earlyquickbook_pickup,
                            'enddate' => $earlyquickbook_delivery,
                            'shipmentstopid' => 0,
                            'txncode' => 'NP',
                            'status' => 1,
                            'created_on' => $cdate
                        ];
                        $insPickupShip = $this->common->insertTableData("tb_shiporder_stops", $pickshipArr);
                             $DdropshipArr = [
                            'stopname' => $drop_city,
                            'plat' => $lat2,
                            'plng' => $lng2,
                            'stopcity' => $drop_city,
                            'address' => $stopDropAddress,
                            'stoptype' => 'D',
                            'stopstatus' => 0,
                            'shipment_id' => $shiftRowId,
                            'ordernumber' => 2,
                            'startdate' => $earlyquickbook_pickup,
                            'enddate' => $earlyquickbook_delivery,
                            'shipmentstopid' => 0,
                            'txncode' => 'NP',
                            'status' => 1,
                            'created_on' => $cdate
                        ];
                        $insDropShip = $this->common->insertTableData("tb_shiporder_stops", $DdropshipArr);        
        
        
        // inserting extra data

        $shiftVeharr = [
                'user_id' => $user_id,
                'shft_id' => $shiftRowId,
                'carrier_id' => $carrierId,
                'status' => 1,
                'created_on' => $cdate
        ];
        $shiftVehRowId = $this->common->insertTableData("tb_shft_veh", $shiftVeharr);
               $tripArr = [
                'shift_id' => $shiftRowId,
                'status' => 1,
                'created_on' => $cdate,
                'plat' => $lat1,
                'plng' => $lng1,
                'dlat' => $lat2,
                'dlng' => $lng2,
                'stime' => $earlyquickbook_pickup,
                'etime' => $latequickbook_delivery,
       ];
        $tripRowId = $this->common->insertTableData("tb_trips", $tripArr);


        $upd     = $this->db->where(['id' => $order_id])->update("tb_orders", ['order_id' => $booking_id,'shift_id' => $shiftRowId,'shipmentid'=>$trip['shipmentId']]);

        // employee table update
          $employeearr = [
            'assoc_id ' => $trip['shipmentId'],
            'customer_id'       => $customer_id,
            'plat' => $lat1,
            'plng' => $lng1,
            'dlat' => $lat2,
            'dlng' => $lng2,
            'pickup_city'       => $pickup_city,
            'drop_city'     => $drop_city,
            'user_id' => $user_id,
            'shift_id' => $shiftRowId,
            'vendor_id' => $carrierId,
            'order_id' => $booking_id,
            'status' => 1,
            'startdate' => $earlyquickbook_pickup,
            'enddate' => $earlyquickbook_delivery,
            'pickup_datetime' => $earlyquickbook_pickup,
            'drop_datetime' => $earlyquickbook_delivery,
            'pickup' => $pickup_street,
            'drop' => $drop_street,
            'ship_type' => 'P',
            'stop_id' => $insPickupShip,
            'stop_order' => 1,
            'address' => $stopPickupAddress,
            'createdon' => $cdate
        ];
        $employeeRowId = $this->common->insertTableData("tb_employee", $employeearr);


        $insertedStatus = $this->common->insertTableData("tb_stop_status", ['order_id' => $order_id, 'status_id' => '9', 'status_code' => '0100', 'stop_type' => '', 'loc_name' => '', 'comment' => '', 'status' => '1', 'reason' => '', 'createdon' => $cdate]);
        $details = [
            'shipper_id'      => $_POST['indentshipper_id'],
            'service'         => $service,
            'delivery_term'   => $delivery_terms,
            'incoterm'        => $incoterm,
            /*'purchase_order'  => $porder,*/
            'notify_party'    => $notify_party,
            'department_code' => $department_code,
            'createdon'       => $cdate,
            'order_row_id'    => $order_id,
            'order_id'        => $booking_id,
            'order_type'      => $popuporder_type,
        ];
        $this->db->insert('tb_order_details', $details);
     
        $order_shipper_id   = isset($_POST['indentshipper_id']) ? $_POST['indentshipper_id'] : "";
        $pickup_address     = $pickup_street . "," . $pickup_city . "," . $pickup_state;
        $shipper_address    = ['order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'location_id' => $pickup_city, 'street' => $pickup_street, 'state' => $pickup_state, 'address' => $pickup_address, 'pincode' => $pickup_pincode, 'country' => $pickup_country, 'user_id' => $user_id];
        $chk_shipperaddress = $this->db->select("id")->get_where("tbl_orderparty_address", ['order_id' => $order_id, 'party_master_id' => $order_shipper_id, 'status' => '1']);
        if ($chk_shipperaddress->num_rows() > 0) {
            $shipperadd_id = $chk_shipperaddress->row()->id;
            $upd_add       = $this->db->where(['id' => $shipperadd_id])->update("tbl_orderparty_address", $shipper_address);
        } else {
            $shipper_address['createdon'] = $cdate;
            $this->db->insert("tbl_orderparty_address", $shipper_address);
            $shipperadd_id = $this->db->insert_id();
        }
        $drop_address        = $drop_street . "," . $drop_city . "," . $drop_state;
        $delivery_address    = ['order_id' => $order_id, 'party_master_id' => $delivery, 'location_id' => $drop_city, 'street' => $drop_street, 'state' => $drop_state, 'address' => $drop_address, 'pincode' => $drop_pincode, 'country' => $drop_country, 'user_id' => $user_id];
        $chk_deliveryaddress = $this->db->select("id")->get_where("tbl_orderparty_address", ['order_id' => $order_id, 'party_master_id' => $delivery, 'status' => '1']);
        if ($chk_deliveryaddress->num_rows() > 0) {
            $dropadd_id = $chk_deliveryaddress->row()->id;
            $upd_add    = $this->db->where(['id' => $dropadd_id])->update("tbl_orderparty_address", $delivery_address);
        } else {
            $delivery_address['createdon'] = $cdate;
            $this->db->insert("tbl_orderparty_address", $delivery_address);
            $dropadd_id = $this->db->insert_id();
        }
        $shipment_name = "BOXES";
        $cargo_typeArr = isset($_POST['popupcargo_type']) ? $this->db->escape_str($_POST['popupcargo_type']) : [];
        $quantityArr = isset($_POST['quantity']) ? $this->db->escape_str($_POST['quantity']) : [];
        $lengthArr = isset($_POST['length']) ? $this->db->escape_str($_POST['length']) : [];
        $length_uomArr = isset($_POST['length_uom']) ? $this->db->escape_str($_POST['length_uom']) : [];
        $widthArr = isset($_POST['width']) ? $this->db->escape_str($_POST['width']) : [];
        $width_uomArr = isset($_POST['width_uom']) ? $this->db->escape_str($_POST['width_uom']) : [];
        $heightArr = isset($_POST['height']) ? $this->db->escape_str($_POST['height']) : [];
        $height_uomArr = isset($_POST['height_uom']) ? $this->db->escape_str($_POST['height_uom']) : [];
        $actualWeightArr = isset($_POST['actualWeight']) ? $this->db->escape_str($_POST['actualWeight']) : [];
        $actualWeight_uomArr = isset($_POST['actualWeight_uom']) ? $this->db->escape_str($_POST['actualWeight_uom']) : [];
        $weightArr = isset($_POST['weight']) ? $this->db->escape_str($_POST['weight']) : [];
        $weight_uomArr = isset($_POST['weight_uom']) ? $this->db->escape_str($_POST['weight_uom']) : [];
        $volumetricWeightArr = isset($_POST['volumetricWeight']) ? $this->db->escape_str($_POST['volumetricWeight']) : [];
        $volumetricWeight_uomArr = isset($_POST['volumetricWeight_uom']) ? $this->db->escape_str($_POST['volumetricWeight_uom']) : [];
        $actualVolumeArr = isset($_POST['actualVolume']) ? $this->db->escape_str($_POST['actualVolume']) : [];
        $actualVolume_uomArr = isset($_POST['actualVolume_uom']) ? $this->db->escape_str($_POST['actualVolume_uom']) : [];
        $volumeArr = isset($_POST['volume']) ? $this->db->escape_str($_POST['volume']) : [];
        $volume_uomArr = isset($_POST['volume_uom']) ? $this->db->escape_str($_POST['volume_uom']) : [];
        $lbhData = [];
        foreach ($cargo_typeArr as $key => $value) {
			if (!in_array('', [$value])) {
				$cargo_type = $value ?? "";
                $quantity = $quantityArr[$key] ?? "1";
				$length = $lengthArr[$key] ?? 1;
				$lengthUnit = $length_uomArr[$key] ?? "M";
				$width = $widthArr[$key] ?? 1;
				$widthUnit = $width_uomArr[$key] ?? "M";
				$height = $heightArr[$key] ?? 1;
				$heightUnit = $height_uomArr[$key] ?? "M";
				$weight = $actualWeightArr[$key] ?? 1;
				$weightUnit = $actualWeight_uomArr[$key] ?? "KG";
                $secondWeight = $weightArr[$key] ?? 1;
				$secondWeightUnit = $weight_uomArr[$key] ?? "KG";
                $volumetricWeight = $volumetricWeightArr[$key] ?? 1;
				$volumetricWeightUnit = $volumetricWeight_uomArr[$key] ?? "KG";
				$actualVolume = $actualVolumeArr[$key] ?? 1;
				$actualVolumeUnit = $actualVolume_uomArr[$key] ?? "CBM";
                $secondVolume = $volumeArr[$key] ?? 1;
				$secondVolumeUnit = $volume_uomArr[$key] ?? "CBM";
			
                 $cargo = [
                        'cargo_type'          => $cargo_type,
                        'quantity'          => $quantity,
                        'status'            => '1',
                        'length'            => $length,
                        'length_unit'       => $lengthUnit,
                        'width'             => $width,
                        'width_unit'       => $widthUnit,
                        'height'            => $height,
                        'height_unit'       => $heightUnit,
                        'weight'            => $weight,
                        'weight_unit'       => $weightUnit,
                        'second_weight'      => $secondWeight,
                        'secondweight_uom'       => $secondWeightUnit,
                        'volumetric_weight' => $volumetricWeight,
                        'volweight_uom'     => $volumetricWeightUnit,
                        'volume'            => $actualVolume,
                        'volume_unit'     => $actualVolumeUnit,
                        'second_volume'     => $secondVolume,
                        'secondvolume_uom'     => $secondVolumeUnit,
                        'createdon' => $cdate
                    ];
                    $cargoId = $this->common->insertTableData("tb_cargo_details", $cargo);
                                        $orderCargo = [
                        'order_id'          => $order_id,
                        'cargo_id'          => $cargoId,
                        'status'            => '1',
                        'length'            => $length,
                        'width'             => $width,
                        'height'            => $height,
                        'weight'            => $weight,
                        'volume'            => $actualVolume,
                        'quantity'          => $quantity,
                        'quantity_type'     => $cargo_type,
                        'volumetric_weight' => $volumetricWeight,
                        'volweight_uom'     => $volumetricWeightUnit,
                        'second_weight'     => $secondWeight,
                        'second_volume'     => $secondVolume,
                        'createdon'         => $cdate
                    ];
                    $orderCargoId = $this->common->insertTableData("tb_order_cargodetails", $orderCargo);
                    $packetNo = $booking_id.'-'.$cargoId;
                    $lbhData[] = [
                    "packetCount"         => (int)$quantity,
                    "packetLength"        => (int)$length,
                    "packetWidth"         => (int)$width,
                    "packetHeight"        => (int)$height,
                    "packetNo"            => null,
                    "customerPacketRefNo" => $packetNo,
                    "actualWeight"        => (int)$weight,
                    "invoiceNo"           => null,
                ];
			}
		}

        $total_weight = $total_volume = $total_quantity = 0;
        $gettotal     = $this->db->query("SELECT sum(weight) as total_weight,sum(volume) as total_volume,sum(quantity) as total_quantity FROM tb_order_cargodetails WHERE order_id='" . $order_id . "'");
        if ($gettotal->num_rows() > 0) {
            $total_volume   = $gettotal->row()->total_volume;
            $total_weight   = $gettotal->row()->total_weight;
            $total_quantity = $gettotal->row()->total_quantity;
        }
        $cargo_forship = [];
        $getcargos     = $this->db->query("SELECT quantity_type FROM tb_order_cargodetails WHERE order_id ='" . $order_id . "'");
        if ($getcargos->num_rows() > 0) {
            foreach ($getcargos->result() as $res) {
                $cargo_forship[] = $res->quantity_type;
            }
        }
        $unitspec = "";
        if (! empty($cargo_forship)) {
            $unitspec = implode(',', $cargo_forship);
        }
        $updship   = $this->db->where(['id' => $ship_row_id])->update("tb_shipments", ['unitspec' => $unitspec, 'txncode' => $booking_id]);
        $upd_order = $this->db->where(['id' => $order_id])->update("tb_orders", ['volume' => $total_volume, 'weight' => $total_weight, 'quantity' => $total_quantity]);
        $ids       = [];
        if ($reference_ids != "0") {
            $refids = explode(',', $reference_ids);
        }
        $order_ref_ids = [];
        if ($quickbook_order_reference_ids != "0") {
            $order_ref_ids = explode(',', $quickbook_order_reference_ids);
        }
        if (! empty($order_ref_ids)) {
            for ($i = 0; $i < count($order_ref_ids); $i++) {
                if ($order_ref_ids[$i] != "") {
                    $upd = $this->db->where(['id' => $order_ref_ids[$i]])->update("tb_order_references", ['order_id' => $order_id]);
                }
            }
        }
        if ($shipment_id != "" && $this->session->userdata('company_code') != 'KNAU') {
            $ins_ref = ['order_id' => $order_id, 'reference_id' => 'DQ', 'ref_value' => $shipment_id, 'createdon' => $cdate];
            $ins = $this->db->insert('tb_order_references', $ins_ref);

        }
        if ($carrierRef != "") {
            $ins_ref = ['order_id' => $order_id, 'reference_id' => 'TKN', 'ref_value' => $carrierRef, 'createdon' => $cdate];
            $ins = $this->db->insert('tb_order_references', $ins_ref);

        }
        if ($driverdelivery_popup != "") {
            $ins_ref = ['order_id' => $order_id, 'reference_id' => 'ORD_DLVINST', 'ref_value' => $driverdelivery_popup, 'createdon' => $cdate];
            $ins = $this->db->insert('tb_order_references', $ins_ref);

        }
        if ($driverpickup_popup != "") {
            $ins_ref = ['order_id' => $order_id, 'reference_id' => 'ORD_PIKINST', 'ref_value' => $driverpickup_popup, 'createdon' => $cdate];
            $ins = $this->db->insert('tb_order_references', $ins_ref);

        }
        if ($porder != "") {
            $ins_ref = ['order_id' => $order_id, 'reference_id' => 'PO', 'ref_value' => $porder, 'createdon' => $cdate];
            $ins = $this->db->insert('tb_order_references', $ins_ref);

        }
        if (checkAccessConditions("CHECK_STS_REFERENCE_COUNTRIES", $company_code)) {
            $ins_ref     = ['order_id' => $order_id, 'reference_id' => 'STS'];
            $checkSTSRef = $this->common->gettblrowdata($ins_ref, "id", "tb_order_references", 0, 0);
            if (count($checkSTSRef) == 0) {
                $ins_ref['ref_value'] = "Pending";
                $this->common->insertTableData("tb_order_references", $ins_ref);
            }
        }

        $sub_cut_parties      = [];
        $sub_cut_parties['0'] = $order_shipper_id;
        $sub_cut_parties['1'] = $delivery;
        $sub_cut_parties['2'] = '0';
        $sub_cut_parties['3'] = '0';
        if (! empty($sub_cut_parties)) {
            subcustpartiesinsert($order_id, $booking_id, $sub_cut_parties);
        }
        $pref_arr = [
            'pickup'          => strtoupper($pickup_country),
            'pickup_state'    => strtoupper($pickup_state),
            'pickup_city'     => strtoupper($pickup_city),
            'pickup_pincode'  => $pickup_pincode,
            'drop'            => strtoupper($drop_country),
            'drop_state'      => strtoupper($drop_state),
            'drop_city'       => strtoupper($drop_city),
            'drop_pincode'    => $drop_pincode,
            'customer_id'     => $popupcustomer_id,
            'service'         => $service,
            'product'         => $product,
            'user_id'         => $user_id,
            'company_code'    => $company_code,
            'order_id'        => $order_id,
            'order_type'      => $popuporder_type,
            'customer_row_id' => $customer_id,
        ];
        $post              = $this->input->post(null, true);
        $customerProfileId = $post['customerProfileId'] ?? 0;
        $rateServiceRowId  = $post['rateServiceRowId'] ?? 0;
        $rateOfferingRowId = $post['rateOfferingRowId'] ?? 0;
        $rateRecordRowId   = $post['rateRecordRowId'] ?? 0;
        $laneRowId         = $post['laneRowIdForBook'] ?? 0;
        if (! in_array(0, [$customerProfileId, $rateServiceRowId, $rateOfferingRowId, $rateRecordRowId, $laneRowId], true)) {
            $this->ratemanagement->addratesForOrderFromRateEnquiry(
                ['customerId' => $popupcustomer_id, 'orderRowId' => $order_id, 'customerProfile' => $customerProfileId, 'rateServiceRowId' => $rateServiceRowId, 'rateOfferingRowId' => $rateOfferingRowId, 'rateRecordRowId' => $rateRecordRowId, 'currency' => $this->session->userdata("usr_tzone")['currency'], 'userId' => $user_id, 'laneRowId' => $laneRowId, 'vendorIdFromProfile' => $post['vendorIdFromProfile'] ?? 0, 'vendorCodeFromProfile' => $post['vendorCodeFromProfile'] ?? ""]
            );
        } else {
            $this->ratemanagement->addrecodfororderinsertion($pref_arr);
        }
        /*if($this->session->userdata('usr_tzone')['country'] == "RU"){*/

        if ($order_id != "" && $customer_id != "") {
            $pickupinfo['country']       = trim($pickup_country);
            $pickupinfo['state']         = trim($pickup_state);
            $pickupinfo['city']          = trim($pickup_city);
            $pickupinfo['region']        = trim($pickup_street);
            $pickupinfo['zipcode']       = trim($pickup_pincode);
            $pickupinfo['order_country'] = trim($pickup_country);
            $pickupinfo['order_city']    = trim($pickup_city);
            $pickupinfo['order_zipcode'] = trim($pickup_pincode);
            $pickupinfo['stoptype']      = "P";
            $dropinfo['country']         = trim($drop_country);
            $dropinfo['order_country']   = trim($drop_country);
            $dropinfo['order_city']      = trim($drop_city);
            $dropinfo['order_zipcode']   = trim($drop_pincode);
            $dropinfo['state']           = trim($drop_state);
            $dropinfo['city']            = trim($drop_city);
            $dropinfo['region']          = trim($drop_street);
            $dropinfo['zipcode']         = trim($drop_pincode);

            $dropinfo['stoptype'] = "D";
            $pickupgeocode        = checkgeocode($pickupinfo);
            $dropgeocode          = checkgeocode($dropinfo);
            if (! empty($pickupgeocode) && ! empty($dropgeocode)) {
                $pickupgeocode['stoptype']      = "P";
                $dropgeocode['stoptype']        = "D";
                $pickupgeocode['order_country'] = trim($pickup_country);
                $pickupgeocode['order_city']    = trim($pickup_city);
                $pickupgeocode['order_zipcode'] = trim($pickup_pincode);
                $dropgeocode['order_country']   = trim($drop_country);
                $dropgeocode['order_city']      = trim($drop_city);
                $dropgeocode['order_zipcode']   = trim($drop_pincode);

                //-------------------------------- //for auto route
                $pickupgeocode['cargo'] = $cargo;
                $dropgeocode['cargo']   = $cargo;
                //--------------------------------
                $pickuproute = getcust_routeautomate($customer_id, $pickupgeocode);
                $droproute   = getcust_routeautomate($customer_id, $dropgeocode);
                if (! empty($pickuproute) && ! empty($droproute)) {
                    $orderinfo['id']             = $order_id;
                    $orderinfo['order_id']       = $booking_id;
                    $orderinfo['shipment_name']  = $shipment_name;
                    $orderinfo['customer_phone'] = $customer_phone;
                    $orderinfo['customer_email'] = $customer_email;
                    $orderinfo['volume']         = $total_volume;
                    $orderinfo['weight']         = $total_weight;
                    $orderinfo['quantity']       = $total_quantity;
                    $orderinfo['quantity']       = $total_quantity;
                    $shipment                    = createshipmentbyorder($pickuproute, $orderinfo);
                } else {
                    //-------------------------------- //for auto route
                    $pickupinfo['cargo'] = $cargo;
                    $dropinfo['cargo']   = $cargo;
                    //--------------------------------
                    $pickuproute1 = getcust_routeautomate($customer_id, $pickupinfo);
                    $droproute1   = getcust_routeautomate($customer_id, $dropinfo);
                    if (! empty($pickuproute1) && ! empty($droproute1)) {
                        $orderinfo['id']             = $order_id;
                        $orderinfo['order_id']       = $booking_id;
                        $orderinfo['shipment_name']  = $shipment_name;
                        $orderinfo['customer_phone'] = $customer_phone;
                        $orderinfo['customer_email'] = $customer_email;
                        $orderinfo['volume']         = $total_volume;
                        $orderinfo['weight']         = $total_weight;
                        $orderinfo['quantity']       = $total_quantity;
                        $orderinfo['quantity']       = $total_quantity;
                        $shipment                    = createshipmentbyorder($pickuproute1, $orderinfo);
                    }
                }
            } else {

                //-------------------------------- //for auto route
                $pickupinfo['cargo'] = $cargo;
                $dropinfo['cargo']   = $cargo;
                //--------------------------------

                $pickuproute1 = getcust_routeautomate($customer_id, $pickupinfo);
                $droproute1   = getcust_routeautomate($customer_id, $dropinfo);
                if (! empty($pickuproute1) && ! empty($droproute1)) {
                    $orderinfo['id']             = $order_id;
                    $orderinfo['order_id']       = $booking_id;
                    $orderinfo['shipment_name']  = $shipment_name;
                    $orderinfo['customer_phone'] = $customer_phone;
                    $orderinfo['customer_email'] = $customer_email;
                    $orderinfo['volume']         = $total_volume;
                    $orderinfo['weight']         = $total_weight;
                    $orderinfo['quantity']       = $total_quantity;
                    $orderinfo['quantity']       = $total_quantity;
                    $shipment                    = createshipmentbyorder($pickuproute1, $orderinfo);
                }
            }
            $checkTripForOrder = $this->common->gettblrowdata("id='" . $order_id . "' AND shift_id >0", "id,shift_id", "tb_orders", 0, 0);
            if (! empty($checkTripForOrder)) {
                $this->load->library('notifytrigger');
                $this->notifytrigger->sendNotificationToCarrier($checkTripForOrder['shift_id'], $company_code, 'CR');
            }
        }
        /*}*/
        $this->ordernotify('booking_create', $order_id);
        if ($order_id != "" && $order_id != '0') {
            try {
                $this->altovaordercreation->sendOrderToAltova($order_id);
            } catch (Exception $ex) {
                log_message("error", "Some Problem occured!, While Sending Order to Altova " . $ex->getMessage());
            }
            $flipkartRequest = [
                "poNumber"                => (string)$booking_id,
                "travelMode"              => "Road",
                "grossWeight"             => (int)$total_weight,
                "packetCount"             => (int)$total_quantity,
                "material"                => null,
                "deliveryAppointmentDate" => null,
                "deliveryTimeSlot"        => null,
                "lbhData"                 => $lbhData,
                "invoiceDetails"          => [
                    [
                        "invoiceNo"     => (string)$booking_id,
                        "invoiceAmount" => 1,
                        "ewbNo"         => null,
                        "invoiceDate"   => $currentdate,
                        "ewbDate"       => null,
                        "ewbValidTill"  => null,
                    ],
                ],
                "consignor"               => [
                    "consignorCode"    => null,
                    "consignorPincode" => trim($pickup_pincode),
                    "consignorName"    => trim($pickup_name),
                    "address1"         => trim($pickup_street), //"13th Floor, AIPL Business Club, Golf Course Extension Road, Sector 62, Gurugram, Haryana, 12210",
                    "city"             => trim($pickup_city),
                    "state"            => trim($pickup_state),
                    "contactName"      => null,
                    "contactPhoneno"   => null,
                    "email"            => "",
                ],
                "consignee"               => [
                    "consigneeCode"    => null,
                    "consigneePincode" => trim($drop_pincode),
                    "consigneeName"    => trim($drop_name),
                    "address1"         => trim($drop_street),
                    "city"             => trim($drop_city),
                    "state"            => trim($drop_state),
                    "contactName"      => null,
                    "contactPhoneno"   => null,
                    "email"            => null,
                ],
                "docketNo"                => $carrierRef,
                "packetLbhUom"            => "IN",
                "totalConsignmentValue"   => 1,
                "ftlOrPtl"                => "0",
                "openBoxPickup"           => 0,
                "truckType"               => null,
            ];
           
            /* log_message("error", "flipkartRequest:" . json_encode($flipkartRequest));*/
            
            $carrierCode= "";
            $vendor_list = $this->db->select("code")->get_where("tb_vendors", ['id' => $carrierId]);
            if ($vendor_list->num_rows() > 0) {
                $carrierCode = $vendor_list->row()->code;
            }
            
            if($carrierCode == FLIPKART_USERID)
            {
                $flipkartResponse = $this->flipkartediservices->createOrder($flipkartRequest);
            }
            /*log_message("error", "flipkartResponse:" . json_encode($flipkartResponse));
            log_message("error", "booking_id:" . $booking_id);*/
            $this->session->set_flashdata('success_msg', 'Order Created Successfully - ' . $booking_id);
           /* log_message("error", "order_id:" . $order_id);*/
            redirect('orders/orderslist/' . $order_id);
        } else {
            redirect("orders");
        }

    }
    
    public function addIndent() {
        $company_code = $this->session->userdata( 'company_code' );
        $branch_code  = $this->session->userdata( 'branch_code' );
        $data['company_code'] = $company_code;
        $data['branch_code']  = $branch_code;
        $this->load->view('orders/addIndent', $data);
    }
    
     public function addQuickBook() {
        $data['title'] = 'Quick Book';
        $data['company_code'] = $this->session->userdata('company_code');
        log_message("error", "data:" . json_encode($data));
        $this->load->view('orders/addQuickBook', $data);
    }
}
