<?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: ShippingmethodController.php, v 1.0 2012/12/18 14:00:00
//
class ShippingmethodController extends Controller {
    public function indexAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        //change status
        if (isset($_POST['changeStatus'])) {
            if (count($_POST['checkSmgIDs']) > 0) {
                $changestatus = $ObjShippingMethod->changeShippingMethodStatus($_POST);
                if ($changestatus) {
                    $this->setMessage("language.msgShippingMethodStatusUpdated", "success");
                }
                $this->setRedirect();
            }
        }
        $resShippingMethods = $ObjShippingMethod->listShippingMethods();
        $this->ObjView->assign('resShippingMethods', $resShippingMethods);
        //Privilege
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('shippingmethod/edit/'));
        $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('shippingmethod/show/'));
        $this->ObjView->assign("showShippingServicePrivilege", $this->ObjCommon->hasPrivilege('shippingmethod/options/'));
        //Privilege
        $this->ObjView->display('ShippingMethodsList.tpl');
    }
    public function showAction() {
        $smGroupID         = $this->getRequestValue('id');
        $ObjShippingMethod = new ShippingmethodModel();
        //get shipping method settings
        $resSmSettings     = $ObjShippingMethod->listSmSettingsByGroupId($smGroupID);
        //get shipping method group details
        $resSmGroup        = $ObjShippingMethod->getShippingMethodGroupDetails($smGroupID);
        $smGroupStatus     = $resSmGroup['settingsGroupStatus'];
        $smGroupLabel      = $resSmGroup['settingsGroupXmlLabel'];
        if (empty($resSmSettings)) {
            $this->setRedirect("/shippingmethod/");
        }
        $previousURL = $this->getPreviousURL();
        $this->ObjView->assign('previousURL', $previousURL);
        $this->ObjView->assign('smGroupID', $smGroupID);
        $this->ObjView->assign('smGroupStatus', $smGroupStatus);
        $this->ObjView->assign('smGroupLabel', $smGroupLabel);
        $this->ObjView->assign('resSmSettings', $resSmSettings);
        $this->ObjView->display('ShippingMethodView.tpl');
    }
    //EDIT SHIPPING METHOD SETTINGS
    public function editAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        $smGroupID         = $this->getRequestValue('id');
        //Get details in edit mode
        $resSmSettings     = $ObjShippingMethod->listSmSettingsByGroupId($smGroupID);
        $smGroupDetails    = $ObjShippingMethod->getShippingMethodGroupDetails($smGroupID);
        if (empty($resSmSettings)) {
            $this->setRedirect("/shippingmethod/");
        }
        if ($this->ObjForm->isValid('formShippingMethod', 'submitSms')) {
            //if(isset($_POST['submitSms'])){			
            $smUpdate = $ObjShippingMethod->saveSmSettingsDetails($_POST, $smGroupID);
            $this->setMessage("language.msgShippingMethodUpdated", "success");
            $this->setRedirect("/shippingmethod/");
        }
        //Assign links for cancel button
        $previousURL = $this->getPreviousURL();
        $this->ObjView->assign('previousURL', $previousURL);
        $this->ObjView->assign('smGroupID', $smGroupID);
        $this->ObjView->assign('resSmSettings', isset($resSmSettings) ? $resSmSettings : '');
        $this->ObjView->assign('smGroupLabel', $smGroupDetails['settingsGroupXmlLabel']);
        $this->ObjView->display('ShippingMethodEdit.tpl');
    }
    //TO SET PRIORITY
    public function ajaxPriorityAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        $smGroupIDs        = $_POST['smGroupIDs'];
        $smGroupIDs        = explode("|", $smGroupIDs);
        //update priority
        for ($i = 0; $i < count($smGroupIDs); $i++) {
            if ($smGroupIDs[$i] > 0)
                $respUpdate = $ObjShippingMethod->updateShippingMethodPriority($smGroupIDs[$i], $i);
        }
    }
    public function ajaxStatusAction() {
        $ObjShippingMethod     = new ShippingmethodModel();
        $_POST['checkSmgIDs']  = array(
            $_POST['id']
        );
        $_POST['changeStatus'] = isset($_POST['newstatus']) ? $_POST['newstatus'] : "";
        if (isset($_POST['defaultStatus'])) {
            $changestatus = $ObjShippingMethod->changeShippingMethodDefault($_POST['id'], $_POST['defaultStatus']);
        } else {
            $changestatus = $ObjShippingMethod->changeShippingMethodStatus($_POST);
        }
        $this->setMessage("language.msgShippingServiceStatusUpdated", "success");
        if ($changestatus)
            echo 1;
    }
    //Assign shipping services
     public function assignshippingAction() {
         $ObjShippingMethod		= new ShippingmethodModel();
         $smGroupID			= $this->getRequestValue('id');
         if($smGroupID>0) {
             $serviceData            = array();
             $sqlService		= "SELECT * FROM ".DB_PREFIX."shipping_methods_settings WHERE settingsGroupID='".$smGroupID."'";             
             $resServices		= $this->ObjDatabase->readValues($sqlService);
             foreach($resServices as $service) {				
                     $serviceData[$service['settingsGroupID']][$service['settingKey']]=  $service['settingValue'];
                     $serviceData[$service['settingsGroupID']]['settingsGroupKey']    =  $service['settingsGroupKey'];
             }             
             $getProducts               = $ObjShippingMethod->getAllProducts();

             if(!empty($getProducts)) {
                 foreach($getProducts as $productDet) {                        
                    if ($productDet['productID'] > 0) {       
                         $sqlSel                = "SELECT shippingtoproductID FROM " . DB_PREFIX . "shipping_to_product
                                                 WHERE productID = '" . $productDet['productID'] . "' AND shippingServiceID = '".$smGroupID."' and status='A'";
                         $res                   = $this->ObjDatabase->readValue($sqlSel);         
                         $shippingtoproductID   = (!empty($res['shippingtoproductID']))?$res['shippingtoproductID']:0;
                         if ($shippingtoproductID<=0) { 
                             $insertSql     =   "INSERT INTO `".DB_PREFIX."shipping_to_product`(`productID`, `shippingServiceID`,
                                             `baseCharge`,`maxQtyPerShipping`,`taxClassID`,								
                                             `status`,`AssignedDate`,`ModifiedDate`) VALUES";
                         } else {
                             $insertSql     = "update `".DB_PREFIX."shipping_to_product` set ";
                             $delSql = "Delete from ".DB_PREFIX."product_to_shipping_deliveryzone where shippingtoproductID ='".$shippingtoproductID."'";
                             $this->ObjDatabase->setQuery($delSql);	
                         }

                         foreach($serviceData as $id=>$data){					
                             if (strpos($data['settingsGroupKey'],'free_') !== false) {
                                 $data['qty_upto']=$data['free_qty_upto'];
                                 $data['taxClassID']=0;
                             }
                             elseif(strpos($data['settingsGroupKey'],'flat_')!== false)
                             {
                                 $data['qty_upto']=0;
                                 $data['taxClassID']=$data['flat_tax_class'];
                             }
                             if ($shippingtoproductID<=0) { 
                                 $valueSql="('".$productDet['productID']."',												
                                             '".$this->escape($id)."',												 
                                             '". (isset($data['flat_fixed_charge'])?$this->escape($data['flat_fixed_charge']):'') ."',												   
                                             '".$this->escape($data['qty_upto'])."',
                                             '".$this->escape($data['taxClassID'])."',	
                                             'A',
                                             '".date("Y-m-d H:i:s")."',
                                             '".date("Y-m-d H:i:s")."')";

                                 $this->ObjDatabase->setQuery($insertSql.$valueSql);					
                                 $shippingID	= $this->ObjDatabase->getInsertId();
                             } else {
                                 $valueSql=" productID = '".$productDet['productID']."',									 
                                             baseCharge = '". (isset($data['flat_fixed_charge'])?$this->escape($data['flat_fixed_charge']):'') ."',												   
                                             maxQtyPerShipping = '".$this->escape($data['qty_upto'])."',
                                             taxClassID = '".$this->escape($data['taxClassID'])."',	                                                
                                             ModifiedDate = '".date("Y-m-d H:i:s")."'
                                             where shippingtoproductID = '".$shippingtoproductID."' and shippingServiceID='".$smGroupID."'";
                                 $shippingID = $shippingtoproductID;                                    
                                 $this->ObjDatabase->setQuery($insertSql.$valueSql);	

                             }

                             if($data['delivery_zones']!='')
                             {
                                     $dzones=explode('~*',$data['delivery_zones']);
                                     foreach($dzones as $zone) {
                                             $insertDeliveryzonesql = "INSERT INTO ".DB_PREFIX."product_to_shipping_deliveryzone 
                                             (deliveryZoneID, 
                                              shippingtoproductID
                                             ) 
                                             VALUES('".$zone."',
                                             '".$shippingID."')";
                                             $this->ObjDatabase->setQuery($insertDeliveryzonesql);
                                     }
                             }
                         }



                     } 
                     
                 }

             } 
             $this->setMessage("Shipping Methods has been assigned successfully","success");


         }
         $this->setRedirect("/shippingmethod/options/");
     }
    public function optionsAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        //get shipping method settings
        list($limitFrom, $limitTo) = ''; //NO OF RECORDS PER PAGE
        $resSelServices = $ObjShippingMethod->listAvailableSmServices($limitFrom, $limitTo);
        $resPagesCount  = $this->setPagesCount($key = 'page');
        $previousURL    = $this->getPreviousURL();
        $this->ObjView->assign('previousURL', $previousURL);
        //	$this->ObjView->assign('smGroupStatus', $smGroupStatus);
        //	$this->ObjView->assign('smGroupLabel', $smGroupLabel);
        $this->ObjView->assign('resShippingMethods', $resSelServices);
        //Privilege
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('shippingmethod/editoption/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('shippingmethod/unassign/'));
        $this->ObjView->assign("showShippingMethodPrivilege", $this->ObjCommon->hasPrivilege('shippingmethod/index/'));
        //Privilege
        $this->ObjView->display('ShippingMethodOptions.tpl');
    }
    public function assignoptionAction($smServiceID = '', $smGroupID = '', $smServiceTypeID = '') {
        $ObjShippingMethod = new ShippingmethodModel();
        $ObjDelzone        = new DeliveryZoneModel();
        $languageIDs       = $this->ObjView->languageIDs;
        $resDelZones       = $ObjDelzone->listDeliveryZones($languageIDs, '', '', '', 'Active', 'options', '', '');
        $this->ObjView->assign('resDelZones', $resDelZones);
        $resSmServices = $ObjShippingMethod->listShippingMethodServices();
        //	$smGroupDetails		= $ObjShippingMethod->getShippingMethodGroupDetails($smGroupID);
        if (empty($resSmSettings)) {
            //		$this->setRedirect("/shippingmethod/");		
        }
        if ($smServiceID) {
            $isDefault = $ObjShippingMethod->getShippingMethodDefault($smServiceID);
            $this->ObjView->assign('isDefault', $isDefault);
            $dZones = $ObjShippingMethod->getSmsZoneByID($smServiceID);
            $this->ObjView->assign('dZones', $dZones);
        }
        if (isset($_POST['submitSms'])) {
            if (isset($_POST['isDefault']) && ($_POST['isDefault'] != 'Yes'))
                $_POST['isDefault'] = 'No';
            if ($smGroupID > 0 && $smServiceID > 0) {
                $smsUpdate          = $ObjShippingMethod->saveSmSettingsDetails($_POST, $smServiceID);
                $smgUpdate          = $ObjShippingMethod->updateSmServiceAvailability($smServiceID);
                $_POST['isDefault'] = isset($_POST['isDefault']) ? $_POST['isDefault'] : '';
                $ObjShippingMethod->changeSmGroupDefault($_POST['isDefault'], $smServiceID);
            } else {
                $selSmgDetails = $ObjShippingMethod->getShippingMethodGroupDetails($_POST['sm_main']);
                if ($selSmgDetails['isRealTimeCalculation'] == 'No' && in_array($selSmgDetails['settingsGroupKey'], array(
                    'free_shipping',
                    'flat_rate'
                ))) {
                    if ($selSmgDetails['settingsGroupKey'] == 'flat_rate')
                        $_POST['settingsGroupKey'] = 'flat_custom';
                    else
                        $_POST['settingsGroupKey'] = 'free_custom';
                    $smGroupID                      = $ObjShippingMethod->getGroupIDByKey($_POST['settingsGroupKey']);
                    $_POST['realtime_sm_services']  = $smGroupID;
                    $_POST['isRealTimeCalculation'] = 'No';
                } else {
                    $_POST['settingsGroupKey']      = $selSmgDetails['settingsGroupKey'];
                    $_POST['isRealTimeCalculation'] = 'Yes';
                }
                $sms_insertID = $ObjShippingMethod->cloneCustomShippingService();
                $smServiceID  = $sms_insertID;
            }
            $deliveryZoneID = isset($_POST['deliveryZoneID']) ? $_POST['deliveryZoneID'] : '';
            if (isset($deliveryZoneID) && $deliveryZoneID != '' && (count($deliveryZoneID) > 0))
                $deliveryZoneID = implode("~*", $deliveryZoneID);
            else
                $deliveryZoneID = '';
            $ObjShippingMethod->assignSmServiceZone($smServiceID, $deliveryZoneID);
            $this->setMessage("language.msgShippingServiceUpdated", "success");
            echo '<script type="text/javascript">parent.$.colorbox.close();</script>';
            exit;
            //	$this->setRedirect("/shippingmethod/");
        }
        //Assign links for cancel button
        $previousURL = $this->getPreviousURL();
        $this->ObjView->assign('previousURL', $previousURL);
        $this->ObjView->assign('smGroupID', $smGroupID);
        $this->ObjView->assign('smServiceID', $smServiceID);
        $this->ObjView->assign('smServiceTypeID', $smServiceTypeID);
        $this->ObjView->assign('resSmServices', $resSmServices);
        //	$this->ObjView->assign('smGroupLabel',$smGroupDetails['settingsGroupXmlLabel']);
        $this->ObjView->display('ShippingMethodOptionsAssign.tpl');
    }
    public function ajaxGetSettingsAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        $ObjTaxclassModel  = new TaxclassModel();
        $smGroupID         = $this->getRequestValue('group_id');
        $serviceType       = $this->getRequestValue('s_type');
        $actionType        = $this->getRequestValue('ac_type');
        if ($smGroupID == 0) {
            $smGroupID = '';
            if ($serviceType)
                $smGroupID = $ObjShippingMethod->getGroupIDByKey($serviceType);
        }
        $resSmSettings = $ObjShippingMethod->listSmSettingsByGroupId($smGroupID);
        $smGroupKey    = $ObjShippingMethod->getGroupKeyByID($smGroupID);
        if (empty($resSmSettings)) {
            echo '';
            exit;
        }
        $this->ObjView->assign('smGroupID', $smGroupID);
        $this->ObjView->assign('serviceType', $serviceType);
        $this->ObjView->assign('resSmSettings', $resSmSettings);
        $this->ObjView->assign('actionType', $actionType);
        $html               = $this->ObjView->fetch('ShippingMethodOptionSettingsAjax.tpl');
        $returnData['html'] = $html;
        $ObjDelzone         = new DeliveryZoneModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $resDelZones        = $ObjDelzone->listDeliveryZones($languageIDs, '', '', '', 'Active', 'options', '', '');
        $this->ObjView->assign('resDelZones', $resDelZones);
        if (strpos($smGroupKey, 'flat_') !== false) {
            $resTaxClass = $ObjTaxclassModel->listTaxClasses("", "", "", "Active", "product");
            $this->ObjView->assign('resTaxClass', $resTaxClass);
            $this->ObjView->assign('gKey', 'flat');
        }
        if ($smGroupID) {
            $isDefault = $ObjShippingMethod->getShippingMethodDefault($smGroupID);
            $this->ObjView->assign('isDefault', $isDefault);
            $dZones = $ObjShippingMethod->getSmsZoneByID($smGroupID);
            $this->ObjView->assign('dZones', $dZones);
            $tax = $ObjShippingMethod->getTaxcalassByID($smGroupID);
            $this->ObjView->assign('flat_tax_class', $tax);
        }
        $zonehtml               = $this->ObjView->fetch('ShippingServiceDelZones.tpl');
        $returnData['zonehtml'] = $zonehtml;
        echo json_encode($returnData);
    }
    public function ajaxGetServicesAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        $smGroupID         = $this->getRequestValue('group_id');
        $smServiceID       = $this->getRequestValue('s_id');
        $smServiceTypeID   = $this->getRequestValue('t_id');
        $smGroupKey        = $ObjShippingMethod->getGroupKeyByID($smGroupID);
        if (in_array($smGroupKey, array(
            'free_shipping',
            'flat_rate'
        )))
            $user_custom = 1;
        if (isset($user_custom) && $user_custom == 1)
            $type = $smGroupKey;
        else
            $type = '';
        $resServices = $ObjShippingMethod->listSmServices($smGroupID, $smServiceID, $type, $smServiceTypeID);
        if (empty($resServices)) {
            echo '';
        }
        echo $resServices;
        exit;
    }
    public function ajaxUnassignServiceAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        $smServiceID       = $_POST['sid'];
        $services          = $ObjShippingMethod->getProductShippingServices();
        if (in_array($smServiceID, $services)) {
            $this->setMessage("Shipping Service Assigned To products,It Cannot be Deleted", "message_error");
        } else {
            $changestatus = $ObjShippingMethod->unassignSmService($smServiceID);
            $this->setMessage("language.msgShippingServiceStatusDeleted", "success");
        }
        if (!empty($changestatus))
            echo 1;
    }
    //Edit Assign 
    public function editOptionAction() {
        $smServiceID     = $this->getRequestValue('id');
        $smGroupID       = $this->getRequestValue('sm');
        $smServiceTypeID = $this->getRequestValue('tid');
        $this->assignoptionAction($smServiceID, $smGroupID, $smServiceTypeID);
    }
}