<?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: DeliveryzoneController.php, v 1.0 2013/06/29 20:52:11
//
class DeliveryzoneController extends Controller {
    public function indexAction() {
        $merchantID      = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $languageIDs     = $this->ObjView->languageIDs;
        $ObjDeliveryzone = new DeliveryZoneModel();
        $deleteprivilage = 1;
        $link            = "/deliveryzone/index/";
        if ($this->getRequestValue('page')) {
            $link .= "page/" . $this->getRequestValue('page') . '/';
        }
        //search		
        if (isset($_POST['submitSearch'])) {
            $link .= (isset($_POST['deliveryZoneMode']) && $_POST['deliveryZoneMode'] != '') ? 'mode/' . $_POST['deliveryZoneMode'] . '/' : '';
            $link .= (isset($_POST['deliveryZoneName']) && $_POST['deliveryZoneName'] != '') ? 'key/' . $this->encodeUrlString($_POST['deliveryZoneName']) . '/' : '';
            $link .= (isset($_POST['countryID']) && $_POST['countryID'] > 0) ? 'cid/' . $_POST['countryID'] . '/' : '';
            $link .= (isset($_POST['stateID']) && $_POST['stateID'] > 0) ? 'sid/' . $_POST['stateID'] . '/' : '';
            $link .= (isset($_POST['zipcode']) && $_POST['zipcode'] > 0) ? 'zip/' . $this->encodeUrlString($_POST['zipcode']) . '/' : '';
            $this->setRedirect($link);
        }
        $mode             = $this->getRequestValue('mode');
        $deliveryZoneName = $this->decodeUrlString($this->getRequestValue('key'));
        $countryID        = $this->getRequestValue('cid');
        $stateID          = $this->getRequestValue('sid');
        $zipcode          = $this->decodeUrlString($this->getRequestValue('zip'));
        //search ends 
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $resListDeliveryZones = $ObjDeliveryzone->listDeliveryZones($languageIDs, $limitFrom, $limitTo, 'ASC', '', '', $mode, $merchantID, 'alphabetical', $deliveryZoneName, $countryID, $stateID, $zipcode);
        $resPagesCount        = $this->setPagesCount($key = 'page');
        if (isset($_POST['deliveryzoneBulkStatus']) && $_POST['deliveryzoneBulkStatus'] != '' && $_POST['deliveryZoneStatus'] != '') {
            if ($_POST['deliveryZoneStatus'] == "Deleted" || $_POST['deliveryZoneStatus'] == "Inactive") {
                if (isset($_POST['delid']) && $_POST['delid'] != '') {
                    $del_array = array_diff($_POST['deliveryzoneBulkStatus'], $_POST['delid']);
                } else {
                    $del_array = $_POST['deliveryzoneBulkStatus'];
                }
                if (count($del_array) > 0) {
                    $resChangeDeliveryZoneStatus = $ObjDeliveryzone->changeDeliveryZoneStatus($_POST['deliveryZoneStatus'], $del_array, $deleteprivilage, $merchantID);
                    if ($_POST['deliveryZoneStatus'] == "Deleted") {
                        $this->setMessage("language.msgDeliveryZoneDelete", "message_success");
                    } else {
                        $this->setMessage("language.msgDeliveryZoneUpdate", "message_success");
                    }
                } else {
                    if ($_POST['deliveryZoneStatus'] == "Deleted") {
                        $this->setMessage("language.msgDeliveryZoneDeletetax", "message_error");
                    } else {
                        $this->setMessage("language.msgDeliveryZoneupdate", "message_error");
                    }
                }
            } else {
                $resChangeDeliveryZoneStatus = $ObjDeliveryzone->changeDeliveryZoneStatus($_POST['deliveryZoneStatus'], $_POST['deliveryzoneBulkStatus'], $deleteprivilage, $merchantID);
                $this->setMessage("language.msgStatusUpdatedSuccessfully", "message_success");
            }
            $this->setRedirect();
        }
        $ObjCountry            = new CountryModel();
        $resListCountryOptions = $ObjCountry->listCountriesForOption($languageIDs);
        $this->ObjView->assign('resCountry', $resListCountryOptions);
        $this->ObjView->assign('rsDeliveryzone', $resListDeliveryZones);
        $this->ObjView->assign('merchantID', $merchantID);
        $this->ObjView->assign('deliveryZoneMode', $mode);
        $this->ObjView->assign('deliveryZoneName', $deliveryZoneName);
        $this->ObjView->assign('countryID', $countryID);
        $this->ObjView->assign('stateID', $stateID);
        $this->ObjView->assign('zipcode', $zipcode);
        $this->ObjView->display('DeliveryzoneList.tpl');
    }
    //FUNCTION TO ADD NEW GEOZONE
    public function newAction() {
        $ObjCountries   = new CountryModel();
        $ObjStates      = new StateModel();
        $languageIDs    = $this->ObjView->languageIDs;
        $merchantID     = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $resListCountry = $ObjCountries->listCountries($languageIDs);
        $this->ObjView->assign('resCountry', $resListCountry);
        $ObjDeliveryzone = new DeliveryZoneModel();
        $this->ObjView->assign('countryCount', 0);
        $this->ObjView->assign('rsCountryStateCount', isset($_POST['countryIDs']) ? count($_POST['countryIDs']) : 0);
        if ($this->ObjForm->isValid('formDeliveryZone', 'submitDeliveryzone')) {
            $resSaveDeliveryZoneDetails = $ObjDeliveryzone->saveDeliveryZone($languageIDs, '', $merchantID);
            $this->setMessage("language.msgDeliveryZoneAdd", "message_success");
            $this->setRedirect("deliveryzone/");
        }
        $this->ObjView->display('DeliveryzoneAdd.tpl');
    }
    //END OF FUNCTION
    public function ajaxAction() {
        $countryID     = $_POST['ajax_request'][0];
        $zoneType      = $_POST['ajax_request'][1];
        $statearray    = $_POST['ajax_request'][2];
        $selcountryids = $_POST['selids'];
        $zipCode       = '';
        $isRange       = '';
        $country_ids   = explode(",", $selcountryids);
        if ($zoneType == 'Location') {
            $zipCode         = str_replace('ZipCodes,', '', $_POST['ajax_request'][3]);
            $slctdStatsLoctn = $_POST['ajax_request'][4];
            $isRange         = $_POST['ajax_request'][5];
        }
        $output = "0~*";
        if (count($country_ids) > 1) {
            //unset($country_ids['0']);
            array_pop($country_ids);
            if (in_array($countryID, $country_ids)) {
                $output = "1~*";
                if ($zoneType == 'Location')
                    $locationCountry = 'Yes';
                //exit();
            }
        }
        echo $output;
        $languageIDs  = $this->ObjView->languageIDs;
        $ObjCountries = new CountryModel();
        $ObjStates    = new StateModel();
        $resCountry   = $ObjCountries->getCountryDetails($countryID, $languageIDs);
        $resListState = $ObjStates->listAjaxStates($languageIDs, $countryID, array_unique(explode(",", $statearray)));
        $stateIDs     = '';
        for ($i = 0; $i < count($resListState); $i++) {
            $stateIDs = $stateIDs . '|' . $resListState[$i]['stateID'];
        }
        $this->ObjView->assign('stateIDs', $stateIDs);
        $this->ObjView->assign('rsCountryName', $resCountry);
        $this->ObjView->assign('rsStates', $resListState);
        $this->ObjView->assign('isRange', $isRange);
        $this->ObjView->assign('zoneType', $zoneType);
        $this->ObjView->assign('zip', isset($zipCode) ? $zipCode : '');
        if (isset($locationCountry) && $locationCountry == 'Yes') {
            $this->ObjView->display('DeliveryzoneAjaxLocationAdd.tpl');
        } else {
            $this->ObjView->display('DeliveryzoneCountryAjax.tpl');
        }
    }
    //FUNCTION TO SET COUNTRY
    public function ajaxSetCountryAction() {
        $country_list     = $_POST['ajax_request'][0];
        $ObjGeozone       = new GeoZoneModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $rescountry_array = $ObjGeozone->getcountries($languageIDs, $country_list);
        $this->ObjView->assign('country_array', $rescountry_array);
        $this->ObjView->display('GeozoneSetCountryAjax.tpl');
    }
    //END OF FUNCTION
    //FUNCTION TO EDIT DELIVERYZONE
    public function editAction() {
        $ObjDeliveryzone    = new DeliveryZoneModel();
        $ObjCountries       = new CountryModel();
        $ObjStates          = new StateModel();
        $merchantID         = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $selcountries_array = array();
        $languageIDs        = $this->ObjView->languageIDs;
        $resListCountry     = $ObjCountries->listCountries($languageIDs);
        $this->ObjView->assign('resCountry', $resListCountry);
        $deliveryZoneID = $this->getRequestValue("id");
        $this->ObjView->assign('deliveryZoneID', $deliveryZoneID);
        if ($deliveryZoneID) {
            $resDeliveryZone = $ObjDeliveryzone->getDeliveryZoneDetails($deliveryZoneID, $languageIDs, 0, 0, '', $merchantID);
            if (!$resDeliveryZone)
                $this->setRedirect('/deliveryzone/new/');
            $this->ObjView->assignValues(isset($resDeliveryZone[0]) ? $resDeliveryZone[0] : '');
            //echo "<pre />"; print_r($resDeliveryZone); exit;
            $slctdStates = '';
            foreach ($resDeliveryZone as $value) {
                $countryID                                                    = $value['countryID'];
                $zoneType                                                     = $value['deliveryZoneType'];
                $slctdStates[$countryID][]                                    = $value['stateID'];
                $curr_StateID                                                 = ($value['stateID']) ? $value['stateID'] : 0;
                $selcountries_array[$value['countryID']]                      = $value['countryID'];
                $resCountryState[$countryID]['countryName']                   = $value['countryName'];
                $resCountryState[$countryID][$curr_StateID]['delZoneRegID'][] = $value['deliveryZoneRegionID'];
                if ($value['isRange'] == 'Yes') {
                    $resCountryState[$countryID][$curr_StateID]['zipCodes'][] = $value['rangeFrom'] . " - " . $value['rangeTo'];
                } else {
                    $resCountryState[$countryID][$curr_StateID]['zipCodes'][] = $value['zipCodes'];
                }
                $resCountryState[$countryID][$curr_StateID]['isRange'][] = $value['isRange'];
                if ($value['stateID'])
                    $resCountryState[$countryID]['rsStates'] = $ObjStates->listAjaxStates($languageIDs, $countryID, array_unique($slctdStates[$countryID]), 'all');
            }
        }
        //echo "<pre />"; print_r($resCountryState); exit;
        $countryCount = count($selcountries_array);
        $this->ObjView->assign('countryCount', $countryCount);
        if ($selcountries_array) {
            $selcountries = implode(',', $selcountries_array);
        }
        $this->ObjView->assign('rsCountryState', isset($resCountryState) ? $resCountryState : '');
        if (isset($_POST['submitDeliveryzone'])) {
            $this->ObjView->assign('rsCountryStateCount', count($_POST['countryIDs']));
        } else {
            $this->ObjView->assign('rsCountryStateCount', isset($resCountryState) ? count($resCountryState) : 0);
        }
        $this->ObjView->assign('slctdStates', $slctdStates);
        $this->ObjView->assign('zoneType', isset($zoneType) ? $zoneType : '');
        $this->ObjView->assign('selcountries', isset($selcountries) ? $selcountries : '');
        $previousURL = $this->getPreviousURL();
        $this->ObjView->assign('previousURL', $previousURL);
        if ($this->ObjForm->isValid('formDeliveryZone', 'submitDeliveryzone')) {
            $resSaveDeliveryZoneDetails = $ObjDeliveryzone->saveDeliveryZone($languageIDs, $deliveryZoneID, $merchantID);
            if ($resSaveDeliveryZoneDetails)
                $this->setMessage("language.msgDeliveryZoneUpdate", "message_success");
            else
                $this->setMessage("language.msgDeliveryZoneNoStatusUpdate", "message_success");
            $this->setRedirect($previousURL);
        }
        $this->ObjView->display('DeliveryzoneAdd.tpl');
    }
    //END OF FUNCTION
    //FUNCTION TO DELETE DELIVERYZONE
    public function destroyAction() {
        $merchantID                  = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $deliveryZoneID[]            = $this->getRequestValue("id");
        $deleteprivilage             = 1;
        $ObjDeliveryzone             = new DeliveryZoneModel();
        $resChangeDeliveryZoneStatus = $ObjDeliveryzone->changeDeliveryZoneStatus('Deleted', $deliveryZoneID, $deleteprivilage, $merchantID);
        $this->setMessage("language.msgDeliveryZoneDelete", "message_success");
        $previousURL = $this->getPreviousURL();
        $this->setRedirect($previousURL);
    }
    //END OF FUNCTION
    public function ajaxstatusAction() {
        $merchantID                      = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $ObjDeliveryzone                 = new DeliveryZoneModel();
        $_POST['deliveryZoneStatus']     = $_POST['newstatus'];
        $_POST['deliveryzoneBulkStatus'] = array(
            $_POST['id']
        );
        $resChangeDeliveryZoneStatus     = $ObjDeliveryzone->changeDeliveryZoneStatus($_POST['deliveryZoneStatus'], $_POST['deliveryzoneBulkStatus'], 1, $merchantID);
        $this->setMessage("language.msgStatusUpdatedSuccessfully", "message_success");
        if ($resChangeDeliveryZoneStatus)
            echo 1;
    }
    public function showAction() {
        $ObjDeliveryzone = new DeliveryZoneModel();
        $ObjStates       = new StateModel();
        $merchantID      = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $languageIDs     = $this->ObjView->languageIDs;
        $deliveryZoneID  = $this->getRequestValue("id");
        $resCountryState = $selcountries_array = array();
        $this->ObjView->assign('deliveryZoneID', $deliveryZoneID);
        if ($deliveryZoneID) {
            $resDeliveryZone = $ObjDeliveryzone->getDeliveryZoneDetails($deliveryZoneID, $languageIDs, 0, 0, '', $merchantID, 'show');
            $this->ObjView->assignValues($resDeliveryZone[0]);
            $slctdStates = '';
            foreach ($resDeliveryZone as $value) {
                $countryID = $value['countryID'];
                $zoneType  = $value['deliveryZoneType'];
                if ($value['stateID'])
                    $slctdStates[$countryID][] = $value['stateID'];
                $curr_StateID                               = ($value['stateID']) ? $value['stateID'] : 0;
                $selcountries_array[$value['countryID']]    = $value['countryID'];
                $resCountryState[$countryID]['countryName'] = $value['countryName'];
                if ($value['isRange'] == 'Yes') {
                    $resCountryState[$countryID][$curr_StateID]['zipCodes'][] = $value['rangeFrom'] . " - " . $value['rangeTo'];
                } else {
                    $resCountryState[$countryID][$curr_StateID]['zipCodes'][] = $value['zipCodes'];
                }
                if ($value['stateID'])
                    $resCountryState[$countryID]['rsStates'] = $ObjStates->listAjaxStates($languageIDs, $countryID, array_unique($slctdStates[$countryID]), 'all');
            }
        }
        //echo "<pre />"; print_r($resCountryState); exit;
        $this->ObjView->assign('rsCountryState', $resCountryState);
        $this->ObjView->assign('slctdStates', $slctdStates);
        $this->ObjView->assign('zoneType', $zoneType);
        $previousURL = $this->getPreviousURL();
        $this->ObjView->assign('previousURL', $previousURL);
        $this->ObjView->display('DeliveryzoneShow.tpl');
    }
    //LIST STATES WITH AJAX
    public function ajaxStateAction() {
        $objState        = new StateModel();
        $ObjDeliveryzone = new DeliveryZoneModel();
        $countryID       = $_POST['ajax_request'][0];
        $zoneType        = $_POST['ajax_request'][1];
        $deliveryZoneID  = $_POST['ajax_request'][2];
        $slctdStates     = explode(",", $_POST['slctdStates']);
        $editedState     = (isset($_POST['ajax_request'][3])) ? $_POST['ajax_request'][3] : '';
        $delRegID        = (isset($_POST['ajax_request'][4])) ? $_POST['ajax_request'][4] : '';
        $languageIDs     = $this->ObjView->languageIDs;
        $stateID         = (isset($_POST['stateID'])) ? $_POST['stateID'] : '';
        if ($countryID > 0) {
            $statesList = $objState->listStates($languageIDs, $countryID, 'Active');
            if ($deliveryZoneID > 0 && $zoneType == 'Location' && $delRegID > 0)
                $resZip = $ObjDeliveryzone->getDeliveryZoneDetails($deliveryZoneID, $languageIDs, $countryID, $editedState, 'ajax', '', '', $delRegID);
        }
        $selectedStates = array_unique(($slctdStates));
        $this->ObjView->assign('selectedStates', $selectedStates);
        $this->ObjView->assign('countryID', $countryID);
        $this->ObjView->assign('zoneType', $zoneType);
        $this->ObjView->assign('rsStates', $statesList);
        $this->ObjView->assign('editedState', $editedState);
        $this->ObjView->assign('zipCode', isset($resZip[0]['zipCodes']) ? $resZip[0]['zipCodes'] : '');
        $this->ObjView->assign('isRange', isset($resZip[0]['isRange']) ? $resZip[0]['isRange'] : '');
        $this->ObjView->assign('rangeFrom', isset($resZip[0]['rangeFrom']) ? $resZip[0]['rangeFrom'] : '');
        $this->ObjView->assign('rangeTo', isset($resZip[0]['rangeTo']) ? $resZip[0]['rangeTo'] : '');
        if ($zoneType == 'Region')
            $this->ObjView->display('DeliveryZoneAjaxRegion.tpl');
        else
            $this->ObjView->display('DeliveryZoneAjaxLocation.tpl');
    }
    public function ajaxExistsAction() {
        $zoneID           = $_POST['ajax_request'][0];
        $zoneName         = $_POST['ajax_request'][1];
        $languageIDs      = $this->ObjView->languageIDs;
        $ObjDeliveryzone  = new DeliveryZoneModel();
        $isZoneNameExists = $ObjDeliveryzone->isNameExists($languageIDs, $zoneID, $zoneName);
        exit;
    }
}