<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:             */



// +----------------------------------------------------------------------+



// | PHP version 4/5                                                      |



// +----------------------------------------------------------------------+



// | Copyright (c) 2004-2010 ARMIA INC                                    |



// +----------------------------------------------------------------------+



// | This source file is a part of iScripts VistaCart                     |



// +----------------------------------------------------------------------+



// | Authors: Jipson<jipson.thomas@armiasystems.com>                      |



// +----------------------------------------------------------------------+



App::import('Sanitize');



class AdminsController extends AppController {



    var $name = "Admins";



    var $helpers = array('Html', 'Form','FusionCharts.FusionCharts');

    //   var $components = array('FusionCharts.FusionCharts');
    //   var $helpers = array('FusionCharts.FusionCharts');

    var $components = array ('Salesgraph', 'FusionCharts.FusionCharts'); // Added



    var $uses = array('Order','Admin','Product','User','Setting','Currency','Cmspage');



    var $paginate = array('limit' => 25,'order' => array('Admin.admin_name' => 'asc'));



    function index() {



        $this->__validateLoginStatus();



        $this->layout       =   'adm';




        $pendcnt            =   $this->Order->findCount('Order.order_status_id = 1');



        //print_r($_SESSION);exit;



        //Modified by Vineeth V Alukkal on 23rd April 2010



        //Fetch today's orders



        $ordersToday        =   $this->Order->findCount('DATE(Order.date)=curdate() AND Order.order_status_id = 1');



        //Fetch last months orders



        $ordersLastMonth    =   $this->Order->findCount('month( Order.date)=month( DATE_ADD( curdate(), INTERVAL -1 month))');



        //Fetch last months orders



        $ordersThisMonth    =   $this->Order->findCount('month( Order.date )=month( curdate())');



        //Calculate change in order



        $changeType         ="";



        if ( $ordersLastMonth == 0 ) {



            $order_change = $ordersThisMonth;



        }



        else if ( $ordersThisMonth == 0 ) {



            $order_change = '-'.$ordersLastMonth;



        }



        else {



            $order_change = ( (  $ordersThisMonth - $ordersLastMonth )/ $ordersLastMonth )*100 ;



            $changeType=" %";



        }



        $order_change       =   number_format( $order_change,2,".","").$changeType;







        //Total orders so far



        $totalOrders        =   $this->Order->findCount();







        //Fetch today's Sales



        $salesToday         =   $this->Order->findCount('DATE(Order.date)=curdate() AND Order.order_status_id <> 1');



        //Fetch last months Sales



        $salesLastMonth     =   $this->Order->findCount('month( Order.date)=month( DATE_ADD( curdate(), INTERVAL -1 month)) AND Order.order_status_id <> 1');



        //Fetch this months Sales



        $salesThisMonth     =   $this->Order->findCount('month( Order.date )=month( curdate()) AND Order.order_status_id <> 1');



        //Calculate change in sales



        $changeType         ="";



        if ( $salesLastMonth == 0 ) {



            $sales_change = $salesThisMonth;



        }



        else if ( $salesThisMonth == 0 ) {



            $sales_change = '-'.$salesLastMonth;



        }



        else {



            $sales_change   = ( (  $salesThisMonth - $salesLastMonth )/ $salesLastMonth )*100 ;



            $changeType=" %";



        }







        $sales_change       =   number_format( $sales_change,2,".","").$changeType;



        //Total Sales so far



        $totalSales         =   $this->Order->findCount('Order.order_status_id <> 1');







        //Fetch total users



        $usrnum             =   $this->User->findCount();



        //Fetch total users today



        $usrToday           =   $this->User->findCount('DATE(User.reg_date)=curdate()');



        //Users by this month



        $usrThisMonth       =   $this->User->findCount('month(User.reg_date)=month( curdate())');



        //Users by last month



        $usrLastMonth       =   $this->User->findCount('month( User.reg_date)=month( DATE_ADD( curdate(), INTERVAL -1 month))');







        //Calculate change in USERS



        $changeType         ="";



        if ( $usrLastMonth == 0 ) {



            $users_change = $usrThisMonth;



        }



        else if ( $usrThisMonth == 0 ) {



            $users_change = '-'.$usrLastMonth;



        }else {



            $users_change   = ( ( $usrThisMonth - $usrLastMonth )/ $usrLastMonth )*100 ;



            $changeType=" %";



        }



        $users_change       =   number_format( $users_change,2,".","").$changeType;









//*******************************************Sales graph *************************************

        //plote graph for sales

//Get Orders
        $month_Arr =array();
        $sales_Arr = array();
        $sales_Arr2D =array();
        $graphData      =   $this->Order->fetchgraphgata();
        $month_arr=array(
                "01"=> "Jan" ,
                "02"=> "Feb" ,
                "03"=> "Mar" ,
                "04"=> "Apr" ,
                "05"=> "May" ,
                "06"=> "Jun" ,
                "07"=> "Jul" ,
                "08"=> "Aug" ,
                "09"=> "Sep" ,
                "10"=> "Oct" ,
                "11"=> "Nov" ,
                "12"=> "Dec"
        );

        $sales_graph_arr=array();
        list($m, $y) = explode('-', date('m-Y'));
        for ($i = -12; $i <= 0; $i++) {
            $ts = mktime(0,0,0,$m+$i,1,$y);
            $m1  = date('m', $ts);
            $y1  = date('Y', $ts);
            $sales_graph_arr[$m1."-".$y1] = 0;
        }



        $res_sales_graph= $graphData;
        $totrow_sales_graph=count($graphData);
        if ( $totrow_sales_graph > 0 ) {
            foreach ($res_sales_graph as $key =>$value) {
                $arr_key = $value[0]['MONTH']."-".$value[0]['year'] ;
                $sales_graph_arr[$arr_key] = $value[0]['total_amount'] ;
            }
        }
        $total_bars=count($sales_graph_arr);
        if ( $totrow_sales_graph > 0 ) {
            $max_value=max($sales_graph_arr);

            for($i=0;$i< $total_bars; $i++) {
                // Extract key and value pair from the current pointer position
                $str_key = array();
                list($key,$value)=each($sales_graph_arr);
                $str_key = explode("-",$key);
                $month_name = $month_arr[$str_key[0]];
                $month_Arr[] = $month_arr[$str_key[0]] ;//. " " . $str_key[1];
                $sales_Arr[] = array('value' => $value);
                $sales_Arr2D[] = array('value' => $value, 'params' => array('name' => $month_arr[$str_key[0]]));
            }
        } else {
            $default_text ="No Sales.";

        }

        global $currency;

        $curr = $this->Currency->findByCode($currency);

        $this->set('curlogo', utf8_encode($curr["Currency"]["logo"]));


        /*$this->FusionCharts->create
            (
                'Column3DLineDY Chart',
                array
                (
                    'type' => 'MSColumn3DLineDY',
                    'width' => 466,
                    'height' => 250,
                    'id' => ''
                )
            );



 $this->FusionCharts->setChartParams
            (
                'Column3DLineDY Chart',
                array
                (
                    'caption'               => 'Sales',
                    'PYAxisName'            => 'Revenue',
                    //'SYAxisName'          => 'Quantity',
                    'numberPrefix'          => '$',
                    //'showvalues'          => '0',
                    //'numDivLines'         => '4',
                    //'formatNumberScale'       => '0',
                    //'decimalPrecision'        => '0',
                    //'anchorSides'         => '10',
                    //'anchorRadius'            => '3',
                    //'anchorBorderColor'       => '009900'
                )
            );

 $this->FusionCharts->addCategories
            (
                'Column3DLineDY Chart',
                                $month_Arr

            );

$this->FusionCharts->addDatasets
            (
                'Column3DLineDY Chart',
                array
                (
                    'Sales' => array
                    (
                        'params' => array('color' => 'AFD8F8', 'showValues' => '0'),
                        'data' => $sales_Arr
                    )

                )
            );
        */
        //   $sales_Arr2D =array();
//if(count($sales_Arr2D)){
        $this->FusionCharts->create
                (
                'Column3D Chart',
                array
                (
                'type' => 'Column3D',
                'width' => 500,
                'height' => 250,
                'id' => ''
                )
        );

        $this->FusionCharts->setChartParams
                (
                'Column3D Chart',
                array
                (
                'caption' => 'Sales Graph',
                'xAxisName' => 'Month',
                'yAxisName' => 'Revenue',
                'decimalPrecision' => '0',
                'formatNumberScale' => '0',
                'numberPrefix'          => utf8_encode($curr["Currency"]["logo"])
                )
        );

        $this->FusionCharts->addChartData
                (
                'Column3D Chart',
                $sales_Arr2D
        );
//}

//  $this->Salesgraph->ploteSalesGraph($graphData); // Previous graph
//========Total Sales graph ends

//*********************** Order status ***************

        $ordered    =   $this->Order->findCount('Order.order_status_id = 1');
        $orderShipped   =   $this->Order->findCount('Order.order_status_id = 2');
        $orderAcptByCustomer    =   $this->Order->findCount('Order.order_status_id = 3');
        if($ordered != 0)
            $orderedPer = number_format($ordered / $totalOrders * 100,2,".","");
        else
            $orderedPer = 0;
        if($orderShipped != 0)
            $orderShippedPer = number_format($orderShipped / $totalOrders * 100,2,".","") ;
        else
            $orderShippedPer = 0;
        if($orderAcptByCustomer != 0)
            $orderAcptByCustomerPer = number_format($orderAcptByCustomer / $totalOrders * 100,2,".","") ;
        else
            $orderAcptByCustomerPer = 0;
        $this->set("pendingOrdersPerc",$orderedPer);
        $this->set("shippedOrdersPerc",$orderShippedPer);
        $this->set("deliveredOrdersPerc",$orderAcptByCustomerPer);


//*********************** Order status  ends***************

//*********Get Order details********************
        $pageLimit = 6;
        $cond = 'Order.order_status_id = 1';
        $usrtbl=$this->Order->getTableName("users");
        $statustbl=$this->Order->getTableName("order_statuses");
        $this->paginate = array(
                'conditions' => array($cond),
                'fields' => array("Order.id,Order.date,Order.total_price,Order.user_id,ORS.name,USR.uname"),
                'order' => 'Order.id DESC',
                'limit' => $pageLimit,
                'joins' => array(
                        array(
                                'table' => $usrtbl,
                                'alias' => 'USR',
                                'type' => 'LEFT',
                                'conditions'=> array('Order.user_id = USR.id')
                        ),
                        array(
                                'table' => $statustbl,
                                'alias' => 'ORS',
                                'type' => 'LEFT',
                                'conditions'=> array( 'Order.order_status_id = ORS.id')
                        )
                ),
                'group' => '',
                'passit' => $this->passedArgs
        );
        $data = $this->paginate('Order');



        $this->set('odr', $data);
        $this->set('cnt', 0);
//******************Get Order details ends********************

        global $currency;

        $curr = $this->Currency->findByCode($currency);

        $this->set('curlogo', utf8_encode($curr["Currency"]["logo"]));

//***********************************Ak ends*******************








        $reordercnt         =   $this->Product->reorderalrt();



        $pdtnum             =   $this->Product->findCount();







        //Modified by Vineeth V Alukkal on 23rd April 2010



        $this->set("todays_order",$ordersToday);



        $this->set("lastMonth_order",$ordersLastMonth);



        $this->set("thisMonth_order",$ordersThisMonth);



        $this->set("total_order",$totalOrders);



        $this->set("order_change",$order_change);



        $this->set("pending_order",$pendcnt);







        $this->set("salesToday",$salesToday);



        $this->set("salesLastMonth",$salesLastMonth);



        $this->set("salesThisMonth",$salesThisMonth);



        $this->set("sales_change",$sales_change);



        $this->set("totalSales",$totalSales);







        $this->set("usrToday",$usrToday);



        $this->set("usrThisMonth",$usrThisMonth);



        $this->set("usrLastMonth",$usrLastMonth);



        $this->set("users_change",$users_change);



        $this->set("usrnum",$usrnum);







        $this->set("reorder_alert",$reordercnt);



        $this->set("usernum",$usrnum);



        $this->set("productnum",$pdtnum);







    }



    function add() {
        $cnfg   = Configure::read('Neutrino');
        if(trim($_SERVER['HTTP_HOST']) == 'localhost'){ 
            include_once("../phpmailer/class.phpmailer.php");
        }else{
            include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
        }
        
        $this->__validateLoginStatus();

        $admsess    =   $this->Session->read('Admin');

        if($admsess["adminusers"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        $this->layout = 'adm';
       
        if(!empty($this->data)) {
            //print '<pre />';print_r($this->data);exit;
            //Setting privilages for giftcrads and newsletters
            if($this->data["Admin"]["newsletter"]==1) {
                $this->data["Admin"]["newsletterusers"]=1;
                $this->data["Admin"]["sentnewsletters"]=1;
            }
            else if($this->data["Admin"]["newsletter"]==0) {
                $this->data["Admin"]["newsletterusers"]=0;
                $this->data["Admin"]["sentnewsletters"]=0;
            }
            if($this->data["Admin"]["giftcards"]==1)
                $this->data["Admin"]["giftcardusers"]=1;
            else if($this->data["Admin"]["giftcards"]==0)
                $this->data["Admin"]["giftcardusers"]=0;

            $addet  =   $this->Admin->findByAdminName($this->data["Admin"]["admin_name"]);

            if(empty($addet)) {
                $admin_pass                             = $this->data["Admin"]["admin_pword"];
                $this->data["Admin"]["admin_pword"] =   md5($this->data["Admin"]["admin_pword"]);

                $this->Admin->save($this->data);

                $this->Session->setFlash(__('New admin has been added.', '/admins'));
                
                $cnfg                            = Configure::read('Neutrino');
                $subject                         = "Registration complete at ".$cnfg["site_name"];
                $headers                         = "From: ".$cnfg["site_name"]."<".$cnfg["admin_email"].">\r\n";
                $headers                        .= "MIME-Version: 1.0\r\n";
                $headers                        .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $pdt                             = $this->Cmspage->findByTitle('Registration confirm mail to admin user');
                $path                            = "SiteLogo_disp.gif";
                $mcont                           = "<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>
                                                      <tr><td><a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'><img src='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/app/webroot/".IMAGES_URL.$path."' border='0'></a></td></tr></table>";
                //$cnfg["site_name"]               = "<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'>".$cnfg["site_name"]."</a>";
                $logurl                          = "<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/admins/login' target='_blank'>Click here to login</a>";
                $mailcontent                     = $mcont.$pdt["Cmspage"]["content"];
                $mailcontent                     = str_replace("[User_Name]", $this->data["Admin"]["admin_name"], $mailcontent);
                $mailcontent                     = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontent);
                $mailcontent                     = str_replace("[PASSWORD]", $admin_pass, $mailcontent);
                $mailcontent                     = str_replace("[LOGIN_URL]", $logurl, $mailcontent);
                
                /*#################################### EMAIL SEGMENT ###############################*/                    
                    $site_name      = "";
                    $admin_email    = "";
                    if(trim($cnfg["site_name"]) <> ""){
                        $site_name  = trim($cnfg["site_name"]);                            
                    }else{
                        $site_name = $cnfg['smtp_user'];
                    }  
                    if(trim($cnfg["admin_email"]) <> ""){
                        $admin_email = trim($cnfg["admin_email"]);
                    }else{
                        $admin_email = $cnfg['smtp_user'];
                    }
                
                    /******************************* MAIL TO THE ADMINISTRATOR ****************************/
                    $mail             = new PHPMailer(true);                
                    $body             = trim($mailcontent);
                    //$body           = eregi_replace("[\]",'',$body);
                    $mail->IsSMTP(); 
                    $mail->SMTPSecure = 'tls';
                    //$mail->SMTPDebug  = 2;                    
                    $mail->SMTPAuth   = true;  
                    
                    $mail->Host       = $cnfg['smtp_host'];
                    $mail->Port       = $cnfg['smtp_port'];
                    $mail->Username   = $cnfg['smtp_user'];
                    $mail->Password   = $cnfg['smtp_password'];     
                    $mail->SetFrom($admin_email,$site_name);
                    //$mail->AddReplyTo($admin_email,$site_name);
                    $mail->Subject    = $subject;
                    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                    $mail->MsgHTML($body);                    
                    $mail->AddAddress($this->data["Admin"]["email"], "Administrator - ".trim($site_name)); 
                    $mail->Send();
                    /******************************* MAIL TO THE ADMINISTRATOR ****************************/  
                /*#################################### EMAIL SEGMENT ###############################*/
                    
                //$mailsent                        = mail($this->data["Admin"]["email"],$subject,$mailcontent,$headers);
                //   echo $mailcontent.'<br />'.$user['email'].'<br />'.$subject;exit;
                $this->redirect('lists');

            }else {

                $this->Session->setFlash(__('Username already exists.', '/admins'));

            }

        }

    }



    function edit($id=0) {

        $this->__validateLoginStatus();

        $admsess    =   $this->Session->read('Admin');

        if($admsess["adminusers"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        if($id == 0) {

            $this->redirect(array('controller' => 'admins','action'=>'lists'));

            exit();

        }

        $this->Admin->id = $id;

        if(!empty($this->data)) {


            //Setting privilages for giftcrads and newsletters
            if($this->data["Admin"]["newsletter"]==1) {
                $this->data["Admin"]["newsletterusers"]=1;
                $this->data["Admin"]["sentnewsletters"]=1;
            }
            else if($this->data["Admin"]["newsletter"]==0) {
                $this->data["Admin"]["newsletterusers"]=0;
                $this->data["Admin"]["sentnewsletters"]=0;
            }
            if($this->data["Admin"]["giftcards"]==1)
                $this->data["Admin"]["giftcardusers"]=1;
            else if($this->data["Admin"]["giftcards"]==0)
                $this->data["Admin"]["giftcardusers"]=0;

            $this->Admin->save($this->data);

            $this->Session->setFlash(__('Admin has been edited Successfully.', '/admins'));

            $this->redirect('lists');

        }



        $this->data = $this->Admin->read();

        $this->set('admin', $this->data);

        $this->layout = 'adm';

        //print_r($data);exit;

    }



    function lists() {



        $this->__validateLoginStatus();



        $admsess    =   $this->Session->read('Admin');



        if($admsess["adminusers"] <> 1) {



            $this->redirect(array('controller' => 'admins', 'action' => 'index'));



            exit();



        }



        $adm_id     =   $admsess["id"];



        $cmbSearchType  =   "";



        $txtSearch      =   "";


        //print '<pre />';print_r($_REQUEST);exit;
        if(isset($_GET["cmbSearchType"]) && isset($_GET["txtSearch"])) {

            $cmbSearchType  =   $_GET["cmbSearchType"];

            $txtSearch      =   $_GET["txtSearch"];

            if($cmbSearchType == "uname") {

                $data = $this->paginate('Admin', array('Admin.admin_name  LIKE ' => "%".addslashes($txtSearch)."%",'Admin.id <>'=>1));

            }

            else if($cmbSearchType == "email") {

                $data = $this->paginate('Admin', array('Admin.email  LIKE ' => "%".addslashes($txtSearch)."%",'Admin.id <>'=>1));

            }else {

                $data = $this->paginate('Admin', array('Admin.id <>'=>1));

            }

        }

        else if(isset($this->passedArgs["cmbSearchType"]) && isset($this->passedArgs["txtSearch"]) &&

                $this->passedArgs["txtSearch"] <> '') {

            $cmbSearchType  =   $this->passedArgs["cmbSearchType"];

            $txtSearch      =   $this->passedArgs["txtSearch"];

            if($cmbSearchType == "uname") {

                $data = $this->paginate('Admin', array('Admin.admin_name  LIKE ' => "%".addslashes($txtSearch)."%",'Admin.id <>'=>1));

            }

            else if($cmbSearchType == "email") {

                $data = $this->paginate('Admin', array('Admin.email  LIKE ' => "%".addslashes($txtSearch)."%",'Admin.id <>'=>1));

            }else {

                $data = $this->paginate('Admin', array('Admin.id <>'=>1));

            }

        }else {

            $data = $this->paginate('Admin', array('Admin.id <>'=>1));

        }







        $this->set('sid', $adm_id);



        $this->set('cmbSearchType', $cmbSearchType);



        $this->set('txtSearch', $txtSearch);

        $this->passedArgs['limit']=$this->paginate["limit"];

        $this->set('passedarg',$this->passedArgs);



        $this->set('admins', $data);



        $this->layout = 'adm';



    }



    function delete($id) {



        $this->__validateLoginStatus();



        $admsess    =   $this->Session->read('Admin');



        if($admsess["adminusers"] <> 1) {



            $this->redirect(array('controller' => 'admins', 'action' => 'index'));



            exit();



        }



        $this->Admin->del($id,true);



        $this->Session->setFlash(__('User has been Removed Successfully.', '/admins'));



        $this->redirect(array('controller'=>'Admins','action'=>'index'));



        exit;



    }



    function beforeFilter() {







        if (isset($this->Setting) && !empty($this->Setting->table)) {



            $this->Setting->load();



        }



        if (isset($this->Setting) && !empty($this->Setting->table)) {



            $this->Setting->load();



        }



        global $sitefolder;



        global $meta_description;



        global $meta_keywords;



        global $page_title;

        global $currency;


        $cnfg               =   Configure::read('Neutrino');



        $sitefolder         =   $cnfg["sitebasefolder"];



        $meta_description   =   $cnfg["meta_description"];



        $meta_keywords      =   $cnfg["meta_keywords"];



        $page_title         =   $cnfg["page_title"];

        $currency = $cnfg["currency"];

        global $style;



        $style              =   "admin/".$cnfg["style"];



        $this->set('style', $style);



        $this->set('meta_description', $meta_description);



        $this->set('meta_keywords', $meta_keywords);



        $this->pageTitle = $page_title  ;



        $this->set('cnfg',$cnfg);



        $this->paginate["limit"]=$cnfg["items_perpage"]; //Setting pagination limit per page.



        $this->set('sitefolder', $sitefolder);

        $httpHost   =   $_SERVER['HTTP_HOST'];

        $this->set('sitebase','http://'.$httpHost);

    }



    function beforeRender() {



        if (isset($this->Setting) && !empty($this->Setting->table)) {



            $this->Setting->load();



        }



        global $sitefolder;



        global $meta_description;



        global $meta_keywords;



        global $page_title;



        $cnfg               =   Configure::read('Neutrino');



        $sitefolder         =   $cnfg["sitebasefolder"];



        $meta_description   =   $cnfg["meta_description"];



        $meta_keywords      =   $cnfg["meta_keywords"];



        $page_title         =   $cnfg["page_title"];



        global $style;



        $style              =   "admin/".$cnfg["style"];



        $this->set('style', $style);



        $this->set('meta_description', $meta_description);



        $this->set('meta_keywords', $meta_keywords);



        $this->pageTitle = $page_title;



        $this->set('cnfg',$cnfg);



        $this->set('sitefolder', $sitefolder);

        $httpHost   =   $_SERVER['HTTP_HOST'];

        $this->set('sitebase','http://'.$httpHost);



    }



    function login($alog='n', $key = NULL) {

        if(!empty($key)){
            
                App::import('Xml');
        // your XML file's location
        $file = "configxml.xml";
        // now parse it
        $parsed_xml = new XML($file);
        $parsed_xml = Set::reverse($parsed_xml); // this is what i call magic
        $secKey = $parsed_xml["Configuration"] ["secretkey"];
                if($key == $secKey) {
                    if(($admin = $this->Admin->validateLogin(NULL, 'pass')) == true) {
                        $this->Session->write('Admin', $admin);
                        $this->redirect('index');
                        exit();
                    }
                }
        }

        if(empty($this->data) == false) {
            
            if(($admin = $this->Admin->validateLogin($this->data['Admins'])) == true) {







                $this->Session->write('Admin', $admin);



                // $this->Session->setFlash('You\'ve successfully logged in.');



                $this->redirect('index');



                exit();



            }



            else {



                $this->Session->setFlash('Sorry, Invalid Username / Password.');



                //exit();



            }







        }



        $this->set('alog', $alog);



        $this->layout = 'adm_log';



    }



    function logout() {



        $this->__validateLoginStatus();



        $this->Session->destroy('admin');



        $this->Session->setFlash('You\'ve successfully logged out.');



        $this->redirect('login');



    }



    function __validateLoginStatus() {



        if($this->action != 'login' && $this->action != 'logout') {



            if($this->Session->check('Admin') == false) {



                $this->redirect('login');



                $this->Session->setFlash('The URL you\'ve followed requires you login.');



            }



        }



    }



    ##################### Function to change password##################







    function chngpword() {



        $this->__validateLoginStatus();



        $sus        =   $this->Session->read('Admin');



        //$adm_id       =   $sus["aid"];



        $adm_id     =   $sus["id"];



        if($_SERVER['REQUEST_METHOD']=="POST") {



            $flag       =   true;



            $adet       =   $this->Admin->findById($adm_id);



            $orpword    =   $adet["Admin"]["admin_pword"];



            if(md5($_POST["cpword"]) <> $orpword) {



                $this->Session->setFlash('The current password you entered is wrong!');



                $flag   =   false;



            }



            if($_POST["npword"] <>$_POST["rpword"]) {



                $this->Session->setFlash('The New Passwords are not matching!');



                $flag   =   false;



            }



            if($flag === true) {



                if($this->Admin->chngpword($adm_id,$_POST["npword"])) {



                    $this->Session->setFlash(__('Password has been changed successfully!', '/admins'));



                    $this->redirect(array('controller' => 'Admins', 'action' => 'chngpword'));



                    exit;



                }



            }







        }



        $this->layout = 'adm';



    }



    function invalidlicence() {



        if ($_SERVER['REQUEST_METHOD']=="POST") {



            $txtAdminPass  = trim($_POST['txtAdminPass']);



            $txtLicenseKey  = trim($_POST['txtLicenseKey']);



            if ($txtLicenseKey != "" && $txtAdminPass != "") {



                $adm    =   $this->Admin->findByAdminPword(md5($txtAdminPass));







                if(!empty($adm)) {



                    if (strlen($txtLicenseKey) == '30') {



                        $res    =   $this->Setting->update('vLicenceKey',$txtLicenseKey);



                        $this->Session->setFlash(__('Your Licence Key is updated!', '/admins'));



                        $this->redirect(array('controller' => 'Admins', 'action' => 'login'));



                        exit;



                    }else {



                        $this->Session->setFlash(__('Invalid key. Please enter a valid key!', '/admins'));



                    }



                }else {



                    $this->Session->setFlash(__('Invalid admin password. Please enter a valid admin password!', '/admins'));



                }



            }else {



                $this->Session->setFlash(__('Please enter new key!', '/admins'));



            }



        }



        $this->layout = 'adm_invalid';



    }

    function fusioncharttest() {

        $this->FusionCharts->create
                (
                'Column3DLineDY Chart',
                array
                (
                'type' => 'MSColumn3DLineDY',
                'width' => 600,
                'height' => 350,
                'id' => ''
                )
        );

        $this->FusionCharts->setChartParams
                (
                'Column3DLineDY Chart',
                array
                (
                'caption'               => 'Sales',
                'PYAxisName'            => 'Revenue',
                'SYAxisName'            => 'Quantity',
                'numberPrefix'          => '$',
                'showvalues'            => '0',
                'numDivLines'           => '4',
                'formatNumberScale'     => '0',
                'decimalPrecision'      => '0',
                'anchorSides'           => '10',
                'anchorRadius'          => '3',
                'anchorBorderColor'     => '009900'
                )
        );

        $this->FusionCharts->addCategories
                (
                'Column3DLineDY Chart',
                array
                (
                'March',
                'April',
                'May',
                'June',
                'July'
                )
        );

        $this->FusionCharts->addDatasets
                (
                'Column3DLineDY Chart',
                array
                (
                'Product A' => array
                (
                        'params' => array('color' => 'AFD8F8', 'showValues' => '0'),
                        'data' => array
                        (
                                array('value' => '25601.34'),
                                array('value' => '20148.82'),
                                array('value' => '17372.76'),
                                array('value' => '35407.15'),
                                array('value' => '38105.68')
                        )
                ),
                'Product B' => array
                (
                        'params' => array('color' => 'F6BD0F', 'showValues' => '0'),
                        'data' => array
                        (
                                array('value' => '57401.85'),
                                array('value' => '41941.19'),
                                array('value' => '45263.37'),
                                array('value' => '117320.16'),
                                array('value' => '114845.27')
                        )
                ),
                'Total Quantity' => array
                (
                        'params' => array('color' => '8BBA00', 'showValues' => '0', 'parentYAxis' => 'S'),
                        'data' => array
                        (
                                array('value' => '45000'),
                                array('value' => '44835'),
                                array('value' => '42835'),
                                array('value' => '77557'),
                                array('value' => '92633')
                        )
                )
                )
        );



        $this->layout = 'adm';
    }

}

?>