<?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: AffiliateController.php, v 1.0 2011/06/14 20:52:11
//
class BannerController extends Controller {
    public function indexAction() {
        $ObjBanner              = new BannerModel();
        $ObjBrand               = new BrandModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        /*privileges*/
        $this->ObjView->assign('editPrivilege', $this->ObjCommon->hasPrivilege('banner/edit/'));
        $this->ObjView->assign('showPrivilege', $this->ObjCommon->hasPrivilege('banner/show/'));
        $deletePrivilege = $this->ObjCommon->hasPrivilege('banner/destroy/');
        $this->ObjView->assign('deletePrivilege', $deletePrivilege);
        /*privileges*/
        $settingsDateFormat = $this->getSettingValue('site_settings', 'date_format');
        $link               = "/banner/index/";
        $bannerName         = $this->decodeUrlString($this->getRequestValue('name'));
        $bannerType         = $this->getRequestValue('type');
        $bannerLoc          = $this->getRequestValue('loc');
        $bannerPlatform     = $this->getRequestValue('platform');
        $category           = $this->getRequestValue('category');
        $brandID            = $this->getRequestValue('brandID');
        $bannerFromDate     = $this->urlDate($this->getRequestValue("from"), 'get', $settingsDateFormat);
        $bannerToDate       = $this->urlDate($this->getRequestValue("to"), 'get', $settingsDateFormat);
        $orderby            = $this->getRequestValue('orderby');
        $sortby             = $this->getRequestValue('sortby');
        $limitFrom          = 0;
        $limitTo            = 0;
        if (($bannerLoc != 2) && ($bannerLoc != 3)) {
            $page = $this->getRequestValue('page');
            list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        }
        $ObjProductCategory = new ProductCategoryModel();
        $resCategoryTree    = $ObjProductCategory->listProductCategoryItems($languageIDs, 0, 0, 0, '', true);
        $resCategoryTree    = array_slice($resCategoryTree, 1);
        if (isset($_REQUEST['changeStatus']) && count($_REQUEST['checkBannerIDs']) > 0) {
            $changeStatus    = $_POST['changeStatus'];
            $bannerIDs       = $_POST['checkBannerIDs'];
            $resBannerStatus = $ObjBanner->changeStatus($bannerIDs, $changeStatus, $deletePrivilege);
            $this->setMessage("language.msgBannerUpdate", 3);
            $this->setRedirect(); //$link
        }
        $brandID = '';
        if (isset($_POST['submitSearch'])) {
            if ($_POST['bannerName']) {
                $link .= "name/" . $this->encodeUrlString($_POST['bannerName']) . "/";
            }
            if ($_POST['bannerType']) {
                $link .= "type/" . $_POST['bannerType'] . "/";
            }
            if ($_POST['bannerPlatform']) {
                $link .= "platform/" . $_POST['bannerPlatform'] . "/";
            }
            if ($_POST['brandID'] && $_POST['bannerLoc'] == 4) {
                $link .= "brandID/" . $_POST['brandID'] . "/";
            }
            if ($_POST['brandID']>0) {
                $link .= "frID/" . $_POST['brandID'] . "/";
            }
            $daterange = $_POST['daterange'];
            if ($daterange) {
                if (strpos($daterange, ' - '))
                    list($startDate, $endDate) = explode(' - ', $daterange);
                else
                    list($startDate, $endDate) = array(
                        $daterange,
                        ""
                    );
            }
            $link .= ((isset($startDate) && $startDate != "") ? "start/" . $this->urlDate($startDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= ((isset($endDate) && $endDate != "") ? "end/" . $this->urlDate($endDate, 'set', $settingsDateFormat) . "/" : "");
            if ($_POST['bannerLoc']) {
                $link .= "loc/" . $_POST['bannerLoc'] . "/";
                if ($_POST['bannerLoc'] == 3 && is_numeric($_POST['category'])) {
                    $link .= "category/" . $_POST['category'] . "/";
                }
            }
            $this->setRedirect($link);
        }
        if ($bannerName) {
            $link .= "name/" . $this->encodeUrlString($bannerName) . "/";
        }
        if ($bannerType) {
            $link .= "type/" . $bannerType . "/";
        }
        if ($bannerPlatform) {
            $link .= "platform/" . $bannerPlatform . "/";
        }
        if ($this->getRequestValue('frID')) {
            $brandID = $this->getRequestValue('frID');
        }
        /* if($bannerFromDate){
        $link	.=	"from/".$this->urlDate($bannerFromDate,'set',$settingsDateFormat)."/";
        }
        if($bannerToDate){
        $link	.=	"to/".$this->urlDate($bannerToDate,'set',$settingsDateFormat)."/";
        } */
        if ($bannerLoc) {
            $link .= "loc/" . $bannerLoc . "/";
        }
        if ($category) {
            $link .= "category/" . $category . "/";
        }
        $startDate     = $this->urlDate($this->getRequestValue('start'), 'get', $settingsDateFormat);
        $endDate       = $this->urlDate($this->getRequestValue('end'), 'get', $settingsDateFormat);
        $startDBDate   = $this->convertDateForSQL($startDate, $settingsDateFormat);
        $endDBDate     = $this->convertDateForSQL($endDate, $settingsDateFormat);
        $resBanner     = $ObjBanner->listBanner($languageIDs, $limitFrom, $limitTo, '', $bannerName, $bannerType, $this->convertDateForSQL($bannerFromDate, $settingsDateFormat), $this->convertDateForSQL($bannerToDate, $settingsDateFormat), $orderby, $sortby, '', $bannerLoc, $category, $startDBDate, $endDBDate, $brandID, $bannerPlatform);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign('resBanner', $resBanner);
        $this->ObjView->assign('bannerName', $bannerName);
        $this->ObjView->assign('bannerType', $bannerType);
        $this->ObjView->assign('bannerPlatform', $bannerPlatform);
        $this->ObjView->assign('bannerLoc', $bannerLoc);
        $this->ObjView->assign('category', $category);
        if ($bannerToDate == $bannerFromDate) {
            $this->ObjView->assign('bannerCreatedDate', $bannerFromDate);
        } else {
            $this->ObjView->assign('bannerCreatedDate', $bannerFromDate . " - " . $bannerToDate);
        }
        if ($startDate && $endDate == '') {
            $this->ObjView->assign('daterange', $startDate);
        } else if ($startDate && $endDate) {
            $this->ObjView->assign('daterange', $startDate . ' - ' . $endDate);
        } else {
            $this->ObjView->assign('daterange', '');
        }
        /*START :  Brand List */
        $params    = array(
            'languageIDs' => $languageIDs
        );
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        /*END :  Brand List */
        $this->ObjView->assign('resCategoryTree', $resCategoryTree);
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('sortName', $orderby);
        $this->ObjView->assign('sortby', $sortby);
        $this->ObjView->assign('brandID', $brandID);
        $this->ObjView->assign('settingsDateFormat', $settingsDateFormat);
        //$this->ObjView->assign('page',$page);
        //$this->ObjView->assign('dataCount',$limitTo);
        $this->ObjView->display('BannerList.tpl');
    }
    public function newAction() {
        $ObjBanner              = new BannerModel();
        $ObjBrand               = new BrandModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        
        if ($this->ObjForm->isValid('formBanner', 'submitBanner')) {
           
            $logoImageWidth             = $this->getSettingValue('product_cart_settings', 'logo_image_width');
            $logoImageHeight            = $this->getSettingValue('product_cart_settings', 'logo_image_height');
            $_POST['logoImageWidth']    = $logoImageWidth;
            $_POST['logoImageHeight']   = $logoImageHeight;
            $_POST['file']              = $_FILES['bannerSwf']['name'];
            $_POST['bannerSwftemppath'] = $_FILES['bannerSwf']['tmp_name'];
            if (isset($_POST['bannerDisplayType']) && $_POST['bannerDisplayType'] == "Swf") {
                $_POST['bannerContent']   = '';
                $_POST['bannerTextBlend'] = 'no';
            }
            $resBanner = $ObjBanner->saveBanner($languageIDs);
            $this->setMessage("language.msgBannerAdd", 3);
            $this->setRedirect("/banner/index/");
        }
        $brandParams         = array(
            'languageIDs' => $languageIDs
        );       
        $listBrand      = $ObjBrand->listBrand($brandParams);  
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->display('BannerAdd.tpl');
    }
    public function editAction() {
        $ObjBanner              = new BannerModel();
        $ObjImage               = new ImageModel();
        $ObjBrand               = new BrandModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $bannerID               = $this->getRequestValue('id');
        $resBanner              = $ObjBanner->listBanner($languageIDs, 0, '', $bannerID);
        if ($this->ObjForm->isValid('formBanner', 'submitBanner')) {
            $logoImageWidth             = $this->getSettingValue('product_cart_settings', 'logo_image_width');
            $logoImageHeight            = $this->getSettingValue('product_cart_settings', 'logo_image_height');
            $_POST['logoImageWidth']    = $logoImageWidth;
            $_POST['logoImageHeight']   = $logoImageHeight;
            $_POST['file']              = $_FILES['bannerSwf']['name'];
            $_POST['bannerSwftemppath'] = $_FILES['bannerSwf']['tmp_name'];
            if ($_POST['bannerDisplayType'] == "Swf") {
                $_POST['bannerContent']   = '';
                $_POST['bannerTextBlend'] = 'no';
            }
            /*unlink old image*/
            /*if (!empty($_POST["bannerImage_temp"])) {
                $imagePath = __UPLOADS_FOLDER . 'banner/' . trim($resBanner['bannerImage']);
                $ObjImage->unlinkImage($imagePath);
                $imagePath = __UPLOADS_FOLDER . 'banner/thumb/' . trim($resBanner['bannerImage']);
                $ObjImage->unlinkImage($imagePath);
            }*/
            /*unlink old image*/
            if($resBanner['bannerLoc']==5 && $_POST['bannerLoc']!=$resBanner['bannerLoc']){
                $ObjBanner->deleteBanner($bannerID);
            }
            $resBanner = $ObjBanner->saveBanner($languageIDs, $bannerID);
            $this->setMessage("language.msgBannerUpdate", 3);
            $this->setRedirect("/banner/index/");
        }
        if ($resBanner['bannerStartTime'])
            $resBanner['bannerStartTime'] = substr($resBanner['bannerStartTime'], 0, -3);
        if ($resBanner['bannerEndTime'])
            $resBanner['bannerEndTime'] = substr($resBanner['bannerEndTime'], 0, -3);
        $this->ObjView->assign('bannerID', $bannerID);
        $this->ObjView->assignValues($resBanner);
        $this->ObjView->assign('bannerFor', $resBanner['bannerLoc']);
        $this->ObjView->assign('bannerPlatform', $resBanner['bannerPlatform']);
        if ($resBanner['bannerLoc'] == 3) {
            $ObjProductCategory = new ProductCategoryModel();
        $resProductCategories      = $ObjProductCategory->listProductCategories($languageIDs, -1);
		
        foreach ($resProductCategories as $key => $value) {
            $categoryTree[$resProductCategories[$key]['productCategoryParent']][] = $resProductCategories[$key];
        }
		//echo '<pre>'; 
		//print_r($categoryTree);exit;		
        $resProductCategories = $this->createCategoryTree($categoryTree, $categoryTree[0]);		
        $this->ObjView->assign('resCategories', $resProductCategories);
            $resProductcategory = $ObjBanner->listBannerTocategoryDetails($bannerID);
            $this->ObjView->assign('resProductcategory', $resProductcategory);
        } else if ($resBanner['bannerLoc'] == 4) {
            
            $languageIDs        = $this->ObjView->languageIDs;
           
            $listBannerToBrands = $ObjBanner->listBannerToBrands(array(
                'bannerID' => $bannerID
            ));
            $this->ObjView->assign('listBannerToBrands', $listBannerToBrands);
            
        }
        $params             = array(
               'languageIDs' => $languageIDs
           );
        $listBrand          = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->display('BannerAdd.tpl');
    }
    public function showAction() {
        $ObjBanner              = new BannerModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $bannerID               = $this->getRequestValue('id');
        $resBanner              = $ObjBanner->listBanner($languageIDs, 0, '', $bannerID);
        if ($resBanner['bannerLoc'] == 3) {
            $resProductcategory = $ObjBanner->listBannerTocategories($languageIDs['Content'], $bannerID);
            $this->ObjView->assign('resSelected', $resProductcategory);
        } else if ($resBanner['bannerLoc'] == 4) {
            $params             = array(
                'languageID' => $languageIDs['Content'],
                'bannerID' => $bannerID,
                'type' => 'view'
            );
            $listBannerToBrands = $ObjBanner->listBannerToBrands($params);
            $this->ObjView->assign('resSelected', $listBannerToBrands);
        }
        $this->ObjView->assign('resBanner', $resBanner);
        $this->ObjView->display('BannerView.tpl');
    }
    public function ajaxchangestatusAction() {
        $ObjBanner       = new BannerModel();
        $bannerIDs       = array(
            $_POST['data']
        );
        $changeStatus    = $_POST['status'];
        $resBannerStatus = $ObjBanner->changeStatus($bannerIDs, $changeStatus, $this->ObjCommon->hasPrivilege('banner/destroy/'));
        if ($changeStatus == 'Deleted') {
            $this->setMessage("language.msgBannerDeleted", 3);
        } else {
            $this->setMessage("language.msgBannerUpdate", 3);
        }
    }
    public function ajaxUpdateBannerOrderAction() {
        $ObjBanner      = new BannerModel();
        $bannerOrders   = explode(",", $_POST['bannerOrder']);
        $resBannerOrder = $ObjBanner->changeOrder($bannerOrders);
    }
    //To list categories when banner type field selected is 'Categories'.
    public function ajaxListCategoriesAction() {
        $ObjProductCategory     = new ProductCategoryModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $resProductCategories      = $ObjProductCategory->listProductCategories($languageIDs, -1);
		
        foreach ($resProductCategories as $key => $value) {
            $categoryTree[$resProductCategories[$key]['productCategoryParent']][] = $resProductCategories[$key];
        }
		//echo '<pre>'; 
		//print_r($categoryTree);exit;		
        $resProductCategories = $this->createCategoryTree($categoryTree, $categoryTree[0]);		
        $this->ObjView->assign('resCategories', $resProductCategories);
        $this->ObjView->display('AjaxProductCategories.tpl');
    }
    //To list categories when banner type field selected is 'Categories'.
    public function ajaxListBrandsAction() {
        $ObjBrand    = new BrandModel();
        $languageIDs = $this->ObjView->languageIDs;
        $params      = array(
            'languageIDs' => $languageIDs
        );
        $listBrand   = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->display('AjaxProductBrands.tpl');
    }
	    private function createCategoryTree(&$list, $parent) {
        $tree = array();
        if (is_array($parent)) {
            foreach ($parent as $k => $l) {
                if (isset($list[$l['productCategoryParent']]) && !empty($list[$l['productCategoryID']])) {
                    $l['children'] = $this->createCategoryTree($list, $list[$l['productCategoryID']]);
                }
                $tree[] = $l;
            }
        }
        return $tree;
    }	
    //menu item listing by ajax
	public function ajaxmenuitemsAction() {
            $ObjCustommenu 	= 	new CustommenuModel();
            $ObjBanner      = new BannerModel();
            $bannerID	=	(isset($_POST['bannerID']) && $_POST['bannerID']!='')?$_POST['bannerID']:'';
            $bannerMenuIds = $ObjBanner->getBannerMenus($bannerID);
            $this->ObjView->assign('bannerMenuIds', $bannerMenuIds);
            $ObjMenu       = new MenuModel();
            $languageIDs   = $this->ObjView->languageIDs;
            $listMenus     = $ObjCustommenu->listMenus($languageIDs, '', '', '', 'Active', '', 'menuItemCount', 'DESC', 'sitemap');
            foreach ($listMenus as $menu) {
                $menuTree     = array();
                $reslistMenus = $ObjCustommenu->getMenusItemsSiteMap($languageIDs, $menu['menuID']); //print_r($reslistMenus);
                foreach ($reslistMenus as $key => $list) {
                    $menuTree[$reslistMenus[$key]['parentID']][] = $reslistMenus[$key];
                }
                $mainTree      = $this->createTreeLeft($menuTree, $menuTree[0]);
                $listItem      = $mainTree;
                $resMenuList[] = array(
                    $menu['menuID'],
                    $menu['menuName'],
                    $listItem
                );
            }
            $this->ObjView->assign('resMenuList', $resMenuList);
            $this->ObjView->display('AjaxBannerMenu.tpl');
	}
        private function createTreeLeft(&$list, $parent) {
            $tree = array();
            if (is_array($parent)) {
                foreach ($parent as $k => $l) {
                    if (isset($list[$l['parentID']]) && !empty($list[$l['orderID']])) {
                        $l['children'] = $this->createTreeLeft($list, $list[$l['orderID']]);
                    }
                    $tree[] = $l;
                }
            }
            return $tree;
        }
}
