<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/ //
//$Id: ShipmentController.php, v1 2013/09/24 20:52:11
//
class ShipmentController extends Controller {
    public function indexAction() {
    }
    public function showAction() {
        $ObjOrder    = new OrderModel();
        $ObjStatus = new OrderstatusModel();
        $this->_allorderstatus = $dynamicOrderStatuses = $ObjStatus->listOrderstatusInOptions(array("list" => 'hash','languageIDs'=>$this->ObjView->languageIDs));
        $jk=0;
        foreach($dynamicOrderStatuses as $key=>$value){
            $dynamicOrdersStatus[$jk][0] = $key;
            $dynamicOrdersStatus[$jk][1] = ($value);
            $jk++;
        }
        $this->ObjView->assign("getDynOrderStatusByKey", $dynamicOrderStatuses);
        $this->ObjView->assign("dynamicOrdersStatus", $dynamicOrdersStatus);
        $shipmentID  = $this->getRequestValue('id');
        $languageIDs = $this->ObjView->languageIDs;
        $history     = $this->getPreviousURL();
        if ($shipmentID < 1) {
            $this->setredirect("/shipping/shipped/");
        }
        $shipmentDetails = $ObjOrder->getShipmentDetails($shipmentID, $languageIDs);        
        if (empty($shipmentDetails['items'])) {
            $this->setredirect("/shipping/shipped/");
        }
        $billingAddress                     = unserialize($shipmentDetails['billingAddress']);
        $shipmentDetails['billingAddress']  = array_values(array_slice(unserialize($shipmentDetails['billingAddress']), 0, -2));
        $shipAddress                        = unserialize($shipmentDetails['shippingAddress']);
        $shippingPhone                      = $shipAddress['shippingPhone'];
        unset($shipAddress['shippingPhone']);
        //unset($shipAddress['shippingProvince']);
        $shipmentDetails['shippingAddress'] = array_values($shipAddress);
        $shipmentDetails['extraData']       = unserialize($shipmentDetails['extraData']);
        if (count($shipmentDetails['items']) > 0) {
            foreach ($shipmentDetails['items'] as $key => $items) {
                $extraStr                                = unserialize($items['extra']);
                $shipmentDetails['items'][$key]['extra'] = $extraStr;
            }
        }
        $this->ObjView->assign("shipmentDetails", $shipmentDetails);
        $this->ObjView->assign('showprivilege', $this->ObjCommon->hasPrivilege('order/show/'));
        $this->ObjView->assign("billingAddress", $billingAddress);
        $this->ObjView->assign("shipmentID", $shipmentID);
        $this->ObjView->assign("history", $history);
        $this->ObjView->assign("shippingPhone", $shippingPhone);
        $this->ObjView->assign("labelPrivilege", $this->ObjCommon->hasPrivilege('shipment/label/'));
        $this->ObjView->assign("shipmentEditPrivilege", $this->ObjCommon->hasPrivilege('shipment/edit/'));
        $this->ObjView->display('ShipmentView.tpl');
        //echo '<pre>';print_r($shipmentDetails);
    }
    public function labelAction() {
        $ObjOrder         = new OrderModel();
        $ObjLanguage        = new languageModel();
        $ObjStatus = new OrderstatusModel();
        $this->_allorderstatus = $dynamicOrderStatuses = $ObjStatus->listOrderstatusInOptions(array("list" => 'hash','languageIDs'=>$this->ObjView->languageIDs));
        $jk=0;
        foreach($dynamicOrderStatuses as $key=>$value){
            $dynamicOrdersStatus[$jk][0] = $key;
            $dynamicOrdersStatus[$jk][1] = ($value);
            $jk++;
        }
        $this->ObjView->assign("getDynOrderStatusByKey", $dynamicOrderStatuses);
        $this->ObjView->assign("dynamicOrdersStatus", $dynamicOrdersStatus);
        $languageIDs      = $this->ObjView->languageIDs;
        //search parameters
        $shipmentID       = explode(":", substr($this->decodeUrlString($this->getRequestValue('shipmentIDs')), 0, -1));
        $shipmentID       = implode(",", $shipmentID);
        
        $resShippedOrders = $ObjOrder->getShipmentDetails($shipmentID, $languageIDs, 'list');
        $orderLangIDs     = $ObjOrder->getOrderLanguageIDs('', $resShippedOrders[0]['masterOrderId']);  
        $languageDirection= !empty($resShippedOrders[0]['languageDirection'])?$resShippedOrders[0]['languageDirection']:'';
        foreach ($resShippedOrders as $key => $array) {
            $shipAddress = unserialize($array['shippingAddress']);           
            $shippingPhone                      = $shipAddress['shippingPhone'];
            unset($shipAddress['shippingPhone']);
            //unset($shipAddress['shippingProvince']);           
            if ($shipAddress != '') {
                $resShippedOrders[$key]['shippingAddress'] = array_values($shipAddress);
            }
            $billingAddress = unserialize($array['billingAddress']);
            if ($billingAddress != '') {
                $resShippedOrders[$key]['billingAddress'] = array_values(array_slice($billingAddress, 0, -2));
            }
        }
        if($resShippedOrders[0]['items'][0]['shippingMethod'] !=''){
             $shipmentmethod=$resShippedOrders[0]['items'][0]['shippingMethod'];
            $langXML                = $ObjLanguage->loadLanguageXMLtoArray(__CORE_PUBLIC_COMMON_FRONTEND_PATH . '/' . __DIR_LANGUAGE . '/' . $this->ObjCommon->langArray[$languageIDs['Current']]['LanguageLCIDstring'] . '.xml');
            if($shipmentmethod == "One Day Delivery"){
                $shipmentmethod= $langXML['lblOneDayDelivery'];
            }
            else if($shipmentmethod == "Free Shipping"){
                $shipmentmethod= $langXML['lblFreeShipping'];
            }
             else if($shipmentmethod == "Flat Rate Shipping"){
                $shipmentmethod= $langXML['lblFlatRateShipping'];
            }
             else if($shipmentmethod == "Same Day Delivery"){
                $shipmentmethod= $langXML['lblSameDayDelivery'];
            }
             else if($shipmentmethod == "All For Free"){
                $shipmentmethod= $langXML['lblAllForFree'];
            }
             else if($shipmentmethod == "Quick Delivery"){
                $shipmentmethod= $langXML['lblQuickDelivery'];
            }
             else if($shipmentmethod == "Next Day Delivery"){
                $shipmentmethod= $langXML['lblNextDayDelivery'];
            }
             else if($shipmentmethod == "Jihazi Delivery" || $shipmentmethod == "Jihazi Delivery Charge" ){
                $shipmentmethod= $langXML['lblJihaziDelivery'];
            }
                    
        }
        else{
            $shipmentmethod='';
        }
        $adminInfo      = $this->getSettingValue("company_information", "address_1");             
        if($this->getSettingValue("company_information", "address_2")!='') {
            $adminInfo  .=    ",<br>".$this->getSettingValue("company_information", "address_2");
        }            
        if($this->getSettingValue("company_information", "company_city")!='') {
            $adminInfo  .=    ",<br>".$this->getSettingValue("company_information", "company_city");
        }
        if($this->getSettingValue("company_information", "company_zip")!='') {
            $adminInfo  .=    ",<br>".$this->getSettingValue("company_information", "company_zip");
        }
        if($this->getSettingValue("company_information", "company_state")!='' && $this->getSettingValue("company_information", "company_city")!='' && $this->getSettingValue("company_information", "company_state")!=$this->getSettingValue("company_information", "company_city")) {
            $adminInfo  .=    ",<br>".$this->getSettingValue("company_information", "company_state");
        }
        if($this->getSettingValue("company_information", "company_country")!='') {
            $adminInfo  .=    ",<br>".$this->getSettingValue("company_information", "company_country");
        }
        $companyEmail       =   $this->getSettingValue("company_information", "company_email");
        $companyPhone       =   $this->getSettingValue("company_information", "company_phone");
        
        $companyWebsite     =   $this->getSettingValue("company_information", "company_website");
        $companyFax         =   $this->getSettingValue("company_information", "company_fax");
                 
        $this->ObjView->assign("adminInfo", $adminInfo);
        $this->ObjView->assign("companyName", $this->getSettingValue("company_information", "company_name"));
        $this->ObjView->assign("companyEmail", $companyEmail);
        $this->ObjView->assign("companyWebsite", $companyWebsite);
        $this->ObjView->assign("companyFax", $companyFax);
        $this->ObjView->assign("companyPhone", $companyPhone);
        $this->ObjView->assign("shipmentmethods", $shipmentmethod);
        $this->ObjView->assign("resShippedOrders", $resShippedOrders);
        $this->ObjView->assign("languageDirection", $languageDirection);
        $vatNumber = ($languageIDs['Current']==$orderLangIDs['Current'])?$this->getLanguageValue('lblVatValue'):$this->getVatNumber($orderLangIDs['Current']);        
        $this->ObjView->assign('vatNumber', $vatNumber);        
        $this->ObjView->assign("shippingPhone", $shippingPhone);
        $this->ObjView->display('ShipmentLabels.tpl');
    }
    public function getVatNumber($languageID) {        
        $ObjLanguage        = new languageModel();
        $langXML            = $ObjLanguage->loadLanguageXMLtoArray(__CORE_PUBLIC_COMMON_FRONTEND_PATH . '/' . __DIR_LANGUAGE . '/' . $this->ObjCommon->langArray[$languageID]['LanguageLCIDstring'] . '.xml');
        return $langXML['lblVatValue'];
    }    
    public function editAction() {
        $ObjOrder          = new OrderModel();
        $ObjShippingMethod = new ShippingmethodModel();
        $ObjShipment       = new ShipmentModel();
        $ObjUsers          = new UserModel();
        $shipmentID        = $this->getRequestValue('id');
        $languageIDs       = $this->ObjView->languageIDs;
        $ObjLanguage       = new languageModel();
        $currentLang       = $languageIDs['Current'];
        $history           = $this->getPreviousURL();
        if ($shipmentID < 1) {
            $this->setredirect("/shipping/shipped/");
        }
        if (isset($_POST['changeShippingStatus'])) {
            $posData            = $_POST;
            $posData['comment'] = $posData['CareerDetails'];
            $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
            $settingsTimeFormat = $this->getSettingValue("site_settings", "time_format");
            $orderItemIDs           = ($posData['orderItemIDArr']!='')?explode(",",$posData['orderItemIDArr']):'';
            $masterOrderID          = $posData['masterOrderID'];
            $orderLangIDs           = $ObjOrder->getOrderLanguageIDs('', $masterOrderID);
            $xmlLang = $this->ObjCommon->loadLanguageXml("",$orderLangIDs['Current']);
            $resProductOrderDetails = $ObjOrder->getProductOrderDetails($orderLangIDs,'',$orderItemIDs,$masterOrderID);		
            $ProductIDS="";
            foreach ($resProductOrderDetails as $key => $productOrderDetails) {
                ($key > 0) ? $sep = ',' : $sep = '';
                $productTitle .= $sep . $nxtline . $productOrderDetails['productTitle'];
		$productSms	.= $sep . $productOrderDetails['productTitle'];
		$ProductIDS .=$sep .$productOrderDetails['optionSKU'];
            }	            
            // Real time shipping creation
            if (isset($posData['realtimeCarrier']) && $posData['realtimeCarrier'] == 'Yes') {
                $posData['partnerName'] = '';
                $posData['trackingUrl'] = '';
                $paramsArray            = array(
                    'tableName' => 'shipping_methods',
                    'fieldName' => 'settingsGroupKey',
                    'conditionField' => 'settingsGroupID',
                    'condition' => '=',
                    'conditionValue' => $posData['sm_main'],
                    'conditionFieldType' => 'int'
                );
                $ObjCart                = new CartModel();
                $resshippingGateWayKey  = $ObjCart->getFieldValue($paramsArray);
                $shippingGateWayKey     = $resshippingGateWayKey['settingsGroupKey'];
                $ObjShippingLib         = new Shipping($shippingGateWayKey);
                $ObjShipping            = $ObjShippingLib->getShippingObject();
               /* if (!is_object($ObjShipping)) {
                    continue;
                } else {*/
                if(is_object($ObjShipping)){
                    if ((isset($posData['createPickup'])) && ($posData['createPickup'] == 'Yes')) {
                        $ObjCountry     = new CountryModel();
                        $ObjState       = new StateModel();
                        $shipmentOrigin = $ObjShipment->getShipmentOriginAddress($posData['shipmentID']);
                        $originAddress  = unserialize($shipmentOrigin);
                        if ($originAddress['businessProvince'] == '')
                            $originAddress['businessStateShortName'] = $ObjState->getStateShortNameByID($originAddress['businessState']);
                        else
                            $originAddress['businessStateShortName'] = $ObjState->getProvinceShortCode($originAddress['businessProvince']);
                        $originAddress['businessCountryShortName'] = $ObjCountry->getCountryCode($originAddress['businessCountry']);
                        $originAddress['grossWeight']              = $posData['grossWeight'];
                        $originAddress['pickupDate']               = $posData['pickupDate'];
                        $posData['pickup_created_time']            = 'NOW()';
                        $posData['pickupDate']                     = $this->convertDateForSQL($posData['pickupDate'], $settingsDateFormat);
                        $posData['pickup_closing_time']            = $this->convertDateForSQL($posData['pickupClosingTime'], $settingsTimeFormat);
                        $pickupResponseArray                       = $ObjShipping->createPickup($originAddress);
                        $posData['pickupData']                     = $pickupResponseArray;
                        if ($pickupResponseArray['successCode'] == 'FAILURE' || $pickupResponseArray['successCode'] == 'ERROR') {
                            $this->setMessage($pickupResponseArray['message'], "error");
                            $this->setRedirect();
                        } else {
                            $posData['shipmentStatus'] = 'Pickup';
                        }
                    } else {
                        $posData['createPickup']        = 'No';
                        $posData['pickup_created_time'] = '\'\'';
                        $posData['pickup_closing_time'] = '';
                        $posData['pickupDate']          = '';
                    }
                }
            } // Real time shipping creation END	// Non Real time shipping start
            $posData['packageType'] = '';
            $posData['dropOffType'] = '';
            if ($posData['sm_main'] == 'other')
                $posData['realtime_sm_services'] = '';
		$shipmentDetails = $ObjOrder->getShipmentDetails($shipmentID, $languageIDs);
		$shipAddress                        = unserialize($shipmentDetails['shippingAddress']);
		$posData['shippingPhone']                      = $shipAddress['shippingPhone'];	            
            if ((isset($posData['dispatchInfo'])) && ($posData['dispatchInfo'] == 'Yes')) {
                $posData['dispatchDate']    = $this->convertDateForSQL($posData['dispatchDate'], $settingsDateFormat);
                $posData['dispatchExpDate'] = $this->convertDateForSQL($posData['dispatchExpDate'], $settingsDateFormat);
                $posData['dispatchNotify']  = (isset($posData['dispatchNotify'])) ? $posData['dispatchNotify'] : 'No';
                $posData['shipmentStatus']  = 'Dispatched';
                //DISPATCHED SMS
                if($posData['shippingPhone']!='' && $posData['dispatchNotify']!='No'){
                    $ObjSmsTemplate            = new SmstemplateModel();
                    $messageBody                    = $ObjSmsTemplate->getSmsTempDetails('', $orderLangIDs,'sms_buyer_item_dispatch');

                    $message  =  $messageBody['smsTemplateContent'];
                    $trackingUrldesc="";
                    if($posData['dispatchExpDate']!='')
                    {
                        $dispatchExpDate = $xmlLang['msgDispatched1'].$posData['dispatchExpDate'].'.';
                    }	
                    if($posData['trackingUrl']!='')
                    {
                        $trackingUrldesc = $xmlLang['msgDispatched2'].$posData['trackingUrl'];
                    }				
                    //  sms body
                    $bodytag                = str_replace('(1)', $productSms, $messageBody['smsTemplateContent']);
                    $bodytag                = str_replace('(2)', $resProductOrderDetails[0]['orderNumber'], $bodytag);
                    $bodytag                = str_replace('(3)', $ProductIDS, $bodytag);
                    $bodytag                = str_replace('(4)', $dispatchExpDate, $bodytag);
                    $bodytag                = str_replace('(5)', $posData['trackingNumber'], $bodytag);
                    $bodytag                = str_replace('(6)', $trackingUrldesc, $bodytag);
                    //$msgKey = "(1),*,".$orderNumbers.",@,(2),*,".$orderPrice.",@,(3),*,".$link;			
                    $user_id=$this->getSettingValue('sms_settings', 'sms_username');
                    $password=$this->getSettingValue('sms_settings', 'sms_password');
//                    if (strpos($posData['shippingPhone'], "05") === 0){
//                        $userPhoneFull          =  '966'.ltrim($posData['shippingPhone'], '0');	
//                    }else{
//                        $userPhoneFull          = '91'.$posData['shippingPhone'];	
//                    }
                    $userPhoneFull=str_replace("-","",$posData['shippingPhone']);
                    $sms = new Sms($user_id, $password);
                    $result	=	$sms->setSms($bodytag,$userPhoneFull,'Normal',$msgKey);
                }                        
            } else {
                $posData['dispatchInfo']          = 'No';
                $posData['dispatchDate']          = '';
                $posData['dispatchExpDate']       = '';
                $posData['dispatchNotify']        = '';
                $posData['dispatchStatusDetails'] = '';
            }
            if ((isset($posData['deliveredInfo'])) && ($posData['deliveredInfo'] == 'Yes')) {
                $posData['deliveredDate']   = $this->convertDateForSQL($posData['deliveredDate'], $settingsDateFormat);
                $posData['deliveredNotify'] = (isset($posData['deliveredNotify'])) ? $posData['deliveredNotify'] : 'No';
                $posData['shipmentStatus']  = 'Delivered';
                if($posData['shippingPhone']!='' && $posData['deliveredNotify']!='No'){
                    $ObjSmsTemplate            = new SmstemplateModel();
                    $messageBody                    = $ObjSmsTemplate->getSmsTempDetails('', $orderLangIDs,'sms_buyer_item_deliver');
                    $dispatchExpDate ="";
                    if($posData['deliveredDate']!='')
                    {
                            $dispatchExpDate = $xmlLang['msgDeliver1'].$posData['deliveredDate'].'.';
                    }	

                    //  sms body
                    $bodytag                = str_replace('(1)', $productSms, $messageBody['smsTemplateContent']);
                    $bodytag                = str_replace('(3)', $resProductOrderDetails[0]['orderNumber'], $bodytag);
                    $bodytag                = str_replace('(2)', $ProductIDS, $bodytag);
                    $bodytag                = str_replace('(4)', $dispatchExpDate, $bodytag);
                    //$msgKey = "(1),*,".$orderNumbers.",@,(2),*,".$orderPrice.",@,(3),*,".$link;			
                    $user_id=$this->getSettingValue('sms_settings', 'sms_username');
                    $password=$this->getSettingValue('sms_settings', 'sms_password');
//                    if (strpos($posData['shippingPhone'], "05") === 0){
//                      $userPhoneFull          = '966'.ltrim($posData['shippingPhone'], '0');	
//                    }else{
//                      $userPhoneFull          = '91'.$posData['shippingPhone'];	
//                    }
                    $userPhoneFull=str_replace("-","",$posData['shippingPhone']);
                    $sms = new Sms($user_id, $password);
                    $result	=	$sms->setSms($bodytag,$userPhoneFull,'Normal',$msgKey);							
                }                                      
            } else {
                $posData['deliveredInfo']    = 'No';
                $posData['deliveredDate']    = NULL;
                $posData['shippedExpDate']   = NULL;
                $posData['deliveredNotify']  = '';
                $posData['deliveredComment'] = '';
            }
            // End non real time shipping
            $resUpdate = $ObjShipment->updateShipment($posData);
            if (isset($posData['deliveredNotify']) && $posData['deliveredNotify'] == 'Yes' || isset($posData['dispatchNotify']) && $posData['dispatchNotify'] == 'Yes') {
                /* Mail for user*/
                $ObjEmailtemplate       = new EmailtemplateModel();
                $productTitle           = '';
                $masterOrderID          = $posData['masterOrderID'];
                $orderLangIDs           = $ObjOrder->getOrderLanguageIDs('', $masterOrderID);
                $resProductOrderDetails = $ObjOrder->getProductOrderDetails($orderLangIDs, '', '', $masterOrderID);
                $billingAddress         = unserialize($resProductOrderDetails[0]['billingAddress']);
                $userLangID             = $ObjUsers->getUserDefaultLanguage($resProductOrderDetails[0]['userID']);
                if ($userLangID > 0) {
                    $languageIDs['Current'] = $userLangID;
                }
                //if($currentLang!=$languageIDs['Current']) {                       
                    $langXML                = $ObjLanguage->loadLanguageXMLtoArray(__CORE_PUBLIC_COMMON_FRONTEND_PATH . '/' . __DIR_LANGUAGE . '/' . $this->ObjCommon->langArray[$languageIDs['Current']]['LanguageLCIDstring'] . '.xml');
                    $lblComment             = $langXML['lblComment'];
                    $lblTrackingnumber      = $langXML['lblTrackingnumber'];
                    $lblCarrier             = $langXML['lblCarrier'];
                    $lblDelivered           = $langXML['lblDelivered'];
                    $lblShipmentcreated     = $langXML['lblShipmentcreated'];
                    $lblPickupCreated       = $langXML['lblPickupCreated'];
                    $lblDispatched          = $langXML['lblDispatched'];
                /*} else {
                    $lblComment             = $this->getLanguageValue("lblComment");
                    $lblTrackingnumber      = $this->getLanguageValue("lblTrackingnumber");
                    $lblCarrier             = $this->getLanguageValue("lblCarrier");
                    $lblDelivered           = $this->getLanguageValue("lblDelivered");
                    $lblShipmentcreated     = $this->getLanguageValue("lblShipmentcreated");
                    $lblPickupCreated       = $this->getLanguageValue("lblPickupCreated");
                    $lblDispatched          = $this->getLanguageValue("lblDispatched");

                }*/
                $emailbody   = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-order-notify');
                $from        = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $siteName    = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl     = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo = $this->getSettingValue('company_information', 'company_logo');
                $companyName = $this->getSettingValue('company_information', 'company_name');
                $subject     = $emailbody['emailSubject'];
                foreach ($resProductOrderDetails as $key => $productOrderDetails) {
                    ($key > 0) ? $sep = ',' : $sep = '';
                    $nxtline = "<br />";
                    $productTitle .= $sep . $nxtline . $productOrderDetails['productTitle'];
                }
                $posData['shipmentCarrier'] = '';
                $comment                    = '';
                if ($posData['comment'] != '' || $posData['trackingNumber'] != '' || $posData['shipmentCarrier'] != '') {
                    $comment .= "<table>";
                    if ($posData['comment'] != '') {
                        $comment .= "<tr><td>" . $lblComment . "</td><td>: " . $posData['comment'] . "</td></tr>";
                    }
                    if ($posData['trackingNumber'] != '') {
                        $comment .= "<tr><td>" .$lblTrackingnumber . "</td><td>: " . $posData['trackingNumber'] . "</td></tr>";
                    }
                    if ($posData['shipmentCarrier'] != '') {
                        $comment .= "<tr><td>" . $lblCarrier . "</td><td>: " . $posData['shipmentCarrier'] . "</td></tr>";
                    }
                    $comment .= "</table>";
                }
                $name = $billingAddress['billingFirstName'] . $billingAddress['billingLastName'];
                if ($posData['shipmentStatus'] == 'Delivered') {
                    $shipmentCurrentStatus = $lblDelivered;
                } else if ($posData['shipmentStatus'] == 'Shipment') {
                    $shipmentCurrentStatus = $lblShipmentcreated;
                } else if ($posData['shipmentStatus'] == 'PickUp') {
                    $shipmentCurrentStatus = $lblPickupCreated;
                } else if ($posData['shipmentStatus'] == 'Dispatched') {
                    $shipmentCurrentStatus = $lblDispatched;
                }
                $bodytag = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                $bodytag = str_replace('{$productTitle}', $productTitle, $bodytag);
                $bodytag = str_replace('{$comment}', $comment, $bodytag);
                $bodytag = str_replace('{$userName}', $name, $bodytag);
                $bodytag = str_replace('{$status}', $shipmentCurrentStatus, $bodytag);
                $bodytag = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body                          = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                $mailSettings                  = $this->getSettingValue('mail_settings');
                $mailSettings['smtp_password'] = $this->encryptDecrypt("decrypt", $mailSettings['smtp_password']);
                $emailID                       = $billingAddress['billingEmail'];
                $ObjMail                       = new Mail(isset($mailSettings) ? $mailSettings : '');
                $ObjMail->IsHTML();
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                }
            }
            if ($resUpdate) {
                $this->setMessage("language.msgShipmentUpdated", "success");
                $this->setredirect("/shipment/edit/id/" . $posData['shipmentID'] . "/");
            }
        }
        $shipmentDetails = $ObjOrder->getShipmentDetails($shipmentID, $languageIDs);
        if (empty($shipmentDetails['items'])) {
            $this->setredirect("/shipping/shipped/");
        }
        $billingAddress                     = unserialize($shipmentDetails['billingAddress']);
        $shipmentDetails['billingAddress']  = array_values(array_slice(unserialize($shipmentDetails['billingAddress']), 0, -2));
        $shipAddress                        = unserialize($shipmentDetails['shippingAddress']);
        $shippingPhone                      = $shipAddress['shippingPhone'];
        unset($shipAddress['shippingPhone']);
        //unset($shipAddress['shippingProvince']);
        $shipmentDetails['shippingAddress'] = array_values($shipAddress);
        $shipmentDetails['extraData']       = unserialize($shipmentDetails['extraData']);
        if (count($shipmentDetails['items']) > 0) {
            foreach ($shipmentDetails['items'] as $key => $items) {
                $extraStr                                = unserialize($items['extra']);
                $shipmentDetails['items'][$key]['extra'] = $extraStr;
            }
        }
        $this->ObjView->assign('resSmServices', $ObjShippingMethod->listLogisticPartners());
        $this->ObjView->assign("shipmentDetails", $shipmentDetails);
        $this->ObjView->assign("shippingPhone", $shippingPhone);
        $this->ObjView->assign('showprivilege', $this->ObjCommon->hasPrivilege('order/show/'));
        $this->ObjView->assign("billingAddress", $billingAddress);
        $this->ObjView->assign("shipmentID", $shipmentID);
        $this->ObjView->assign("history", $history);
        $this->ObjView->assign("labelPrivilege", $this->ObjCommon->hasPrivilege('shipment/label/'));
        $this->ObjView->display('ShipmentEdit.tpl');
    }
    public function checkTrackingNumberRequired() {
        if (isset($_POST['dispatchInfo']) || isset($_POST['shippedInfo'])) {
            if ($_POST['trackingNumber'] == '')
                return false;
            else
                return true;
        } else {
            return true;
        }
    }
    public function createmanifestAction(){
        $ObjBusiness        = new BusinessModel();
        $ObjOrder           = new OrderModel();
        $ObjShippingMethod  = new ShippingmethodModel();
        $ObjShipment        = new ShipmentModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $resBusiness        = $ObjBusiness->listBusinessInOptions($languageIDs);
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $timeFormat = $this->getSettingValue('site_settings', 'time_format');
        $resProductTypes = $ObjOrder->getProductTypeOfProducts('product_product');
        $productTypeKey = 'product_product';
        $productType = $resProductTypes[0]['productTypeID'];
        $orderLink = '';
        $fromDate = '';
        $toDate = '';
        $link = '';
        //CREATE MANIFEST
        if (isset($_POST['CreateManifest'])) {
//            if ($_POST['logisticpartner'] == 30) {
//                if (count($_POST['shipmentIDs']) > 0) {
//                    $APIresult = $this->ecomExpressManifestAPICall($_POST);
//                    //echo "<pre>";print_r($APIresult);exit;
//                    if ($APIresult['shipments'][0]['success'] == 'true') {
//                        //Create Manifest
//                        $ObjShipment->createManifest($_POST);
//                        $this->setMessage("language.msgShipmentManifestCreated", "success");
//                        $this->setredirect();
//                    } else {
//                        //Cancel Manifest
//                        $reason = $APIresult['shipments'][0]['reason'];
//                        $this->setMessage($reason, "error");
//                        $this->setredirect();
//                    }
//                 }
//             }else if ($_POST['logisticpartner'] == 32) {
//                 if(count($_POST['shipmentIDs'])>0){
//                    $APIresult = $this->delhiveryManifestAPICall($_POST);
//                    //echo "<pre>";print_r($APIresult);exit;
//                    if ($APIresult['success'] == 'true') {
//                        //Create Manifest
//                        $ObjShipment->createManifest($_POST);
//                        $this->setMessage("language.msgShipmentManifestCreated", "success");
//                        $this->setredirect();
//                    } else {
//                        //Cancel Manifest
//                        $reason = $APIresult['packages'][0]['remarks'][0];
//                        $this->setMessage($reason, "error");
//                        $this->setredirect();
//                    }
//                 }
//             }else{
//                $ObjShipment->createManifest($_POST);
//                $this->setMessage("language.msgShipmentManifestCreated", "success");
//                $this->setredirect();
//             }
                $ObjShipment->createManifest($_POST,$this->ObjCommon->manageUserID);
                $this->setMessage("language.msgShipmentManifestCreated", "success");
                $this->setredirect();
         }
        //search
        if (isset($_POST['submitSearch'])) {
            $orderNumber = trim($this->encodeUrlString($_POST['orderNumber']));
            $shippingSetting = ($_POST['shippingSetting'] == 'business') ? 'merchant' : $_POST['shippingSetting'];
            $date = $_POST['date'];
            if ($date) {
                $searchDates = explode(' - ', $date);
                $fromDate = $searchDates[0];
                if (isset($searchDates[1])) {
                    $toDate = $searchDates[1];
                }
            }
            $fromDate = trim($fromDate);
            $toDate = trim($toDate);
            $searchBusiness = isset($_POST['searchBusiness']) ? $_POST['searchBusiness'] : '';
            if ($searchBusiness != '') {
                $searchBusiness = implode(":", $searchBusiness);
            }
            $orderStatus = $_POST['orderStatus'];
            $productKey = isset($_POST['productKey']) ? trim($this->encodeUrlString($_POST['productKey'])) : '';
            $certificateName = trim($this->encodeUrlString($_POST['certificateName']));
            $paymentStatus = $_POST['paymentStatus'];
            $shippingStatus = isset($_POST['shippingStatus']) ? $_POST['shippingStatus'] : '';
            $link .= (($orderNumber != "") ? "orderid/" . $orderNumber . "/" : "");
            $link .= (($fromDate != "") ? "from/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($toDate != "") ? "to/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($searchBusiness != "") ? "business/" . $searchBusiness . "/" : "");
            $link .= (($orderStatus != "") ? "status/" . $orderStatus . "/" : "");
            $link .= (($productKey != "") ? "productid/" . $productKey . "/" : "");
            $link .= (($certificateName != "") ? "cname/" . $certificateName . "/" : "");
            $link .= (($paymentStatus != "") ? "pymntstatus/" . $paymentStatus . "/" : "");
            $link .= (($shippingStatus != "" && $shippingStatus != "Any") ? "shippingStatus/" . $shippingStatus . "/" : "");
            $link .= (($shippingSetting != "") ? "shippingby/" . $shippingSetting . "/" : "");
            $link .= (($_POST['sm_main'] != "") ? "sm/" . $_POST['sm_main'] . "/" : "");
            $link .= (($_POST['realtime_sm_services'] != "") ? "stype/" . $_POST['realtime_sm_services'] . "/" : "");
            $link .= (($_POST['trackingNumber'] != "") ? "track/" . $_POST['trackingNumber'] . "/" : "");
            $this->setRedirect('/shipment/createmanifest/' . $link);
        }
        //search parameters
        $shippingSetting = ($this->getRequestValue('shippingby') == 'merchant') ? 'business' : $this->getRequestValue('shippingby');
        $orderNumber = $this->decodeUrlString($this->getRequestValue('orderid'));
        $fromDate = $this->urlDate($this->getRequestValue('from'), 'get', $settingsDateFormat);
        $toDate = $this->urlDate($this->getRequestValue('to'), 'get', $settingsDateFormat);
        $searchBusiness = $this->getRequestValue('business');
        $orderStatus = $this->getRequestValue('status');
        $productKey = $this->decodeUrlString($this->getRequestValue('productid'));
        $certificateName = $this->decodeUrlString($this->getRequestValue('cname'));
        $paymentStatus = $this->getRequestValue('pymntstatus');
        $shippingStatus = $this->getRequestValue('shippingStatus');
        $shippingMethod = $this->getRequestValue('sm');
        $shippingServiceType = $this->getRequestValue('stype');
        $trackingNumber = $this->getRequestValue('track');
        $sortByOption = $this->getRequestValue("sortby");
        $sortByOrder = $this->getRequestValue("orderby");
        // sort by
        if ($sortByOption == 'sorderid' && $sortByOrder == "asc") {
            $sortByOrderID = "desc";
        } else {
            $sortByOrderID = "asc";
        }
        if ($sortByOption == 'sproductid' && $sortByOrder == "asc") {
            $sortByProductKey = "desc";
        } else {
            $sortByProductKey = "asc";
        }
        if ($sortByOption == 'ssdate' && $sortByOrder == "asc") {
            $sortByDate = "desc";
        } else {
            $sortByDate = "asc";
        }
        if ($sortByOption == 'sshipmentid' && $sortByOrder == "asc") {
            $sortByShipmentID = "desc";
        } else {
            $sortByShipmentID = "asc";
        }
        if ($sortByOption == '') {
            $sortByOption = 'sshipmentid';
        }
        $normallink = "";
        if ($fromDate != "")
            $normallink .= "from/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/";
        if ($toDate != "")
            $normallink .= "to/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        if ($searchBusiness != "")
            $normallink .= "business/" . $searchBusiness . "/";
        if ($orderStatus != "")
            $normallink .= "status/" . $orderStatus . "/";
        if ($productKey != "")
            $normallink .= "productid/" . $this->encodeUrlString($productKey) . "/";
        if ($certificateName != "")
            $normallink .= "cname/" . $this->encodeUrlString($certificateName) . "/";
        if ($paymentStatus != "")
            $normallink .= "pymntstatus/" . $paymentStatus . "/";
        if ($productType != "")
            $normallink .= "producttype/" . $productType . "/";
        if ($orderNumber != "")
            $normallink .= "orderid/" . $this->encodeUrlString($orderNumber) . "/";
        if ($orderNumber != "")
            $orderLink .= "orderid/" . $orderNumber . "/";
        if ($shippingStatus != "")
            $normallink .= "shippingStatus/" . $shippingStatus . "/";
        if ($shippingMethod != "")
            $normallink .= "sm/" . $shippingMethod . "/";
        if ($shippingServiceType != "")
            $normallink .= "stype/" . $shippingServiceType . "/";
        if ($trackingNumber != "")
            $normallink .= "track/" . $trackingNumber . "/";
        $normallink .= "list";
        $date = $fromDate;
        if ($toDate) {
            $date .= " - " . $toDate;
        }
        if ($fromDate && $toDate == '') {
            $toDate = $fromDate;
        }
        $this->ObjView->assign("date", $date);
        $this->ObjView->assign("orderNumber", $orderNumber);
        $this->ObjView->assign("normallink", $normallink);
        $this->ObjView->assign("fromDate", $fromDate);
        $this->ObjView->assign("toDate", $toDate);
        $this->ObjView->assign("orderStatus", $orderStatus);
        $this->ObjView->assign("productKey", $productKey);
        $this->ObjView->assign("productType", $productType);
        $this->ObjView->assign("orderLink", $orderLink);
        $this->ObjView->assign("certificateName", $certificateName);
        $this->ObjView->assign("paymentStatus", $paymentStatus);
        $this->ObjView->assign("shippingStatus", $shippingStatus);
        $this->ObjView->assign("selectedBusiness", explode(":", $searchBusiness));
        $this->ObjView->assign("business", $searchBusiness);
        $this->ObjView->assign("date_format", $settingsDateFormat);
        $this->ObjView->assign("time_format", $timeFormat);
        $this->ObjView->assign('sortByOrder', $sortByOrder);
        $this->ObjView->assign('sortByOption', $sortByOption);
        $this->ObjView->assign('sortByOrderID', $sortByOrderID);
        $this->ObjView->assign('sortByProductKey', $sortByProductKey);
        $this->ObjView->assign('smGroupID', ($shippingMethod != '') ? $shippingMethod : '');
        $this->ObjView->assign('selectedServiceType', $shippingServiceType);
        $this->ObjView->assign('trackingNumber', $trackingNumber);
        $this->ObjView->assign('sortByDate', $sortByDate);
        $this->ObjView->assign('sortByShipmentID', $sortByShipmentID);
        $this->ObjView->assign('shippingSetting', $shippingSetting);
        if (!$sortByOption) {
            $this->ObjView->assign('sortByOption', 'sshipmentid');
            $this->ObjView->assign('sortByOrder', 'desc');
        }
        // pagination settings
        if ($shippingStatus == '') {
            $searchShippingStatus = 'Shipped';
        } else {
            $searchShippingStatus = $shippingStatus;
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params['languageIDs'] = $this->ObjView->languageIDs;
        $params['limitFrom'] = $limitFrom;
        $params['limitTo'] = $limitTo;
        $params['orderNumber'] = $orderNumber;
        $params['fromDate'] = $this->convertDateForSQL($fromDate, $settingsDateFormat);
        $params['toDate'] = $this->convertDateForSQL($toDate, $settingsDateFormat);
        $params['searchBusiness'] = isset($searchBusiness) ? $searchBusiness : '';
        $searchBusiness;
        $params['orderStatus'] = isset($orderStatus) ? $orderStatus : '';
        $orderStatus;
        $params['productKey'] = isset($productKey) ? $productKey : '';
        $productKey;
        $params['searchProductTypes'] = isset($searchProductTypes) ? $searchProductTypes : '';
        $params['certificateName'] = isset($certificateName) ? $certificateName : '';
        $certificateName;
        $params['paymentStatus'] = isset($paymentStatus) ? $paymentStatus : '';
        $paymentStatus;
        $params['userID'] = isset($userID) ? $userID : '';
        $params['orderAs'] = isset($sortByOrder) ? $sortByOrder : '';
        $sortByOrder;
        $params['sortBy'] = isset($sortByOption) ? $sortByOption : '';
        $sortByOption;
        $params['shipmentStatus'] = isset($searchShippingStatus) ? $searchShippingStatus : '';
        $searchShippingStatus;
        $params['productTypeKey'] = isset($productTypeKey) ? $productTypeKey : '';
        $productTypeKey;
        $params['groupBy'] = isset($groupBy) ? $groupBy : '';
        $params['orderItemID'] = isset($orderItemID) ? $orderItemID : '';
        $orderItemID;
        $params['masterOrderID'] = isset($masterOrderID) ? $masterOrderID : '';
        $masterOrderID;
        $params['shippingSetting'] = isset($shippingSetting) ? $shippingSetting : '';
        $shippingSetting;
        $params['shippingMethod'] = isset($shippingMethod) ? $shippingMethod : '';
        $params['shippingServiceType'] = isset($shippingServiceType) ? $shippingServiceType : '';
        $params['trackingNumber'] = isset($trackingNumber) ? $trackingNumber : '';
        $params['manifest'] = 'No';
        $resNotShippedOrders = $ObjOrder->listShipments($params);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign("resNotShippedOrders", $resNotShippedOrders);
        $resLogisticPartners = $ObjShippingMethod->listLogisticPartnersnew();
        $selectAnyArray = array(
            0 => '',
            'settingsGroupID' => '',
            1 => 'Select',
            'settingsGroupXmlLabel' => 'Select'
        );
        array_unshift($resLogisticPartners, $selectAnyArray);
        //echo '<pre>';print_r($resLogisticPartners);exit;
        $this->ObjView->assign('resSmServices', $resLogisticPartners);
        $this->ObjView->assign("resBusiness", $resBusiness);
        $this->ObjView->assign("labelPrivilege", $this->ObjCommon->hasPrivilege('shipment/label/'));
        $this->ObjView->assign("orderShowprivilage", $this->ObjCommon->hasPrivilege('order/show/'));
        $this->ObjView->assign("shipmentShowPrivilege", $this->ObjCommon->hasPrivilege('shipment/show/'));
        $this->ObjView->assign("shipmentEditPrivilege", $this->ObjCommon->hasPrivilege('shipment/edit/'));
        $this->ObjView->assign("showUserPrivilege", $this->ObjCommon->hasPrivilege('user/show/'));
        $this->ObjView->display('CreateManifest.tpl');
    }

    public function manifestsAction() {
        $ObjShipment = new ShipmentModel();
        $ObjShippingMethod = new ShippingmethodModel();
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        //search
        if (isset($_POST['submitSearch'])) {
            $date = $_POST['date'];
            if ($date) {
                $searchDates = explode(' - ', $date);
                $fromDate = $searchDates[0];
                if (isset($searchDates[1])) {
                    $toDate = $searchDates[1];
                }
            }
            $fromDate = trim($fromDate);
            $toDate = trim($toDate);

            $link .= (($fromDate != "") ? "from/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($toDate != "") ? "to/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($_POST['manifestNumber'] != "") ? "smno/" . $this->encodeUrlString($_POST['manifestNumber']) . "/" : "");
            $link .= (($_POST['sm_main'] != "") ? "sm/" . $_POST['sm_main'] . "/" : "");
            $this->setRedirect('/shipment/manifests/' . $link);
        }
        //search parameters
        $fromDate = $this->urlDate($this->getRequestValue('from'), 'get', $settingsDateFormat);
        $toDate = $this->urlDate($this->getRequestValue('to'), 'get', $settingsDateFormat);
        $smno = $this->decodeUrlString($this->getRequestValue('smno'));
        $shippingMethod = $this->getRequestValue('sm');
        $date = $fromDate;
        if ($toDate) {
            $date .= " - " . $toDate;
        }
        if ($fromDate && $toDate == '') {
            $toDate = $fromDate;
        }
        $this->ObjView->assign("date", $date);
        $normallink = "";
        if ($fromDate != "")
            $normallink .= "from/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/";
        if ($toDate != "")
            $normallink .= "to/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        if ($smno != "")
            $normallink .= "smno/" . $smno . "/";
        if ($shippingMethod != "")
            $normallink .= "sm/" . $shippingMethod . "/";


        $normallink .= "list";
        $date = $fromDate;
        if ($toDate) {
            $date .= " - " . $toDate;
        }
        if ($fromDate && $toDate == '') {
            $toDate = $fromDate;
        }
        $this->ObjView->assign("normallink", $normallink);
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params['limitFrom'] = $limitFrom;
        $params['limitTo'] = $limitTo;
        $params['fromDate'] = $this->convertDateForSQL($fromDate, $settingsDateFormat);
        $params['toDate'] = $this->convertDateForSQL($toDate, $settingsDateFormat);
        $params['shippingMethod'] = isset($shippingMethod) ? $shippingMethod : 'other';
        $params['smno'] = isset($smno) ? $smno : '';
        $this->ObjView->assign('smGroupID', ($shippingMethod != '') ? $shippingMethod : 'other');
        $manifests = $ObjShipment->listManifests($params);
        $this->ObjView->assign("resManifests", $manifests);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $resLogisticPartners = $ObjShippingMethod->listLogisticPartnersnew();
        $selectAnyArray = array(
            0 => '',
            'settingsGroupID' => '',
            1 => 'Select',
            'settingsGroupXmlLabel' => 'Select'
        );
        array_unshift($resLogisticPartners, $selectAnyArray);
        //echo '<pre>';print_r($resLogisticPartners);exit;
        $this->ObjView->assign('resSmServices', $resLogisticPartners);
        $this->ObjView->display('Manifests.tpl');
    }

    public function downloadAction() {
        $id = $this->getRequestValue('id');
        $ObjShipment = new ShipmentModel();
        	$ObjState = new StateModel();
                $ObjCountry = new CountryModel();
                   $languageIDs        = $this->ObjView->languageIDs;
        define('CODE128A_START_BASE', 103);
        define('CODE128B_START_BASE', 104);
        define('CODE128C_START_BASE', 105);
        define('STOP', 106);
        $ObjBar = new BarcodeModel();
        $resDet = $ObjShipment->getManifestDetailsForPDF($id);  
    // print_r($resDet);exit;
        $logistic = ($resDet['logisticPartner'] != '') ? $resDet['logisticPartner'] : $resDet['carrier'];
        $siteUrl = $this->getSettingValue('site_settings', 'global_http_url');
        $siteUrl = rtrim($siteUrl, '/') . '/';
        $pdfbody = '<table align="center" border="0" cellpadding="0" cellspacing="0" style="font-family:Arial, Helvetica, sans-serif;font-size:0.813em;font-weight:normal;" width="100%">
	<tbody>

		<tr>
			<td align="left" valign="top">
			<table align="center" border="1" cellpadding="5" cellspacing="0" width="100%" style="font-size9.5pt;">
				<tbody>
					<tr>
                        <td align="center">SNO</td>
                        <td align="center">Order_No</td>
                        <td align="center">Shipping Method</td>
                        <td align="center">AWB_No</td>
                        <td align="center"><p>N0_of_<br>Pieces</p></td>
                        <td align="center">Customer_Name</td>
                        <td align="center">Shipping_Add1</td>
                        <td align="center">Shipping_Add2</td>
                        <td align="center">Shipping_City</td>
                        <td align="center">Shipping_State</td>
                        <td align="center">Shipping_Zip</td>
                        <td align="center">Shipping_Mobile<br />No</td>
                        <td align="center">VALUE</td>
					</tr>
                                        ';
        foreach ($resDet['shipments'] as $shipment) {
            $shipAddress = unserialize($shipment['shipment_destination_address']);
            $shippingFname = $shipAddress['shippingFname'];
            $shippingPhone = $shipAddress['shippingPhone'];
            $shippingCity  = $shipAddress['shippingCity'];
            $shippingState  = $shipAddress['shippingState'];
            $shippingZip = $shipAddress['shippingZip'];
            $shippingAddress1 = $shipAddress['shippingAddress'];
           // unset($shipAddress['shippingPhone']);
            //unset($shipAddress['shippingProvince']);
            $shippingAddress = array_values($shipAddress);
            $countryName=    $ObjCountry->getCountryNameByID($shippingAddress[7], $languageIDs);
            $stateName =  $ObjState->getStateShortNameByID($shippingState);

              if($shipment['revisedOrderID']>0 ){
                  $declared = $shipment['revisedOrderTotalAmount'];
              } else {
                  $declared = $shipment['orderTotalAmount'];
              }
              //COD
              if($shipment['paymentSettingsGroupID'] == 18){
                    $collectable = $shipment['orderTotalAmount'];
                    if($shipment['revisedOrderID']>0 ){
                        $collectable = $shipment['revisedOrderTotalAmount'];
                    }
              } else {
                  if($shipment['paymentStatus']=='Received'){
                      $collectable = 0;
                  } else if($shipment['paymentStatus']!='Received' && $shipment['excessAmount']>0){
                      $collectable = $shipment['excessAmount'];
                  } 
              }
            $mode = ($shipment['paymentSettingsGroupID'] == 18) ? 'COD' : 'NON COD';
            if ($shipment['trackingNumber'] != '') {
                $img = $ObjBar->generate(stripslashes($shipment['trackingNumber']));        
                ob_start();
                imagepng($img);
                //Get the image from the output buffer
                $output_img = ob_get_clean();
                file_put_contents(__CORE_PUBLIC_PATH . '/uploads/temp/' . $shipment['trackingNumber'] . '.png', $output_img);
            }
            $pdfbody .= '			<tr>
						<td align="center">' . $resDet['manifestNumber'] . '</td>
						<td align="center">' . $shipment['orderNumber'] . '</td>
                        <td align="center">' . $shipment['shippingMethod'] . '</td>
                        <td align="center">' . $shipment['trackingNumber'] . '</td>
                        <td align="center">' .  count($resDet['shipments']) . '</td>
                        <td align="center">' . $shippingFname . '</td>
                              <td align="center">' . $shippingAddress[2] . ', ' . $shippingAddress[3] . '</td>
					 <td align="center"></td> 	
						
                                                <td align="center">' . $shippingCity . '</td>
                                                <td>'.$stateName.'</td>
                                                <td align="center">' .$shippingZip . '</td>
                                                <td align="center">' . $shippingPhone . '</td>
                                               
                                                
                                                
                                                <td align="center">' . round($declared, 2) . '</td>';
            $pdfbody .= '</tr> ';
        }
        $pdfbody .= '		</tbody>
			</table>
			</td>
		</tr>
	</tbody>
</table>';
        //<td align="center">' . round($declared, 2) . '</td>
        // echo $pdfbody;exit;
        // PDF
         $pdfLib = new Pdf();
        $l      = isset($l) ? $l : '';
        ob_end_clean();
        $pdf = new TCPDF('L', PDF_UNIT, array(  200,  325), true, 'UTF-8', false);
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('');
        $pdf->SetTitle('');
        $pdf->SetSubject('');
        $pdf->SetKeywords('');
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->setLanguageArray($l);
        // add a page
        $pdf->AddPage();       
        
        // output the HTML content			
        $pdf->WriteHTML($pdfbody);
        $pdf->Output($resDet['manifestNumber'] . ".pdf", 'D');
        exit;
    }
}