<?php

class SiteController extends Controller {

    public $layout = 'menu';
    public $pageTitle = "D-Link | Partner";

//    public function beforeAction() {
//        if (Yii::app()->user->isGuest) {
//            if (Yii::app()->controller->action->id == "page") {
//                Yii::app()->user->setReturnUrl('page/' . $_GET['id']);
//                if (in_array($_GET['id'], array(20, 22, 23, 53, 54, 55, 56, 57, 59, 60))) {
//                    $this->redirect(array('site/login'));
////                    break;
//                }
//            }
//        }
//        return true;
//    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // logind in users
                'actions' => array(
                    'viewprofile',
                    'editprofile',
                    'requestwallet',
                    'submitpaper',
                    'Changepassword',
                    'Pointstable',
                    'Wallet',
                    'Mywallet',
                    'Earnpoints',
                    'Redeempoints',
                    'downloadableResources',
                    'casestudy',
                    'product_guides',
                    'digital_library',
                    'promotional_items',
                    'events',
                    'promotions',
                    'featured',
                    'download_center',
                    'video_center',
                    'productgroup',
                    'products',
                    'productdetails',
                    'toolsMenudetails',
                    'filter',
                    'checkSerialNo'
                ),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'actions' => array(
                    'viewprofile',
                    'editprofile',
                    'requestwallet',
                    'submitpaper',
                    'Changepassword',
                    'Pointstable',
                    'Wallet',
                    'Mywallet',
                    'Earnpoints',
                    'Redeempoints',
                    'downloadableResources',
                    'casestudy',
                    'product_guides',
                    'digital_library',
                    'promotional_items',
                    'events',
                    'promotions',
                    'featured',
                    'download_center',
                    'video_center',
                    'productgroup',
                    'products',
                    'productdetails',
                    'toolsMenudetails'
                ),
                'users' => array('*'),
            ),
        );
    }

    public function actionCm() {
        $menuBuilder = new Treeview;
        $menustring = '<div class="topmenu_outer"><div class="topmenu"><div id="menu"><ul id="top"><li><a href="#">Partner<span class="arrow"></span></a><ul>' . $menuBuilder->buildmenu(2) . '</ul></li><li><a href="#">Marketing<span class="arrow"></span></a><ul>' . $menuBuilder->buildmenu(4) . '<li><a href="' . Yii::app()->createUrl('site/product_guides') . '" class="messages">Product guides</a></li><li><a href="' . Yii::app()->createUrl('site/digital_library') . '" class="messages">Digital Library</a></li><li><a href="' . Yii::app()->createUrl('site/promotional_items') . '" class="messages">Promotions</a></li><li><a href="' . Yii::app()->createUrl('site/events') . '" class="messages">Events</a></li></ul></li><li><a href="#">Resources<span class="arrow"></span></a><ul>';
        $mod_prod_downloadable=new ProductDownloadable();
        $downloadables = $mod_prod_downloadable->findAll(array('condition' => 'isActive="Y" AND show_in_partner="Y" AND id not in(13)'));
        foreach ($downloadables as $eachDownloadable) {
            $menustring .= '<li><a href="' . Yii::app()->createUrl('site/DownloadableResources', array('id' => $eachDownloadable->id, 'name' => preg_replace('/[^a-z0-9_]/', '', strtolower(str_replace(" ", "_", $eachDownloadable->item_name))))) . '" class="documents">' . $eachDownloadable->item_name . '</a></li>';
        }
        $menustring .= $menuBuilder->buildmenu(5) . '<li><a href="' . Yii::app()->createUrl('site/video_center') . '" class="messages">Video Center</a></li>              <li><a href="' . Yii::app()->createUrl('site/download_center') . '" class="messages">Download Center</a></li>              
            <li><a href="' . Yii::app()->createUrl('site/casestudy') . '" class="messages">Case Studies</a></li></ul></li>
                <li>            <a href="#">Tools<span class="arrow"></span></a>                        
                <ul><li><a class="documents" onclick="psp_form.submit();" href="javascript:;">Product Selector</a></li>              
                <li><a class="documents" onclick="webui_form.submit();" href="javascript:;">Web UI EMULATOR</a></li> 
                <li><a class="documents" onclick="piv_form.submit();" href="javascript:;">Product Interface Viewer</a></li>  
                <li><a class="documents" onclick="bac_form.submit();" href="javascript:;">Bandwidth & Capacity Calculator</a></li> 
                <li><a class="documents" onclick="wifi_form.submit();" href="javascript:;">Wi-fi- Planner</a></li>          ' . $menuBuilder->buildmenu(6) . '            </ul>          </li>          
                    <li>            <a href="#">Academy<span class="arrow"></span></a>
                    <ul>' . $menuBuilder->buildmenu(7) . '</ul>          </li>          
                        <li>            <a href="#"> SCS certification <span class="arrow"></span></a>                       
                        <ul>' . $menuBuilder->buildmenu(52) . '</ul>          </li>          
                            <li>            <a href="#">Rewards<span class="arrow"></span></a>
                            <ul><!--<li><a href="' . Yii::app()->createUrl('site/promotions') . '" class="documents">Promotions</a></li>
                                <li><a href="' . Yii::app()->createUrl('site/featured') . '" class="messages">Featured Items</a></li>-->' . $menuBuilder->buildmenu(8) . '</ul></li>
                                    <li><!-- Do not add any class for links with dropdown --> 
            <a href="' . Yii::app()->createUrl('site/contact') . '">Contact us <span class="arrow"></span></a> 
          </li></ul></div></div></div><div class="container"><div class="header"><div class="logo_outerbox">
          <div class="logo"> <a href="' . Yii::app()->createUrl('site/index') . '">
              <img src="' . Yii::app()->baseUrl . '/images/logo_05.png"  alt="Dlink Logo" /></a> </div>';
        $cfile = Yii::app()->file->set(Yii::getPathOfAlias('application') . '/views/front/site/_top_menu1.php');
        $cfile->setContents($menustring, true);

        $menustring = '<div class="main_menu"><ul id="topnav">';
        $mod_user_group=new UserGroup();
        $userGroups = $mod_user_group->findAll(array('condition' => 'isActive="Y" AND show_in_partner="Y"'));
        foreach ($userGroups as $eachUserGroup) {
            $mod_pdt_gp= new ProductGroup();
            $menustring .='<li><a href="#">' . $eachUserGroup->group_name . '</a> <span><div class="menu_product_outer"><div class="browse_outer"> Browse ' . $eachUserGroup->group_name . ' Categories: </div>' . $productGroups = $mod_pdt_gp->findAll(array('condition' => 'user_group_id=' . $eachUserGroup->id . ' AND isActive="Y" AND show_in_partner="Y"'));
            foreach ($productGroups as $eachProductGroup) {
                $mod_pdt=new Product();
                $p = $mod_pdt->with('productMapping')
                        ->together(true)
                        ->find(array(
                    'select' => '*, rand() as rand',
                    'order' => 'rand',
                    'condition' => '(t.isActive="Y" AND  
                                    t.category_id=' . $eachUserGroup->id . ' AND
                                    t.product_category_id =' . $eachProductGroup->id . ') OR
                                    (t.isActive="Y" AND  
                                    productMapping.category_id=' . $eachUserGroup->id . ' AND
                                    productMapping.product_category_id =' . $eachProductGroup->id . ')'));
                if ($p != null) {
                    $menustring .='<a href="' . Yii::app()->createUrl('site/productgroup', array('id' => $eachProductGroup->id, 'user_group_id' => $eachUserGroup->id, 'name' => preg_replace('/[^a-z0-9_]/', '', strtolower(str_replace(" ", "_", $eachProductGroup->product_group_name))))) . '"><div class="menuproduct_outer">';
                    if ($eachProductGroup->product_group_icon != '' && file_exists('media/product_group_images/' . $eachProductGroup->product_group_icon) /* && !file_exists('media/product_group_images/140_80'.$eachProductGroup->product_group_image) */) {
                        $thumb = Yii::app()->phpThumb->create('media/product_group_images/' . $eachProductGroup->product_group_icon);
                        $thumb->resize(130, 70);
                        $thumb->save('media/product_group_images/140_80' . $eachProductGroup->product_group_icon);
                    }
                    $menustring .='<div class="menuproduct_imgbox"> <img style="display: block;margin: auto; padding: 2px;" src="' . Yii::app()->baseUrl . '/media/product_group_images/' . (($eachProductGroup->product_group_icon != '') ? '140_80' . $eachProductGroup->product_group_icon : 'noimage_dlink.png') . '" alt="' . $eachProductGroup->product_group_icon . '"  /></div><div class="menuproduct_namebox">' . $eachProductGroup->product_group_name . ' </div></div></a>';
                }
            }
            $menustring .='<div class="viewall"><a class="view_button" href="' . Yii::app()->createUrl('site/products', array('user_group_id' => $eachUserGroup->id, 'name' => preg_replace('/[^a-z0-9_]/', '', strtolower(str_replace(" ", "_", $eachUserGroup->group_name))))) . '">View all ' . $eachUserGroup->group_name . ' products</a></div></div></span></li>';
        }
        $menustring .='</ul></div></div>';
        $cfile = Yii::app()->file->set(Yii::getPathOfAlias('application') . '/views/front/site/_top_menu2.php');
        $cfile->setContents($menustring, true);


        $menustring = '<div class="content2_outerbox"><nav><ul id="tabs" style=" list-style:none">';
        $section = '';
        $mod_user_group=new UserGroup();
        $userGroups = $mod_user_group->findAll(array('condition' => 'isActive="Y" AND show_in_partner="Y"'));
        foreach ($userGroups as $eachUserGroup) {
            $menustring .='<li><a class="current" href="javascript:;">' . $eachUserGroup->group_name . '</a></li>';
            $mod_pdt_group=new ProductGroup();
            $productGroups = $mod_pdt_group->findAll(array('limit' => 4, 'condition' => 'user_group_id=' . $eachUserGroup->id . ' AND isActive="Y" AND show_in_partner="Y"'));
            $section .= '<section><div class="product_tabbox"><div class="product_tab_linkbox">' . $eachUserGroup->group_name . '</div>';
            foreach ($productGroups as $eachProductGroup) {
                if ($eachProductGroup->product_group_icon != '' && file_exists('media/product_group_images/' . $eachProductGroup->product_group_icon)) {
                    $thumb = Yii::app()->phpThumb->create('media/product_group_images/' . $eachProductGroup->product_group_icon);
                    $thumb->resize(200, 110);
                    $thumb->save('media/product_group_images/200_1101' . $eachProductGroup->product_group_icon);
                }
                $image = ($eachProductGroup->product_group_icon != '') ? '200_1101' . $eachProductGroup->product_group_icon : 'noimage_dlink.png';
                $section .= '<a href="' . Yii::app()->createUrl('site/productgroup', array('user_group_id' => $eachProductGroup->user_group_id, 'id' => $eachProductGroup->id)) . '"><div class="product_tabbox"><div class="product_outer"><div class="product_imgbox"> <img style="display: block;margin: auto;" src="' . Yii::app()->baseUrl . '/media/product_group_images/' . $image . '"  alt="' . $eachProductGroup->product_group_name . '" /></div><div class="product_namebox">' . $eachProductGroup->product_group_name . '</div></div></div></a>';
            }
            $section .= ' </div></section>';
        }
        $menustring .='</ul><span id="indicator"></span> </nav><div id="content">' . $section . '</div></div>';

        $cfile = Yii::app()->file->set(Yii::getPathOfAlias('application') . '/views/front/site/_bottom_common_user_product_group.php');
        $cfile->setContents($menustring, true);

        echo '<script>alert("Updated menus"); window.close();</script>';
        //$this->redirect(array('index'));    
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        $this->pageTitle.=' - Home';
        $mod_news=new News();
        $news = $mod_news->findAll(array(
            'limit' => '5',
            'order' => 'date',
            'condition' => 'isActive="Y"')); //news
        $mod_paper = new Paper();
        $caseStudies = $mod_paper->findAll(array(
            'select' => '*, rand() as rand',
            'limit' => '3',
            'order' => 'rand',
            'condition' => 'isActive="Y"'));
        //$newsletters	=	Newsletter::getAllNewsLetters();		
        $this->render('index', array(
            'news' => $news,
            'caseStudies' => $caseStudies
        ));
    }

    public function actionPage($id) {
        if ((!isset(Yii::app()->user->wallet) || Yii::app()->user->wallet == null) && $id == 61) {
            $this->redirect(array('wallet'));
        } else {
            $mod_page = new Page();
            $model = $mod_page->findByAttributes(array('menu_id' => $id));
            if ($model === null) {
                $model = new Page;
                $model->page_title = "Content will be updated soon";
                $this->pageTitle.=' - ' . $model->page_title;
                $model->content = "Content will be updated soon";
            }
            //throw new CHttpException(404,'The requested page does not exist.');
            /* else
              { */
            $this->render('pages/pages', array(
                'model' => $model
            ));
        }
        //}
    }

    /**
     * dlinkchannelpartnerprogram
     */
    public function actionDlinkchannelpartnerprogram() {
        $this->pageTitle = "D-Partner | Channel Partner Program";
        $this->render('dlinkchannelpartnerprogram');
    }

    /**
     * partnerlevel
     */
    public function actionPartnerlevel() {
        $this->pageTitle = "D-Partner | Channel Partner Level";
        $this->render('partnerlevel');
    }

    /**
     * technologyspecializations
     */
    public function actionTechnologyspecializations() {
        $this->pageTitle = "D-Partner | Technology Specializations";
        $this->render('technologyspecializations');
    }

    /**
     * businesssolutionoverview
     */
    public function actionBusinesssolutionoverview() {
        $this->pageTitle = "D-Partner | Business Solution Overview";
        $this->render('businesssolutionoverview');
    }

    /**
     * switchsolution
     */
    public function actionSwitchsolution() {
        $this->pageTitle = "D-Partner | Switch Solution";
        $this->render('switchsolution');
    }

    /**
     * businesswirelesssolution
     */
    public function actionBusinesswirelesssolution() {
        $this->pageTitle = "D-Partner | Business Wireless Solution";
        $this->render('businesswirelesssolution');
    }

    /**
     * surveillance
     */
    public function actionSurveillance() {
        $this->pageTitle = "D-Partner | Surveillance";
        $this->render('surveillance');
    }

    /**
     * storage
     */
    public function actionStorage() {
        $this->pageTitle = "D-Partner | Storage";
        $this->render('storage');
    }

    /**
     * networksecurity
     */
    public function actionNetworksecurity() {
        $this->pageTitle = "D-Partner | Network Security";
        $this->render('networksecurity');
    }

    /**
     * networkmanagementsolution
     */
    public function actionNetworkmanagementsolution() {
        $this->pageTitle = "D-Partner | Network Management Solution";
        $this->render('networkmanagementsolution');
    }

    /**
     * alliance
     */
    public function actionAlliance() {
        $this->pageTitle = "D-Partner | Alliance";
        $this->render('alliance');
    }

    /**
     * thegreenbow
     */
    public function actionThegreenbow() {
        $this->pageTitle = "D-Partner | The Green Bow";
        $this->render('thegreenbow');
    }

    /**
     * tomizone
     */
    public function actionTomizone() {
        $this->pageTitle = "D-Partner | Tomi Zone";
        $this->render('tomizone');
    }

    /**
     * flash
     */
    public function actionFlash() {
        $this->pageTitle = "D-Partner | Flash";
        $this->render('flash');
    }

    /**
     * graphicresources
     */
    public function actionGraphicresources() {
        $this->pageTitle = "D-Partner | Graphic Resources";
        $this->render('graphicresources');
    }

    /**
     * marketinformation
     */
    public function actionMarketinformation() {
        $this->pageTitle = "D-Partner | Market Information";
        $this->render('marketinformation');
    }

    /**
     * marketingtoolbox
     */
    public function actionMarketingtoolbox() {
        $this->pageTitle = "D-Partner | Marketing Toolbox";
        $this->render('marketingtoolbox');
    }

    /**
     * events
     */
    public function actionEvents() {
        $this->pageTitle = "D-Partner | Events";
        $mod_events = new Events();
        $events = $mod_events->getAllEvents();
        $this->render('events', array('events' => $events));
    }

    /**
     * seminarorroadshow
     */
    public function actionSeminarorroadshow() {
        $this->pageTitle = "D-Partner | Seminar / Roadshow";
        $this->render('seminarorroadshow');
    }

    /**
     * monthlynewsletter
     */
    public function actionMonthlynewsletter() {
        $this->pageTitle = "D-Partner | Monthly Newsletter";
        $this->render('monthlynewsletter');
    }

    /**
     * pressresource
     */
    public function actionPressresource() {
        $this->pageTitle = "D-Partner | Press Resource";
        $this->render('pressresource');
    }

    /**
     * newscoverage
     */
    public function actionNewscoverage() {
        $this->pageTitle = "D-Partner | News Coverage";
        $this->render('newscoverage');
    }

    /**
     * publications
     */
    public function actionPublications() {
        $this->pageTitle = "D-Partner | Publications";
        $this->render('publications');
    }

    /**
     * videoresource
     */
    public function actionVideoresource() {
        $this->pageTitle = "D-Partner | Video Resource";
        $this->render('videoresource');
    }

    /**
     * videoclip
     */
    public function actionVideoclip() {
        $this->pageTitle = "D-Partner | Video Clip";
        $this->render('videoclip');
    }

    /**
     * downloadlibrary
     */
    public function actionDownloadlibrary() {
        $this->pageTitle = "D-Partner | Download Library";
        $this->render('downloadlibrary');
    }

    /**
     * aespec
     */
    public function actionAespec() {
        $this->pageTitle = "D-Partner | Aespec";
        $this->render('aespec');
    }

    /**
     * configurationguide
     */
    public function actionConfigurationguide() {
        $this->pageTitle = "D-Partner | Configuration Guide";
        $this->render('configurationguide');
    }

    /**
     * whitepaper
     */
    public function actionWhitepaper() {
        $this->pageTitle = "D-Partner | Whitepaper";
        $this->render('whitepaper');
    }

    /**
     * salesguide
     */
    public function actionSalesguide() {
        $this->pageTitle = "D-Partner | Sales Guide";
        $this->render('salesguide');
    }

    /**
     * software
     */
    public function actionSoftware() {
        $this->pageTitle = "D-Partner | Softwares";
        $this->render('software');
    }

    /**
     * firmware
     */
    public function actionFirmware() {
        $this->pageTitle = "D-Partner | Firmwares";
        $this->render('firmware');
    }

    /**
     * manual
     */
    public function actionManual() {
        $this->pageTitle = "D-Partner | Manuals";
        $this->render('manual');
    }

    /**
     * trainingmeterials
     */
    public function actionTrainingmaterials() {
        $this->pageTitle = "D-Partner | Training Materials";
        $this->render('trainingmaterials');
    }

    /**
     * testreport
     */
    public function actionTestreport() {
        $this->pageTitle = "D-Partner | Test Report";
        $this->render('testreport');
    }

    /**
     * productimage
     */
    public function actionProductimage() {
        $this->pageTitle = "D-Partner | Product Image";
        $this->render('productimage');
    }

    /**
     * worddescriptions
     */
    public function actionWorddescriptions() {
        $this->pageTitle = "D-Partner | Word Descriptions";
        $this->render('worddescriptions');
    }

    /**
     * videoclip
     */
    public function actionConfigurationexample() {
        $this->pageTitle = "D-Partner | Configuration Example";
        $this->render('configurationexample');
    }

    /**
     * toolsforpartners
     */
    public function actionToolsforpartners() {
        $this->pageTitle = "D-Partner | Tools for Partners";
        $this->render('toolsforpartners');
    }

    /**
     * productselectorpro
     */
    public function actionProductselectorpro() {
        $this->pageTitle = "D-Partner | Product Selector Pro";
        $this->render('productselectorpro');
    }

    /**
     * wifiplanner
     */
    public function actionWifiplanner() {
        $this->pageTitle = "D-Partner | Wi-fi- Planner";
        $this->render('wifiplanner');
    }

    /**
     * productinterfaceviewer
     */
    public function actionProductinterfaceviewer() {
        $this->pageTitle = "D-Partner | Product Interface Viewer";
        $this->render('productinterfaceviewer');
    }

    /**
     * surveilanceprojectdesigner
     */
    public function actionSurveilanceprojectdesigner() {
        $this->pageTitle = "D-Partner | Surveilance Project Designer";
        $this->render('surveilanceprojectdesigner');
    }

    /**
     * wirelesscalculator
     */
    public function actionWirelesscalculator() {
        $this->pageTitle = "D-Partner | Wireless Calculator";
        $this->render('wirelesscalculator');
    }

    /**
     * switchemulator
     */
    public function actionSwitchemulator() {
        $this->pageTitle = "D-Partner | Switch Emulator";
        $this->render('switchemulator');
    }

    /**
     * firewallemulator
     */
    public function actionFirewallemulator() {
        $this->pageTitle = "D-Partner | Firewall Emulator";
        $this->render('firewallemulator');
    }

    /**
     * certification
     */
    public function actionCertification() {
        $this->pageTitle = "D-Partner | Certification";
        $this->render('certification');
    }

    /**
     * certificationfaq
     */
    public function actionCertificationfaq() {
        $this->pageTitle = "D-Partner | Certification Faq";
        $this->render('certificationfaq');
    }

    /**
     * training
     */
    public function actionTraining() {
        $this->pageTitle = "D-Partner | Training";
        $this->render('training');
    }

    /**
     * trainingschedule
     */
    public function actionTrainingschedule() {
        $this->pageTitle = "D-Partner | Training Schedule";
        $this->render('trainingschedule');
    }

    /**
     * onlineexam
     */
    public function actionOnlineexam() {
        $this->pageTitle = "D-Partner | Online Exam";
        $this->render('onlineexam');
    }

    public function actiontoolsMenudetails() {
        $this->pageTitle = "D-Partner | Online Exam";
        $this->render('toolsMenuDetails');
    }
    /**
     * Registration
     */
    public function actionRegistration() {

        $this->pageTitle .= " - Registration";

        $model = new User('user_signup');
        
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

        //if ((count($_POST) > 0)&& isset($_POST['User'])) { //PHP 5
        if ((!empty($_POST)) && isset($_POST['User'])) {

            $model->attributes = $_POST['User'];
            $model->user_type_id = 1;
            $model->isActive = 'N';
            $session = new CHttpSession;
            $session->open();
            $model->authCode = $session->getSessionID() . time();
           
            //$model->isConfirmed	=	'Y';
            if ($model->save()) {

                Yii::app()->user->setFlash('success', "Successfully registered!");

               /* $mailContent = array();
                $mailContent['fullname'] = $model->fullname;
                $mailContent['confirmLink'] = Yii::app()->createAbsoluteUrl('site/confirmEmail', array('token' => $model->authCode));

                $message = new YiiMailMessage;
                $message->view = 'emailVerification';

                $message->setBody(array('mailContent' => $mailContent), 'text/html');
                $message->subject = 'Dlink Email Confirmation ';

                //$message->from	=	Yii::app()->params['adminEmail'];
                $message->from = 'noreply@me.dlink.com';
                $message->addTo($model->company_email_address);
                $swiftAttachment = Swift_Attachment::fromPath('images/dmailsignature.jpg'); // create a Swift Attachment
                $message->attach($swiftAttachment);
                Yii::app()->mail->send($message);
                Yii::app()->user->setFlash('success', 'Registartion completed successfully,please check your email and follow the instructions .');*/

                $this->redirect('registration_success', array('model' => $model));
            }
        }

        $this->render('editprofile', array(
            'model' => $model,
        ));
    }

    public function actionRegistration_success($model = null) {
        $this->pageTitle .= " - Registration completed";
        $this->render('registration_success', array('model' => $model));
    }

    /* email verification */

    public function actionConfirmEmail($token = null) {
        $this->pageTitle .= " - Registration final step";
        if ($token != null) {
            $model = new User;
            $model = $model->findByAttributes(array('authCode' => $token));
            if ($model === null) {
                Yii::app()->user->setFlash('error', "Already Confirmed or Invalid key");
                $this->redirect(array('login'));
            } else {
                $model->authCode = '';
                $model->isConfirmed = 'Y';
                $model->isActive = 'Y';
                //$model->wallet_password	= $this->get_random_string('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqestuvwxyz1234567890',8);
                $model->save(false);

                //Yii::app()->user->setFlash('success', "Sucessfully confirmed your email. Please wait for admin approval");
                $this->render('account_activated');
            }
        }
        //die("error!");	
    }

    public function actionRequestwallet() {
        $this->pageTitle .= " - Request a wallet password";
        $model_user = new User();
        $model = $model_user->findByPk(Yii::app()->user->id);
        if(($model->wallet_password=='' || $model->wallet_password==null)){ 
            $model->isWalletPaswdRequested = 'Y';
            $model->save(false);
            $mailContent = array();
            $mailContent['fullname'] = $model->fullname;
            //$mailContent['confirmLink'] = Yii::app()->createAbsoluteUrl('site/confirmEmail',array('token'=>$model->authCode));

            $message = new YiiMailMessage;
            $message->view = 'walletPassrequest';

            $message->setBody(array('mailContent' => $mailContent), 'text/html');
            $message->subject = 'Dlink:Wallet Password Request ';

            $message->from = 'noreply@me.dlink.com';//$model->company_email_address;
            $message->addTo(Yii::app()->params['adminEmail']);
            $message->addTo('tthomas@me.dlink.com');
            //$message->addTo('jisha@mailbluesky.com');
            $swiftAttachment = Swift_Attachment::fromPath('images/dmailsignature.jpg'); // create a Swift Attachment
            $message->attach($swiftAttachment);
            //$message->addTo('arun.p.muthukulam@gmail.com');
            Yii::app()->mail->send($message);
        }else{
            $wallet_password	= $this->get_random_string('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqestuvwxyz1234567890',8);
            $model->isWalletPaswdRequested	=	'N';
            $model->wallet_password	=	md5($wallet_password);
            $model->save(false);
            
            $mailContent = array();
            $mailContent['fullname'] = $model->fullname; 
            $mailContent['walletpassword'] = $wallet_password;

            $message = new YiiMailMessage;
            $message->view = 'emailWalletPassword';

            $message->setBody(array('mailContent'=>$mailContent), 'text/html');
            $message->subject = 'Dlink Wallet Password (New) ';

            $message->from	=	'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
            $message->addTo($model->company_email_address);
            Yii::app()->mail->send($message);

            
            //Yii::app()->user->setFlash('success','Password request sent successfully .');
        }
    }

    function get_random_string($valid_chars, $length) {
        // start with an empty random string
        $random_string = "";
        // count the number of chars in the valid chars string so we know how many choices we have
        $num_valid_chars = strlen($valid_chars);
        // repeat the steps until we've created a string of the right length
        for ($i = 0; $i < $length; $i++) {
            // pick a random number from 1 up to the number of valid chars
            $random_pick = mt_rand(1, $num_valid_chars);
            // take the random character out of the string of valid chars
            // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
            $random_char = $valid_chars[$random_pick - 1];
            // add the randomly-chosen char onto the end of our string so far
            $random_string .= $random_char;
        }
        // return our finished random string
        return $random_string;
    }

    /**
     * viewprofile
     */
    public function actionViewprofile() {
        $this->pageTitle .= " - My Profile";

        $model_user = new User();
        $model = $model_user->findByPk(Yii::app()->user->id);
        //$random	=	$mod_pdt->findAll(array('condition'=>' isActive="Y"','select'=>'*, rand() as rand','limit'=>2,'order'=>'rand'));

        $this->render('viewprofile', array('model' => $model, /* 'random'=>$random */));
    }

    /**
     * editprofile
     */
    public function actionEditprofile() {
        $this->pageTitle .= " - Edit profile";

        $model = new User('update');
        //$random	=	$mod_pdt->findAll(array('condition'=>' isActive="Y"','select'=>'*, rand() as rand','limit'=>2,'order'=>'rand'));

        $model = $model->findByPk(Yii::app()->user->id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', 'Successfully updated');
                $this->redirect(array('viewprofile'));
            }
        }
        $this->render('editprofile', array(
            'model' => $model,
                //'random'=>$random
        ));
    }

    /**
     * changepassword
     */
    public function actionChangepassword() {
        $this->pageTitle .= " - Change password";

        $model_user = new User();
        $model = $model_user->findByPk(Yii::app()->user->id);
        $mod_pdt = new Product();
        $random = $mod_pdt->findAll(array('condition' => ' isActive="Y"', 'select' => '*, rand() as rand', 'limit' => 2, 'order' => 'rand'));
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
         $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if ((count($_POST) > 0) && isset($_POST['User'])) {
            $model->scenario = 'change_my_password';
            $model->old_password = $_POST['User']['old_password'];

            if ($model->password == md5($model->old_password)) {
                $model->password = $_POST['User']['password'];
                $model->repeat_password = $_POST['User']['repeat_password'];
                if ($model->validate()) {
                    $model->save();
                    Yii::app()->user->setFlash('success', 'Successfully changed');
                    $this->redirect(array('changepassword'));
                }
            }
            else
                $model->addError('old_password', 'Old password is wrong.');
        }
        $this->render('changepassword', array(
            'model' => $model,
            'random' => $random
        ));
    }

    /**
     * submitpaper
     */
    public function actionSubmitpaper() {
        $this->pageTitle .= " - Submit a Paper";
        $model = new Paper;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if ((count($_POST) > 0) && isset($_POST['Paper'])) {
            $rnd = rand(0, 9999);  // generate random number between 0-9999
            $model->attributes = $_POST['Paper'];
            $uploadedFile = CUploadedFile::getInstance($model, 'filename');
            if (!empty($uploadedFile)) {  // check if uploaded file is set or not
                $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
                $model->filename = $fileName;
            }
            $model->user_id = Yii::app()->user->id;
            $model->date_added = date('Y-m-d');
            if ($model->save()) {
                if (!empty($uploadedFile)) {
                    $uploadedFile->saveAs(Yii::app()->basePath . '/../media/paper/' . $fileName);  // image will uplode to rootDirectory/banner/
                }
                Yii::app()->user->setFlash('success', 'Successfully submitted');
                $this->redirect(array('submitpaper'));
            }
        }
        $this->render('submitpaper', array(
            'model' => $model,
        ));
    }
    /*
     * check Serial No
     */
    public function actionCheckSerialNo(){
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (!empty($_POST)){
            $product_id = $_POST['product_id'];
            $serial_no  = $_POST['serial_no'];
            $mod_reward_pdts=new RewardProducts();
            $arr_agent = $mod_reward_pdts->findAll(array('condition' => 'serial_no="' . $serial_no. '"'));
            if(!empty($arr_agent)){
                $jsonData['status'] = 'fail';
            } else {
                $jsonData['status'] = 'success';

            }
        }else{
             $jsonData['status'] = 'fail';
        }
        echo CJSON::encode($jsonData);
    }
    /**
     * pointstable
     */
    public function actionPointstable() {
        if (isset(Yii::app()->user->wallet) && Yii::app()->user->wallet != null) {
            $this->pageTitle .= " - Point Stable";
            /* $model = Reward::model()->with('product')->findAll(array(
              'condition' => 'user_id=' . Yii::app()->user->id . ' AND t.isActive="Y"'
              ));
              if ($model === null)
              throw new CHttpException(404, 'The requested page does not exist.');
              //$random	=	Product::model()->findAll(array('condition'=>' isActive="Y"','select'=>'*, rand() as rand','limit'=>2,'order'=>'rand'));
              $this->render('pointstable', array('model' => $model,
              //'random'=>$random
              )); */
            $mod_pdt = new Product();
            $model = $mod_pdt->findAll(array('condition' => 'isIntoPromotion="Y" AND rewardPoints > 0', 'order' => 'rewardPoints'));
            if ($model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
            $this->render('pointstable', array('model' => $model));
        }
        else
            $this->redirect(array('mywallet'));
    }

    public function actionWallet() {
        $this->pageTitle .= " - My wallet";
        if (isset(Yii::app()->user->wallet) && Yii::app()->user->wallet != null) {
            $mod_pdt = new Product();
            $random = $mod_pdt->findAll(array('condition' => ' isActive="Y"', 'select' => '*, rand() as rand', 'limit' => 2, 'order' => 'rand'));
            $model_reward=new Reward();
            $model = $model_reward->findAll(array('condition' => 'user_id = ' . Yii::app()->user->id));
            $mod_user=new User();
            $nameOfUser = $mod_user->findByPk(Yii::app()->user->id)->fullname;

            $temp = $model_reward->findBySql('select sum(`point`) as `sum` from {{_reward}} where isActive="Y" AND user_id=' . Yii::app()->user->id, array());
            $totalRewardPoints = $temp->sum > 0 ? $temp->sum : 0;
            $mod_red_points=new RedeemedPoints();
            $temp = $mod_red_points->findBySql('select sum(`point`) as `sum` from {{_redeemed_points}} where user_id=' . Yii::app()->user->id, array());
            $redeemedRewardPoints = $temp->sum > 0 ? $temp->sum : 0;
            $redeemableRewardPoints = $totalRewardPoints - $redeemedRewardPoints;

            $this->render('wallet', array(
                'totalRewardPoints' => $totalRewardPoints,
                'redeemedRewardPoints' => $redeemedRewardPoints,
                'redeemableRewardPoints' => $redeemableRewardPoints,
                'nameOfUser' => $nameOfUser,
                'model' => $model,
                'random' => $random));
        }
        else
            $this->redirect(array('mywallet'));
    }

    /**
     * mywallet
     */
    public function actionMywallet() {
        //die(Yii::app()->user->wallet);
        $this->pageTitle .= "- My Wallet";
        //$random	=	Product::model()->findAll(array('condition'=>' isActive="Y"','select'=>'*, rand() as rand','limit'=>2,'order'=>'rand'));

        if (isset(Yii::app()->user->wallet) && Yii::app()->user->wallet != null) {
            $this->redirect(array('wallet'));
        } else {
            $model = new User('wallet');
            $model = $model->findByPk(Yii::app()->user->id);
            // Uncomment the following line if AJAX validation is needed
            // $this->performAjaxValidation($model);
            $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
            if ((count($_POST) > 0)&& isset($_POST['User'])) {
                $wallet_password = md5($_POST['User']['wallet_password']);

                $mod_user=new User();
                $w = $mod_user->find('id=? AND wallet_password=? AND isActive=?  AND isConfirmed=?', array(Yii::app()->user->id, $wallet_password, 'Y', 'Y'));

                if ($w == null) {

                    $model->addError('wallet_password', 'Incorrect password');
                } else {
                    Yii::app()->user->setState('wallet', $w->fullname);
                    $this->redirect(array('wallet'));
                }
            }
            $this->render('mywallet', array('model' => $model, /* 'random'=>$random */));
        }
    }

    public function actionCasestudy() {
        
        $this->pageTitle .= " - Case Studies";
        $model = new Paper;
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if((count($_POST) > 0)&&(isset($_POST['usergroup']) || isset($_POST['region']) || isset($_POST['year']) || isset($_POST['industry']))) {
            if (isset($_POST['usergroup'])) {
                $condition = 'isActive="Y"';
                if ($_POST['usergroup'] != '')
                $condition .= ' AND user_group_id=' . $_POST['usergroup'];
                $mod_paper= new Paper();
                $caseStudies = $mod_paper->findAll(array('condition' => $condition));
            }
            if (isset($_POST['region'])) {
                $condition = 'isActive="Y"';
                if ($_POST['region'] != '')
                $condition .= ' AND region_id=' .'"'. $_POST['region'].'"';
                $mod_paper= new Paper();
                $caseStudies = $mod_paper->findAll(array('condition' => $condition));
            }
            if (isset($_POST['year'])) {
                $condition = 'isActive="Y"';
                if ($_POST['year'] != '')
                $condition .= ' AND year=' . $_POST['year'];
                $mod_paper= new Paper();
                $caseStudies = $mod_paper->findAll(array('condition' => $condition));
            }
            if (isset($_POST['industry'])) {
                $condition = 'isActive="Y"';
                if ($_POST['industry'] != '')
                $condition .= ' AND industry_id=' . $_POST['industry'];
                $mod_paper= new Paper();
                $caseStudies = $mod_paper->findAll(array('condition' => $condition));
            }
//print_r  (count($caseStudies));die();
        /*$this->render('caseStudies', array(
            'model' => $model,
            'caseStudies' => $caseStudies,
            'pages' => $pages
        ));*/
            if(count($caseStudies) == 0){
               $jsondata['info'].= "No Records Found" ;
            }
            else{
                foreach($caseStudies as $value){
                //$jsondata['info'].='<tr><td>'. $eachkeywords->keyword.'</td>';

                    $jsondata['info'].='<div class="filter-wrapper">';
                    $jsondata['info'].='<div class="img-outer">';
                    $jsondata['info'].='<img src="'.Yii::app()->request->baseUrl.'/media/casestudy/thumb/'.$value->image.'" alt="No Image"/>';
                    $jsondata['info'].='</div>';
                    $jsondata['info'].='<div class="title-outer">';
                    $jsondata['info'].='<h2>'.$value->image_title.'</h2>';
                    $jsondata['info'].='<span class="entryDate">'.date('M d, Y', strtotime($value->date_added)) .'</span>';
                    $jsondata['info'].='</div>';
                    $jsondata['info'].='<div class="content-outer">';
                    $jsondata['info'].='<h4>'.$value->title_of_the_paper .'</h4>'. substr(strip_tags($value->content),0,80).'<br>' ;


                    $jsondata['info'].='<a class="case-download" href="'.Yii::app()->request->getBaseUrl(true).'/media/paper/'.$value->filename.'" target="_blank">Download pdf</a></br>';
                    $jsondata['info'].='</div>';
                    $jsondata['info'].='</div> ';
                }
            }
            $jsondata['status'] = 'success2';
                            echo CJSON::encode($jsondata);
                            Yii::app()->end();
        }
        else{
            $criteria = new CDbCriteria();
            $criteria->condition = 'isActive="Y"';
            $mod_paper=new Paper();
            $count = $mod_paper->count($criteria);
            $pages = new CPagination($count);
            $pages->pageSize = 10;
            $pages->applyLimit($criteria);
            $caseStudies = $mod_paper->findAll($criteria);
                $this->render('caseStudies', array(
                'model' => $model,
                'caseStudies' => $caseStudies,
                'pages' => $pages
            ));
        }

        /*$this->pageTitle .= " - Case Studies";
        $model = new Paper;
        $criteria = new CDbCriteria();
        $criteria->condition = 'isActive="Y"';
        $count = Paper::model()->count($criteria);
        //print_r($count);die();
        $pages = new CPagination($count);
        $pages->pageSize = 10;
        $pages->applyLimit($criteria);*/
        //$caseStudies = Paper::model()->findAll(array('condition' => 'isActive="Y"', 'limit' => '10'));
         // $caseStudies = Paper::model()->findAll(array('condition' => 'isActive="Y"'));
        //$caseStudies = Paper::model()->findAll($criteria);
//        if (isset($_POST['Paper'])) {
//            $condition = 'isActive="Y"';
//            if ($_POST['Paper']['user_group_id'] != '')
//                $condition .= ' AND user_group_id=' . $_POST['Paper']['user_group_id'];
//            if ($_POST['Paper']['product_group_id'] != '')
//                $condition .= ' AND product_group_id=' . $_POST['Paper']['product_group_id'];
//            if ($_POST['Paper']['product_category_id'] != '' && $_POST['Paper']['product_category_id'] != 0)
//                $condition .= ' AND product_category_id=' . $_POST['Paper']['product_category_id'];
//            if ($_POST['Paper']['region_id'] != '')
//                $condition .= ' AND region_id=' .'"'. $_POST['Paper']['region_id'].'"';
//            if ($_POST['Paper']['industry_id'] != '')
//                $condition .= ' AND industry_id=' . $_POST['Paper']['industry_id'];
//            if ($_POST['Paper']['year'] != '')
//                $condition .= ' AND year=' . $_POST['Paper']['year'];
//            $caseStudies = Paper::model()->findAll(array('condition' => $condition));
//        }

        
    }
    
    public function actionfilter() {

        $this->pageTitle .= " - Case Studies";
        $model = new Paper;
        $mod_paper = new Paper;
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if((count($_POST) > 0)&&(isset($_POST['usergroup']))) {
            $condition = 'isActive="Y"';
            if ($_POST['usergroup'] != '')
            $condition .= ' AND user_group_id=' . $_POST['usergroup'];
            $caseStudies = $mod_paper->findAll(array('condition' => $condition));
        }
        if ((count($_POST) > 0)&&(isset($_POST['region']))) {
            $condition = 'isActive="Y"';
            if ($_POST['region'] != '')
            $condition .= ' AND region_id=' .'"'. $_POST['region'].'"';
            $caseStudies = $mod_paper->findAll(array('condition' => $condition));
        }
        if ((count($_POST) > 0)&&(isset($_POST['year']))) {
            $condition = 'isActive="Y"';
            if ($_POST['year'] != '')
            $condition .= ' AND year=' . $_POST['year'];
            $caseStudies = $mod_paper->findAll(array('condition' => $condition));
        }
        if ((count($_POST) > 0)&&(isset($_POST['industry']))) {
            $condition = 'isActive="Y"';
            if ($_POST['industry'] != '')
            $condition .= ' AND industry_id=' . $_POST['industry'];
            $caseStudies = $mod_paper->findAll(array('condition' => $condition));
        }
        if(count($caseStudies) == 0){
           $jsondata['info'].= "No Records Found" ;
        }
        else{
            foreach($caseStudies as $value){
                //$jsondata['info'].='<tr><td>'. $eachkeywords->keyword.'</td>';

                $jsondata['info'].='<div class="filter-wrapper">';
                $jsondata['info'].='<div class="img-outer">';
                $jsondata['info'].='<img src="'.Yii::app()->request->baseUrl.'/media/casestudy/'.$value->image.'" alt="case-pic"/>';
                $jsondata['info'].='</div>';
                $jsondata['info'].='<div class="title-outer">';
                $jsondata['info'].='<h2>'.$value->image_title.'</h2>';
                $jsondata['info'].='<span class="entryDate">'.date('M d, Y', strtotime($value->date_added)) .'</span>';
                $jsondata['info'].='</div>';
                $jsondata['info'].='<div class="content-outer">';
                $jsondata['info'].='<h4>'.$value->title_of_the_paper .'</h4>'. substr(strip_tags($value->content),0,80).'<br>' ;


                $jsondata['info'].='<a class="case-download" href="'.Yii::app()->request->getBaseUrl(true).'/media/paper/'.$value->filename.'" target="_blank">Download pdf</a></br>';
                $jsondata['info'].='</div>';
                $jsondata['info'].='</div> ';
            }
        }
        $jsondata['status'] = 'success2';
                            echo CJSON::encode($jsondata);
                            Yii::app()->end();
                            
         
        
    }

    public function actionCasestudy_readmore($id) {
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        $mod_paper = new Paper;
        if(count($_POST) > 0){
            $model = $mod_paper->findByPK($id);
            $this->pageTitle .= " - " . $model->title_of_the_paper;
            $this->render('casestudy_readmore', array(
                'model' => $model,
            ));
        }else{
            $this->render('404');
        }
        
    }

    /**
     * earnpoints
     */
    public function actionEarnpoints() {
        if (!isset(Yii::app()->user->wallet) || Yii::app()->user->wallet == null) {
            $this->redirect('mywallet');
        }else{
            $this->pageTitle .= " - Earn Points";

            $model = new Reward;
            $model_pdts = array(new RewardProducts());
            $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
            if (count($_POST) > 0 && (isset($_POST['Reward']))) {
                $rnd = rand(0, 9999);  // generate random number between 0-9999
                $model->attributes = $_POST['Reward'];
                $uploadedFile = CUploadedFile::getInstance($model, 'invoice');
                if (!empty($uploadedFile)) {  // check if uploaded file is set or not
                    $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
                    $model->invoice = $fileName;
                }
                $model->user_id = Yii::app()->user->id;
                $model->product_id ='0';
                $model->serial_number_of_product ='0';
                $model->point ='0';
                //if ($model->product_id != '')
                //    $model->point = Product::model()->findByPk($model->product_id)->rewardPoints;
                $model->date_of_entry = date('Y-m-d');
                $model->isActive = 'N';
                if ($model->save()) {
                    if (!empty($uploadedFile)) {
                        $uploadedFile->saveAs(Yii::app()->basePath . '/../media/reward_invoice/' . $fileName);  // image will uplode to rootDirectory/banner/
                    }
                    $id  = $model->id;
                    if (is_array($_POST['RewardProducts'])) {
                        $sum_points = 0;    
                        foreach ($_POST['RewardProducts'] as $i => $items) {
                            $mod_reward=new RewardProducts;
                            if (empty($items['id'])) {
                                $model_pdts[$i] = new RewardProducts;
                            } else {
                                $model_pdts[$i] = $mod_reward->findByPk($items['id']);
                            }
                            $model_pdts[$i]->attributes = $_POST['ProductInvoice'][$i];
                            $model_pdts[$i]->product_id = $items['product_id'];
                            $model_pdts[$i]->serial_no = $items['serial_no'];
                            $mod_pdt = new Product();
                            if ($model_pdts[$i]->product_id != '')
                                $model_pdts[$i]->points = $mod_pdt->findByPk($model_pdts[$i]->product_id)->rewardPoints;
                            $model_pdts[$i]->reward_id =  $id;
                            $sum_points += $model_pdts[$i]->points;
                            $model_pdts[$i]->save();
                        }

                    }
                    $model=new Reward();
                    $model = $model->findByPk($id);
                    $model->point = $sum_points;
                    $model->save(false);
                    $mod_user= new User();
                    $logd_user = $mod_user->findByPK(Yii::app()->user->id);

                    $body = '<table width="57%" border="1">
                      <tr>
                        <td width="41%">Registered User Name</td>
                        <td width="1%">&nbsp;</td>
                        <td width="58%">' . $logd_user->fullname . '</td>
                      </tr>
                      <tr>
                        <td>Customer Name</td>
                        <td>&nbsp;</td>
                        <td>' . $model->end_customer_name . '</td>
                      </tr>

                      <tr>
                        <td>Points</td>
                        <td>&nbsp;</td>
                        <td>' . $model->point . '</td>
                      </tr>
                      <tr>
                        <td>Invoice Number</td>
                        <td>&nbsp;</td>
                        <td>' . $model->invoice_number . '</td>
                      </tr>
                      <tr>
                        <td>Date of Purchase</td>
                        <td>&nbsp;</td>
                        <td>' . $model->date_of_purchase . '</td>
                      </tr>
                      <tr>
                        <td>Date of entry</td>
                        <td>&nbsp;</td>
                        <td>' . $model->date_of_entry . '</td>
                      </tr>
                    </table>
                    ';
                    $body .='<table width="57%" border="1">
                        <tr>
                            <td width="35%">Product</td>
                            <td width="35">Serial No</td>
                            <td width="30%">Points</td>
                          </tr>';
                    $mod_reward=new RewardProducts;
                    $mod_items = $mod_reward->findAll(array('condition'=>'reward_id ='.$id));
                    $mod_pdt = new Product();
                    foreach ($mod_items as $i=>$row){
                        $body .=      '  <tr>
                            <td>' . $mod_pdt->findByPk($row->product_id)->product_generic_name . '</td>
                            <td>' . $row->serial_no . '</td>
                            <td>' . $row->points . '</td>
                          </tr>';
                    }
                    $body .=      '  </table>';

                    $name = '=?UTF-8?B?' . base64_encode($logd_user->fullname) . '?=';
                    $subject = '=?UTF-8?B?' . base64_encode("DlinkMea-Partner::Redeeem point Request") . '?=';
                    $headers = "From: $name <'noreply@me.dlink.com'>\r\n" .//{$logd_user->company_email_address}
                        "Reply-To: {$logd_user->company_email_address}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-type: text/html; charset=UTF-8";

                        //mail('info.me@me.dlink.com', $subject, $body, $headers);
                        mail('tthomas@me.dlink.com', $subject, $body, $headers);
                        Yii::app()->user->setFlash('success', 'Request sent successfully!');
                        $this->redirect(array('earnpoints'));
                }else {
                    $error = CActiveForm::validate($model, '', false);
                    if ($error != '[]')
                        echo $error;        
                }
            } 
            $this->render('earnpoints', array(
                'model' => $model,
            ));
        }
        
    }

    /**
     * earnpoints
     */
    public function actionEarncertificationpoints() {
        if (!isset(Yii::app()->user->wallet) || Yii::app()->user->wallet == null) {
            $this->redirect('mywallet');
        }
        $this->pageTitle .= " - Earn Points";
        $mod_certifictn= new Certification();
            
        $model = new Reward;
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0 &&(isset($_POST['Reward']))) {
            $rnd = rand(0, 9999);  // generate random number between 0-9999
            $model->attributes = $_POST['Reward'];
            $uploadedFile = CUploadedFile::getInstance($model, 'invoice');
            if (!empty($uploadedFile)) {  // check if uploaded file is set or not
                $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
                $model->invoice = $fileName;
            }
            $model->user_id = Yii::app()->user->id;
            if ($model->product_id != '')
                $model->point = $mod_certifictn->findByPk($model->product_id)->rewardPoints;
            $model->date_of_entry = date('Y-m-d');
            $model->isActive = 'N';
            $model->invoice_number = $model->serial_number_of_product;
            $model->is_certification = "Y";
            $model->certification_id = $model->product_id;
            if ($model->save()) {
                if (!empty($uploadedFile)) {
                    $uploadedFile->saveAs(Yii::app()->basePath . '/../media/reward_invoice/' . $fileName);  // image will uplode to rootDirectory/banner/
                }
                $mod_user = new User();
                $logd_user = $mod_user->findByPK(Yii::app()->user->id);

                $body = '<table width="57%" border="1">
  <tr>
    <td width="41%">Registered User Name</td>
    <td width="1%">&nbsp;</td>
    <td width="58%">' . $logd_user->fullname . '</td>
  </tr>
  <tr>
    <td>Customer Name</td>
    <td>&nbsp;</td>
    <td>' . $model->end_customer_name . '</td>
  </tr>
  <tr>
    <td>Certification</td>
    <td>&nbsp;</td>
    <td>' . $mod_certifictn->findByPk($model->product_id)->certification_name . '</td>
  </tr>
  <tr>
    <td>Points</td>
    <td>&nbsp;</td>
    <td>' . $model->point . '</td>
  </tr>
  <tr>
    <td>Register Number</td>
    <td>&nbsp;</td>
    <td>' . $model->serial_number_of_product . '</td>
  </tr>
  <tr>
    <td>Date of Exam</td>
    <td>&nbsp;</td>
    <td>' . $model->date_of_purchase . '</td>
  </tr>
  <tr>
    <td>Date of entry</td>
    <td>&nbsp;</td>
    <td>' . $model->date_of_entry . '</td>
  </tr>
</table>
';

                $name = '=?UTF-8?B?' . base64_encode($logd_user->fullname) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode("DlinkMea-Partner::Redeeem point Request") . '?=';
                $headers = "From: $name <{'noreply@me.dlink.com'}>\r\n" .//$logd_user->company_email_address
                        "Reply-To: {$logd_user->company_email_address}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-type: text/html; charset=UTF-8";
                mail('info.me@me.dlink.com', $subject, $body, $headers);
                //mail(Yii::app()->params['adminEmail'], $subject, $body, $headers);
                Yii::app()->user->setFlash('success', 'Request sent successfully!');
                $this->redirect(array('earncertificationpoints'));
            }
        }
        $this->render('earnpoints_by_certification', array(
            'model' => $model,
        ));
    }

    /**
     * redeempoints
     */
    public function actionRedeempoints() {
        if (!isset(Yii::app()->user->wallet) || Yii::app()->user->wallet == null) {
            $this->redirect('mywallet');
        }
        $this->pageTitle .= " - Redeempoints Points";

        $mod_pdt = new Product();
        $random = $mod_pdt->findAll(array('condition' => ' isActive="Y"', 'select' => '*, rand() as rand', 'limit' => 2, 'order' => 'rand'));
        $model = new RedeemedPoints;
        $mod_rewrd = new Reward();
        $temp = $mod_rewrd->findBySql('select sum(`point`) as `sum` from {{_reward}} where isActive="Y" AND user_id=' . Yii::app()->user->id, array());
        $totalRewardPoints = $temp->sum > 0 ? $temp->sum : 0;
        $temp = $model->findBySql('select sum(`point`) as `sum` from {{_redeemed_points}} where user_id=' . Yii::app()->user->id, array());
        $redeemedRewardPoints = $temp->sum > 0 ? $temp->sum : 0;
        $redeemableRewardPoints = $totalRewardPoints - $redeemedRewardPoints;
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0 &&(isset($_POST['RedeemedPoints']))) {    
            $model->attributes = $_POST['RedeemedPoints'];
            $model->user_id = Yii::app()->user->id;
            if ($model->point < $redeemableRewardPoints) {
                $model->save();
                $mod_usr=new User();
                $logd_user = $mod_usr->findByPK(Yii::app()->user->id);
                $body = '<table width="57%" border="1">
                          <tr>
                            <td width="41%">Registered User Name</td>
                            <td width="1%">&nbsp;</td>
                            <td width="58%">' . $logd_user->fullname . '</td>
                          </tr>

                          <tr>
                            <td>Total Points</td>
                            <td>&nbsp;</td>
                            <td>' . $redeemableRewardPoints . '</td>
                          </tr>
                          <tr>
                            <td>Redeemed Points</td>
                            <td>&nbsp;</td>
                            <td>' . $model->point . '</td>
                          </tr>

                        </table>   ';

                $name = '=?UTF-8?B?' . base64_encode($logd_user->fullname) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode("DlinkMea-Partner::Redeeem point Request") . '?=';
                $headers = "From: $name <{'noreply@me.dlink.com'}>\r\n" .//$logd_user->company_email_address
                        "Reply-To: {$logd_user->company_email_address}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-type: text/html; charset=UTF-8";
                mail('tthomas@me.dlink.com', $subject, $body, $headers);
                //mail('jisha@mailbluesky.com', $subject, $body, $headers);                
                Yii::app()->user->setFlash('success', 'Redeemed point!');
                $this->redirect(array('redeempoints'));
            } else {
                $model->addError('point', 'Redeemable Points is lesser than your input!');
            }
        }
        $this->render('redeempoints', array(
            'redeemableRewardPoints' => $redeemableRewardPoints,
            'model' => $model,
            'random' => $random));
    }

    /**
     * redeempoints
     */
//    public function actionProductgroup($id, $user_group_id) { //product category listing too
//        $this->pageTitle .= " - Product categories";
//
//        $ProductGroup = ProductGroup::model()->findByPk($id);
//        $UserGroupName = UserGroup::model()->findByPk($user_group_id)->group_name;
//
//        $category = array();
//        $condition = 'isActive="Y" AND show_in_partner="Y" AND product_group_id=' . $id . ' AND user_group_id=' . $user_group_id;
//
//        $categories = ProductCategory::model()->findAll(array('condition' => $condition));
//        $j = 0;
//        foreach ($categories as $eachProductCategory) {
//            $condition = '(t.isActive="Y" AND  
//							t.product_group_id=' . $id . ' AND 
//							t.user_group_id=' . $user_group_id . ' AND 
//							t.product_category_id =' . $eachProductCategory->id . ') OR
//							
//							(t.isActive="Y" AND  
//							productMapping.product_group_id=' . $id . ' AND 
//							productMapping.user_group_id=' . $user_group_id . ' AND 
//							productMapping.category_id =' . $eachProductCategory->id . ')
//							';
//            $p = Product::model()->with('productMapping')
//                    ->together(true)
//                    ->find(array(
//                'select' => '*, rand() as rand',
//                'order' => 'rand',
//                'condition' => $condition));
//            if ($p != null) {
//                $category[$j]['id'] = $eachProductCategory->id;
//                $category[$j]['name'] = $eachProductCategory->category_name;
//                $category[$j]['image'] = $p->product_image;
//                $category[$j]['link'] = Yii::app()->createUrl('site/products', array('user_group_id' => $user_group_id, 'id' => $id, 'product_category_id' => $eachProductCategory->id, 'name' =>
//                    preg_replace('/[^a-z0-9_]/', '', strtolower(str_replace(" ", "_", $eachProductCategory->category_name)))));
//                $j++;
//            }
//        }
//
//        if (count($category) == 0) {
//            //$this->redirect(array('products','id'=>$id,'user_group_id'=>$user_group_id));
//            $condition = 't.isActive="Y"  
//                                     
//                                    AND  ( t.user_group_id=' . $user_group_id . ' 
//                                        AND t.product_group_id=' . $id . ' 
//                                            ) 
//                                                OR (productMapping.user_group_id=' . $user_group_id . ' 
//                                                    AND productMapping.product_group_id=' . $id . ')';
//        } else {
//            $condition = 't.isActive="Y"  
//                                    AND productCategory.show_in_partner="Y" 
//                                    AND  ( t.user_group_id=' . $user_group_id . ' 
//                                        AND t.product_group_id=' . $id . ' 
//                                            AND t.product_category_id=' . $category[0]['id'] . ') 
//                                                OR (productMapping.user_group_id=' . $user_group_id . ' 
//                                                    AND productMapping.product_group_id=' . $id . '
//                                                         AND productMapping.category_id=' . $category[0]['id'] . ')';
//        }
//        $allProductsUnderUserGroup = Product::model()
//                ->with('productCategory', 'productMapping')
//                ->together(true)
//                ->findAll(
//                array('condition' => $condition
//                )
//        );
//        $this->render('productcategory', array(
//            'user_group_id' => $user_group_id,
//            'category' => $category,
//            'allProductsUnderUserGroup' => $allProductsUnderUserGroup,
//            'ProductGroup' => $ProductGroup,
//            'UserGroupName' => $UserGroupName
//        ));
//    }

        public function actionProductgroup($id) { //product category listing too
        $this->pageTitle .= " - Product categories";
        $mod_sub_cat=new SubCategory();
        $ProductGroup = $mod_sub_cat->findByPk($id);
        $category = array();
        $condition = 'isActive="Y" AND sub_category_id=' . $id;

        $mod_pdt = new Product();
        $category = $mod_pdt->findAll(array('condition' => $condition));
       $categories= array();
//        $j = 0;
//        $categories = ProductCategory::model()->findAll(array('condition' => $condition));
//        foreach ($categories as $eachProductCategory) {
//            $condition = '(t.isActive="Y" AND  
//							t.sub_category_id=' . $id . ' AND 
//							t.user_group_id=' . $user_group_id . ' AND 
//							t.product_category_id =' . $eachProductCategory->id . ') OR
//							
//							(t.isActive="Y" AND  
//							productMapping.product_group_id=' . $id . ' AND 
//							productMapping.user_group_id=' . $user_group_id . ' AND 
//							productMapping.category_id =' . $eachProductCategory->id . ')
//							';
//            $p = Product::model()->with('productMapping')
//                    ->together(true)
//                    ->find(array(
//                'select' => '*, rand() as rand',
//                'order' => 'rand',
//                'condition' => $condition));
//            if ($p != null) {
//                $category[$j]['id'] = $eachProductCategory->id;
//                $category[$j]['name'] = $eachProductCategory->category_name;
//                $category[$j]['image'] = $p->product_image;
//                $category[$j]['link'] = Yii::app()->createUrl('site/products', array('user_group_id' => $user_group_id, 'id' => $id, 'product_category_id' => $eachProductCategory->id, 'name' =>
//                    preg_replace('/[^a-z0-9_]/', '', strtolower(str_replace(" ", "_", $eachProductCategory->category_name)))));
//                $j++;
//            }
//        }
//
//   
        $mod_pdt = new Product();
        $allProductsUnderUserGroup = $mod_pdt->findAll( array('condition' => $condition));
   
        $this->render('productcategory', array(
            'category' => $category,
            'ProductGroup' => $ProductGroup,
            'allProductsUnderUserGroup' => $allProductsUnderUserGroup,
            'categories'=>$categories,
            'id'=>$id
        ));
    }

    /* Products Page */

    public function actionProducts($id = null, $product_category_id = null, $product_type_id = null, $name = null, $type = 'New') {
        $this->pageTitle .= " - Products";
        $condition = '( t.isActive="Y" ';
    
        if ($id != null)
            $condition .= ' AND (t.product_group_id=' . $id . ' OR productMapping.product_group_id=' . $id . ')';
        if ($product_category_id != null)
            $condition .= ' AND (t.product_category_id=' . $product_category_id . ' OR productMapping.category_id=' . $product_category_id . ')';
        if ($product_type_id != null)
            $condition .= ' AND (t.type_id=' . $product_type_id . ' OR productMapping.type_id=' . $product_type_id . ')';
        $condition .= " ) ";



        $mod_pdt = new Product();
        $model = $mod_pdt
                ->with(array('productMapping', 'userGroup', 'productGroup', 'productCategory', 'productType'))
                ->findAll(array('condition' => $condition, 'order' => 't.id'));

        $this->render('products', array(
            'model' => $model
        ));
    }

    /* Promotioanal Products Page */

    public function actionPromotions() {
        $this->pageTitle .= " - Promotional products";
        $condition = '( t.isActive="Y"  AND t.promotionFrom <="' . date('Y-m-d') . '" and 
						t.promotionTo >="' . date('Y-m-d') . '" )  ';
        $mod_pdt = new Product();
        $model = $mod_pdt->with('productMapping')->findAll(array('condition' => $condition, 'order' => 't.id'));

        $this->render('promotions', array(
            'model' => $model,
        ));
    }

    /* Promotioanal Products Page */

    public function actionFeatured() {
        $this->pageTitle .= " - Featured products";
        $condition = 't.isActive="Y"  AND t.isFeaturedItem ="Y"';
        $mod_pdt = new Product();
        $model = $mod_pdt->with('productMapping')->findAll(array('condition' => $condition, 'order' => 't.id'));

        $this->render('featured', array(
            'model' => $model,
        ));
    }

    public function actionProductdetails($id) {
        $mod_pdt = new Product();
        $model = $mod_pdt->findByPk($id);

        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        } else {
            $this->pageTitle .= " - " . $model->product_generic_name;
            $modelProductImages=new ProductImages();
            $modelProductImages = $modelProductImages->findAll(array('condition' => 'product_id=' . $model->id));
            $modelProductFeatureRelation = new ProductFeatureRelation();
            $modelProductFeatureRelation = $modelProductFeatureRelation->with('feature')->findAll(array('condition' => 'product_id=' . $model->id . ' AND feature_value<>""'));
            $modelProductDownloadableRelation= new ProductDownloadableRelation();
            $modelProductDownloadableRelation = $modelProductDownloadableRelation->with('downloadable')->findAll(array('condition' => 'product_id=' . $model->id));
            $modelProductDownloadable = new ProductDownloadable();
            $modelProductDownloadable = $modelProductDownloadable->findAll(array('condition' => 'isActive="Y"'));
            $downloadbles = array();
            foreach ($modelProductDownloadableRelation as $eachProductsd) {
                foreach ($modelProductDownloadable as $i => $eachDownloadable) {
                    if ($eachProductsd->item_id == $eachDownloadable->id) {
                        $downloadbles[$eachDownloadable->id]['item_value'][] = $eachProductsd->item_value;
                        $downloadbles[$eachDownloadable->id]['files_available'][] = $eachProductsd->files_available;
                        $downloadbles[$eachDownloadable->id]['downloadbal_title'] = $eachDownloadable->item_name;
                    }
                }
            }
            $this->render('productdetails', array(
                'model' => $model,
                'modelProductImages' => $modelProductImages,
                'modelProductFeatureRelation' => $modelProductFeatureRelation,
                'modelProductDownloadableRelation' => $modelProductDownloadableRelation,
                'downloadbles' => $downloadbles
            ));
        }
    }

    public function actionResources($id) {
        $model = new Resource;
        $resourceTypeName = new ResourceType();
        $resourceTypeName = $resourceTypeName->findByPk($id)->resource_type;
        $this->pageTitle .= " - " . $resourceTypeName;
        $resource = $model->findAll(array('condition' => 'isActive="Y" AND resource_type_id=' . $id, 'limit' => 5));
        $productResource = new ProductResource();
        $productResource = $productResource->findAll(array('condition' => 'isActive="Y" AND resource_type_id=' . $id, 'limit' => 5));
        //$random	=	$mod_pdt->findAll(array('condition'=>' isActive="Y"','select'=>'*, rand() as rand','limit'=>2,'order'=>'rand'));

        if (isset($_POST['Resource'])) {
            $condition = 'isActive="Y" AND resource_type_id=' . $id;
            if ($_POST['Resource']['user_group_id'] != '')
                $condition .= ' AND user_group_id=' . $_POST['Resource']['user_group_id'];
            if ($_POST['Resource']['product_group_id'] != '')
                $condition .= ' AND product_group_id=' . $_POST['Resource']['product_group_id'];
            if ($_POST['Resource']['product_category_id'] != '')
                $condition .= ' AND product_category_id=' . $_POST['Resource']['product_category_id'];
            $resource = $model->findAll(array('condition' => $condition));
            $productResource = new ProductResource();
            $productResource = $productResource->findAll(array('condition' => $condition));
        }

        $this->render('resources', array(
            'resourceTypeName' => $resourceTypeName,
            'model' => $model,
            'resource' => $resource,
            'productResource' => $productResource,
                //'random'=>$random,
        ));
    }

    public function actionDownloadableResources($id) {



        $modelProductDownloadable = new ProductDownloadable;
        $title = $modelProductDownloadable->findByPK($id)->item_name;
        $this->pageTitle .= " - " . $title;
        $criteria = new CDbCriteria();
        $criteria->condition = 't.isActive=:isActive AND t.item_id=:id';
        if (isset($_POST['Product_name'])) {
            $criteria->condition .= ' AND product.product_name like "' . $_POST['Product_name'] . '%" OR product.product_generic_name like "' . $_POST['Product_name'] . '%"';
        }
        //$criteria->order = 'date DESC';
        $criteria->params = array(':isActive' => 'Y', ':id' => $id);


        $mod_down_reln= new ProductDownloadableRelation();
        $item_count = $mod_down_reln->with('product', 'downloadable')->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(/* Yii::app()->params['listPerPage'] */10);
        $pages->applyLimit($criteria);  // the trick is here!
        $this->render('downloadables', array(
            'modelProductDownloadables' => $mod_down_reln->with('product', 'downloadable')->findAll($criteria), // must be the same as $item_count
            'title' => $title,
            'item_count' => $item_count,
            'page_size' => /* Yii::app()->params['listPerPage'] */10,
            'items_count' => $item_count,
            'pages' => $pages,
        ));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        
        $this->pageTitle .= " - Contact us";
        $model = new ContactForm; 
        $mod_contact= new Contact();
        $pageContents = $mod_contact->find();
        $captcha = "";
        if (isset($_POST['ContactForm'])) {  
            
             if(isset($_POST['g-recaptcha-response']))
       {
         $captcha = $_POST['g-recaptcha-response'];
       }
        
       if(!$captcha){
              $jsonData['status'] = 'nocaptcha';
              echo CJSON::encode($jsonData);
              Yii::app()->end();
        }
        else
        {
            $google_secret_key = "6Lfg2yQTAAAAAE_vZSob16lhM-McyXeEJYArMnla";
            $response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$google_secret_key."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
            if($response['success'] == false)
            {
              $jsonData['status'] = 'spammer';
              echo CJSON::encode($jsonData);
              Yii::app()->end();
            }
            else
            {
                $model->attributes = $_POST['ContactForm'];
                if ($model->validate())
                {
                $mailContent = array();
                $mailContent['name'] = $model->name;
                $mailContent['phone'] = $model->phone;
                $mailContent['email'] = $model->email;
                $mailContent['country'] = $model->country;
                $mailContent['query'] = $model->body;


                $message = new YiiMailMessage;
                $message->view = 'contactmailtemplate';

                $message->setBody(array('mailContent' => $mailContent), 'text/html');
                $message->subject = 'Contact request from Dlink Partner site';
                $message->from ='noreply@me.dlink.com';    
                //$message->from = $model->email;
               // $message->addTo('akhil@mailbluesky.com');
                
                if (trim($pageContents->to_email) != '')
                    $message->addTo($pageContents->to_email);
                else
                    $message->addTo(Yii::app()->params['adminEmail']);
                    
                if (trim($pageContents->bcc_email) != '') {
                    $emails = explode(',', $pageContents->bcc_email);
                    if (is_array($emails)) {
                        foreach ($emails as $eachEmail) {
                            $message->addBcc($eachEmail);
                        }
                    }
                    else
                        $message->addBcc($pageContents->bcc_email);
                }
                $swiftAttachment = Swift_Attachment::fromPath('images/dmailsignature.jpg'); // create a Swift Attachment
                $message->attach($swiftAttachment);
                Yii::app()->mail->send($message);

                //////////////////////////////////////////

                /* $name='=?UTF-8?B?'.base64_encode($model->name).'?=';
                  $subject='=?UTF-8?B?'.base64_encode("Dlinkmea.com/partner : contact from ".$model->country).'?=';
                  $headers="From: $name <{$model->email}>\r\n".
                  "Reply-To: {$model->email}\r\n".
                  "MIME-Version: 1.0\r\n".
                  "Content-type: text/plain; charset=UTF-8";

                  mail($pageContents->to_email,$subject,$model->body,$headers); */
                
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
                }
                }
            }
    }
        
        $this->render('contactus', array('model' => $model, 'pageContents' => $pageContents));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {

        $this->pageTitle .= " - Login";
        $model = new User('login');
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        if(!empty($_POST) && isset($_POST['User'])){

        // collect user input data
            $model->attributes = $_POST['User'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()) {

                $model = User::model()->findByPk(Yii::app()->user->id);
                //echo $model->id;exit;
                $model->last_login = date('Y-m-d H:i:s');
                $model->save();
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }
        // display the login form
        if (Yii::app()->user->isGuest)
            $this->render('login', array(
                'model' => $model));
        else
            $this->redirect(array('index'));
    }

    public function actionForgotpassword() {
        $this->pageTitle .= " - Forgot password";
        $model = new User('login');
        $events = new Events();
        $events = $events->getAllEvents();
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        if(!empty($_POST)  && isset($_POST['User'])){
            $model->attributes = $_POST['User'];
            $user = new User();
            $user = $user->find('LOWER(company_email_address)=? AND isActive=?  AND isConfirmed=?', array($model->company_email_address, 'Y', 'Y'));

            if ($user != null) {
                $session = new CHttpSession;
                $session->open();
                $user->authCode = $session->getSessionID() . time();
                $user->isRequestedNewPassword = 'Y';
                if ($user->save(false)) {
                    $mailContent = array();
                    $mailContent['fullname'] = $model->fullname;
                    $mailContent['confirmLink'] = Yii::app()->createAbsoluteUrl('site/resetPassword', array('token' => $user->authCode));

                    $message = new YiiMailMessage;
                    $message->view = 'resetPassword';

                    $message->setBody(array('mailContent' => $mailContent), 'text/html');
                    $message->subject = 'Dlink partner account Password reset request';

                    $message->from = 'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
                    if ($user->personal_email != '')
                        $message->addTo($user->personal_email);
                    $message->addTo($model->company_email_address);
                    $swiftAttachment = Swift_Attachment::fromPath('images/dmailsignature.jpg'); // create a Swift Attachment
                    $message->attach($swiftAttachment);
                    Yii::app()->mail->send($message);
                    Yii::app()->user->setFlash('success', "Mail reset link has been sent to you. Please check your mail");
                    $this->redirect('login');
                }
            }
            else {
                $model->addError('company_email_address', 'No such user found,or contact admin');
            }
        }
        $this->render('forgot_password_form', array(
            'events' => $events,
            'model' => $model));
    }

    public function actionResetPassword($token) {
        $this->pageTitle .= " - Reset password";
        if ($token != null) {
            $model = new User;
            $model = $model->findByAttributes(array('authCode' => $token));
            if ($model === null) {
                Yii::app()->user->setFlash('error', "Invalid key");
                die("Invalid key");
            } else {
                $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
                if(count($_POST) > 0 && isset($_POST['User'])){
                    $model->scenario = 'change_password';
                    $model->password = $_POST['User']['password'];
                    $model->repeat_password = $_POST['User']['repeat_password'];
                    if ($model->validate()) {
                        $model->authCode = '';
                        $model->isRequestedNewPassword = 'N';
                        $model->save();
                        Yii::app()->user->setFlash('success', 'Successfully updated your password');
                        $this->redirect(array('login'));
                    }
                }
                $events = new Events();
                $events = $events->getAllEvents();
                $this->render('resetpassword_form', array(
                    'events' => $events,
                    'model' => $model));
            }
        }
        else
            die('404!');
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionReadmore($id) {
        //die($id);
        $model = new PartnerFrontPage();
        $model = $model->findByPK($id);
        $this->pageTitle .= " - " . $model->title;
        $this->render('pages/front_page_content', array('model' => $model));
    }

    public function actionDownload_center($user_group_id = null, $search_param = null) {
        $this->pageTitle .= " - Download center";
        $criteria = new CDbCriteria();
        $criteria->condition = 'isActive="Y" AND type ="dwc" ';
        if ($user_group_id != null || $user_group_id != '')
            $criteria->condition .=' AND user_group_id=' . $user_group_id;
        if ($search_param != null || $search_param != '')
            $criteria->condition .=' AND file_title LIKE "' . $search_param . '%"';
        $model = new DownloadCentre();
        $item_count = $model->count($criteria);
        $pages = new CPagination($item_count);
        $pages->setPageSize(/* Yii::app()->params['listPerPage'] */10);
        $pages->applyLimit($criteria);  // the trick is here!
        $model = $model->findAll($criteria);
        $this->render('dwnloadcenter', array(
            'model' => $model, // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => /* Yii::app()->params['listPerPage'] */10,
            'items_count' => $item_count,
            'pages' => $pages,
            'title' => "Download center"
        ));
    }

    public function actionTraing_tools() {
        $this->pageTitle .= " - Training tools";
        $model = new TrainingTools();
        $model = $model->findAll(array('condition' => 'isActive="Y"'));
        $this->render('training_tools', array('model' => $model, 'title' => $title));
    }

    public function actionProduct_guides($user_group_id = null, $search_param = null) {
        $this->pageTitle .= " - Product guides";
        $criteria = new CDbCriteria();
        $criteria->condition = 'isActive="Y" AND type ="pg" ';
        if ($user_group_id != null || $user_group_id != '')
            $criteria->condition .=' AND user_group_id=' . $user_group_id;
        if ($search_param != null || $search_param != '')
            $criteria->condition .=' AND file_title LIKE "' . $search_param . '%"';
        $model = new DownloadCentre();
        $item_count = $model->count($criteria);
        $pages = new CPagination($item_count);
        $pages->setPageSize(/* Yii::app()->params['listPerPage'] */10);
        $pages->applyLimit($criteria);  // the trick is here!
        $model =$model->findAll($criteria);
        $this->render('dwnloadcenter', array(
            'model' => $model, // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => /* Yii::app()->params['listPerPage'] */10,
            'items_count' => $item_count,
            'pages' => $pages,
            'title' => "Product Guides"
        ));
    }

    public function actionDigital_library($user_group_id = null, $search_param = null) {
        $this->pageTitle .= " - Digital library";
        $criteria = new CDbCriteria();
        $criteria->condition = 'isActive="Y" AND type ="dl" ';
        if ($user_group_id != null || $user_group_id != '')
            $criteria->condition .=' AND user_group_id=' . $user_group_id;
        if ($search_param != null || $search_param != '')
            $criteria->condition .=' AND file_title LIKE "' . $search_param . '%"';
        $model = new DownloadCentre();
        $item_count = $model->count($criteria);
        $pages = new CPagination($item_count);
        $pages->setPageSize(/* Yii::app()->params['listPerPage'] */10);
        $pages->applyLimit($criteria);  // the trick is here!
        $model = $model->findAll($criteria);
        $this->render('digitallibrary', array(
            'model' => $model, // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => /* Yii::app()->params['listPerPage'] */10,
            'items_count' => $item_count,
            'pages' => $pages,
            'title' => "Digital Library"
        ));
    }

    public function actionPromotional_items($user_group_id = null, $search_param = null) {
        $this->pageTitle .= " - Promotions";
        $criteria = new CDbCriteria();
        $criteria->condition = 'isActive="Y" AND type ="pr" ';
        if ($user_group_id != null || $user_group_id != '')
            $criteria->condition .=' AND user_group_id=' . $user_group_id;
        if ($search_param != null || $search_param != '')
            $criteria->condition .=' AND file_title LIKE "' . $search_param . '%"';
        $model = new DownloadCentre();
        $item_count = $model->count($criteria);
        $model = $model->findAll($criteria);
        $pages = new CPagination($item_count);
        $pages->setPageSize(/* Yii::app()->params['listPerPage'] */10);
        $pages->applyLimit($criteria);  // the trick is here!
        $this->render('promotional_items', array(
            'model' => $model, // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => /* Yii::app()->params['listPerPage'] */10,
            'items_count' => $item_count,
            'pages' => $pages,
        ));
    }

    public function actionVideo_center($user_group_id = null, $purpose = null, $product_id = null) {
        $this->pageTitle .= " - Video center";
        $criteria = new CDbCriteria();
        $criteria->condition = 'isActive = "Y"';
        if ($user_group_id != null || $user_group_id != '')
            $criteria->condition .=' AND user_group_id=' . $user_group_id;
        if ($purpose != null || $purpose != '')
            $criteria->condition .=' AND purpose = "' . $purpose . '"';
        if ($product_id != null || $product_id != '')
            $criteria->condition .=' AND product_id = "' . $product_id . '"';
        $mod_video=new VideoCenter();
        $item_count = $mod_video->count($criteria);


        $pages = new CPagination($item_count);
        $pages->setPageSize(/* Yii::app()->params['listPerPage'] */6);
        $pages->applyLimit($criteria);  // the trick is here!

        $this->render('videocenter', array(
            'model' => $mod_video->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => /* Yii::app()->params['listPerPage'] */6,
            'items_count' => $item_count,
            'pages' => $pages,
        ));
    }

    /**
     * pressreleases
     */
    public function actionPressreleases() {
        $this->pageTitle .= " - Press Releases";
        $criteria = new CDbCriteria();
        $criteria->condition = 'isActive = :isActive';
        $criteria->order = 'date desc';
        $criteria->params = array(':isActive' => 'Y');
        // if($news_seacrh_term!=null && trim($news_seacrh_term)!='')
        //$criteria->condition .= ' AND ( title_of_news LIKE "%'.$news_seacrh_term.'%" OR content LIKE "%'.$news_seacrh_term.'%")';
        $mod_news= new News();
        $item_count = $mod_news->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(/* Yii::app()->params['listPerPage'] */10);
        $pages->applyLimit($criteria);  // the trick is here!

        $this->render('pressreleases', array(
            'model' => $mod_news->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => /* Yii::app()->params['listPerPage'] */10,
            'items_count' => $item_count,
            'pages' => $pages,
        ));
        //$this->render('pressreleases',array('model'=>$model));		
    }

    public function actionNews_details($id) {
        $this->pageTitle.=' - Press Releases';
        //$this->layout	=	'common_layout';
        $mod_news= new News();
        $model = $mod_news->findByPK($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        else {
            $this->render('pressreleases_details', array('model' => $model));
        }
    }

    /* public function actionTest()
      {

      $mailContent = array();
      $mailContent['name'] = 'test mail';
      $mailContent['phone'] = 'testing';
      $mailContent['email'] = 'arun.kumar@bluesky.ae';
      $mailContent['country'] = 'india';
      $mailContent['query'] = 'Email Testing let me know that this system generated mail reached into your inbox or not';


      $message = new YiiMailMessage;
      $message->view = 'contactmailtemplate';

      $message->setBody(array('mailContent'=>$mailContent), 'text/html');
      $message->subject = 'Email Testing let me know that this system generated mail reached into your inbox or not';
      $swiftAttachment = Swift_Attachment::fromPath('images/dmailsignature.jpg'); // create a Swift Attachment
      $message->attach($swiftAttachment);

      $message->from	=	Yii::app()->params['adminEmail'];
      $message->addTo('ddickens789@gmail.com');
      $message->addTo('dlinkindia12@hotmail.com');
      $message->addTo('dlink000@mail.com');
      $message->addTo('risharose34@live.com');
      Yii::app()->mail->send($message);

      } */

    /* public function actionResend() //send mail to users those yet to confirm tre email address
      {
      $models	=	User::model()->findAll(array('condition'=>'isConfirmed="N"'));
      foreach($models as $i=>$model)
      {
      $mailContent = array();
      $mailContent['fullname'] = $model->fullname;
      $mailContent['confirmLink'] = Yii::app()->createAbsoluteUrl('site/confirmEmail',array('token'=>$model->authCode));

      $message = new YiiMailMessage;
      $message->view = 'emailVerification';

      $message->setBody(array('mailContent'=>$mailContent), 'text/html');
      $message->subject = 'Dlink Email Confirmation ';

      $message->from	=	Yii::app()->params['adminEmail'];
      $message->addTo($model->company_email_address);
      $swiftAttachment = Swift_Attachment::fromPath('images/dmailsignature.jpg'); // create a Swift Attachment
      $message->attach($swiftAttachment);
      Yii::app()->mail->send($message);
      echo $i+1.".Ok done:".$model->company_email_address."<br/>";
      }
      } */
}