<?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 UsersController extends AppController {

    var $name = "User";

    var $helpers = array('Html', 'Form','Pagination','Javascript','Ajax','Csv','xls');

    var $components = array ('Pagination','Catmenu','History','Email','Streamsend'); // Added

    var $uses = array('User','Setting','Country','Cmspage','Category','Newsletter','Newsletteruser','Statecode','Currency','Cart');

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

    function index() {

        $this->__validateLoginStatus();
        $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);

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

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

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

            exit();

        }

        $criteria=NULL;

        $cmbSearchType  =   "";

        $txtSearch      =   "";

        if(isset($_GET["cmbSearchType"]) && isset($_GET["txtSearch"])) {

            $cmbSearchType  =   $_GET["cmbSearchType"];

            $txtSearch      =   $_GET["txtSearch"];

            $data = $this->paginate('User', array('User.'.$cmbSearchType.' LIKE ' => "%".addslashes($txtSearch)."%"));

        }

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

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

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

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

            $data = $this->paginate('User', array('User.'.$cmbSearchType.' LIKE ' => "%".addslashes($txtSearch)."%"));

        }

        else {

            $data = $this->paginate('User');

        }

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

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

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

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

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

        $this->layout = 'adm';

    }

    function beforeFilter() {

        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              =   $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);

        //get cart count
        $sus = $this->Session->read();
        if ($this->Session->check('Userlog') === true) {
            $userid = $sus["Userlog"]["id"];
            $cartCount = $this->Cart->getCartCount($userid,'user');
        }else {
            $sessid = $this->Session->id();
            $cartCount = $this->Cart->getCartCount($sessid,'G');
        }
        $this->set('cartcount',$cartCount);

    }

    function beforeRender() {

        //$lst  =   $this->Catmenu->getCatList(1);

        //$this->set('catmenu', $lst);

        //Code Added By shyam for Category Menu Listing starts here..

       // $lst  =   $this->Category->findAll();
        $lst    =   $this->Category->findAll(null, NULL, 'Category.cname ASC', null, null);
        if(empty($lst)===false) {

            foreach($lst as $det)

                $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"],'parent' => $det["Category"]["parent_id"]);

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

        }

        //Code Added By shyam for Category Menu Listing ends here..
        $footer_links = $this->Cmspage->find('list',array('conditions' => array('Cmspage.type' => 'content','Cmspage.status' => 'Y')));
        $this->set('footerlinks', $footer_links);

    }

    function __validateLoginStatus($typ='A') {

        if($typ == 'A') {

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

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

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

            }

        }else {

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

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

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

            }

        }

    }



    function add() {
        $this->__validateLoginStatus();
        $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");
        }
        
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);
        $admsess    =   $this->Session->read('Admin');
        if($admsess["users"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }
        if (!empty($this->data)) {

            if($this->data["User"]["password"] <> $this->data["User"]["conpassword"]) {
                $this->Session->setFlash(__('Password Mismatch!', true));
                $this->redirect(array('controller'=>'users','action'=>'add'));
            }else {
                $user["password"]       =   md5($this->data["User"]["password"]);
            }
            $user["email"]      =   $this->data["User"]["email"];
            $user["uname"]      =   $this->data["User"]["uname"];
            $user["usertype"]       =   $this->data["User"]["usertype"];
            $user["reg_date"]   =   date('Y-m-d h:i:s');
            $user["reg_status"]     =   'R';
            $usse = $this->User->findByEmail($user["email"]);
            $ussn = $this->User->findByUname($user["uname"]);
            if (!empty($ussn['User']['uname'])) {
                $this->Session->setFlash(__('The Username Already Exist!', true));
                $this->redirect(array('controller'=>'users','action'=>'add'));
                exit;
            }elseif (!empty($usse['User']['uname'])) {
                $this->Session->setFlash(__('The Email Address Already Exist!', true));
                $this->redirect(array('controller'=>'users','action'=>'add'));
                exit;
            }else {
                $this->User->save($user);
                $id =   $this->User->id;

                $this->Newsletteruser->create($newsletteruser = array());
                $newsletteruser["id"]   =   $id;
                $newsletteruser["uname"]    =   $user["uname"];
                $newsletteruser["email"]    =   $user["email"];
                $newsletteruser["sub_date"] =   date('Y-m-d h:i:s');
                $newsletteruser["status"]   =   'N';
                $dups = $this->Newsletteruser->findByEmail(trim($user["email"]));
                if (empty($dups['Newsletteruser']['email'])=== true)
                    $this->Newsletteruser->save($newsletteruser);
                unset($newsletteruser);
            }
            if(!empty($id)) {
                $ship["fname"]      =   $this->data["User"]["sfname"];
                $ship["lname"]      =   $this->data["User"]["slname"];
                $ship["address"]    =   $this->data["User"]["saddress"];
                $ship["country"]    =   $this->data["User"]["scountry"];
                $ship["city"]       =   $this->data["User"]["scity"];

                //$ship["state"]        =   $this->data["User"]["sstate"];
                if($this->data["User"]["scountry"] == 'US') {
                    $ship["state"] = $this->data["User"]["us_sstate"];
                }
                else {
                    $ship["state"]      =   $this->data["User"]["sstate"];
                    unset($this->data["User"]["sstate"]);
                }


                $ship["zip"]        =   $this->data["User"]["szip"];
                $ship["phone"]      =   $this->data["User"]["sphone"];
                $ship["fax"]        =   $this->data["User"]["sfax"];
                $ship["mobile"]     =   $this->data["User"]["smobile"];
                $ship["user_id"]    =   $id;
                $ship["addr_type"]  =   "Shipping";
                $this->User->save_address($ship);


                $bill["fname"]      =   $this->data["User"]["bfname"];
                $bill["lname"]      =   $this->data["User"]["blname"];
                $bill["address"]    =   $this->data["User"]["baddress"];
                $bill["country"]    =   $this->data["User"]["bcountry"];
                $bill["city"]       =   $this->data["User"]["bcity"];

                //$bill["state"]        =   $this->data["User"]["bstate"];
                if($this->data["User"]["bcountry"] == 'US') {
                    $bill["state"] = $this->data["User"]["us_bstate"];
                }
                else {
                    $bill["state"]      =   $this->data["User"]["bstate"];
                    unset($this->data["User"]["bstate"]);
                }

                $bill["zip"]        =   $this->data["User"]["bzip"];
                $bill["phone"]      =   $this->data["User"]["bphone"];
                $bill["fax"]        =   $this->data["User"]["bfax"];
                $bill["mobile"]     =   $this->data["User"]["bmobile"];
                $bill["user_id"]    =   $id;
                $bill["addr_type"]  =   "Billing";
                $this->User->save_address($bill);
                $this->Session->setFlash(__('The Record has been Added', true));
                
                    $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');
                    $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"]."/users/login' target='_blank'>Click here to login</a>";
                    $mailcontent                     =  $mcont.$pdt["Cmspage"]["content"];
                    $mailcontent                     = str_replace("[User_Name]", $user['uname'], $mailcontent);
                    $mailcontent                     = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontent);
                    $mailcontent                     = str_replace("[PASSWORD]", $this->data["User"]["password"], $mailcontent);
                    $mailcontent                     = str_replace("[LOGIN_URL]", $logurl, $mailcontent);
                    //$mailsent                        = mail($user['email'],$subject,$mailcontent,$headers);
                   // echo $mailcontent.'<br />'.$user['email'].'<br />'.$subject;exit;
                    
                    /******************************* MAIL TO THE USER ****************************/
                    $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             = 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($user['email'], ""); 
                    $mail->Send();
                    /******************************* MAIL TO THE USER ****************************/ 
                   
                $this->redirect(array('action'=>'index'));
            }

        }
        $this->layout = 'adm';
        $countrylist    =   $this->Country->find('list',array('fields'=>array('Country.country_iso_code_2','Country.country_name')));
        $this->set('countrylist', $countrylist);

        //Setting the US States dtails
        $us_cntrydet = $this->Country->find("Country.country_iso_code_2 ='US'");
        if(isset($us_cntrydet["Country"]["country_id"])) {
            $us_states  =   $this->Statecode->findAll("Statecode.country_id ='".$us_cntrydet["Country"]["country_id"]."'");
            $this->set('us_states', $us_states);
        }
        //Setting the US States dtails
    }

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

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

            if($this->data["User"]["password"] <> $this->data["User"]["conpassword"]) {

                $this->Session->setFlash(__('Password Mismatch!', true));

                $this->redirect(array('controller'=>'users','action'=>'register'));

            }else {

                $user["password"]       =   md5($this->data["User"]["password"]);

            }

            //print_r($user["password"]);exit;

            $user["email"]      =   $this->data["User"]["email"];

            $user["uname"]      =   $this->data["User"]["uname"];

            $user["usertype"]   =   'retail';

            $user["reg_status"] =   'R';

            $user["reg_date"]   =   date('Y-m-d h:i:s');

            //See if a user with that username exists

            $usse = $this->User->findByEmail($user["email"]);

            $ussn = $this->User->findByUname($user["uname"]);

            // Invalidate the field to trigger the HTML Helper's error messages

            if (!empty($ussn['User']['uname'])) {

                $this->Session->setFlash(__('Username Already Exists!', true));

                //$this->redirect(array('controller'=>'users','action'=>'register'));

                //exit;

            }elseif (!empty($usse['User']['uname'])) {

                $this->Session->setFlash(__('Email Address Already Exists!', true));

                //$this->redirect(array('controller'=>'users','action'=>'register'));

                //exit;

            }else {

                if($id = $this->User->save($user)) {

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

                    $this->Session->setFlash(__('Your registration has been completed successfully', true));

                    $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');

                    $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"]."/users/login' target='_blank'>Click here to login</a>";

                    $mailcontent    =   $mcont.$pdt["Cmspage"]["content"];

                    $mailcontent    = str_replace("[User_Name]", $user['uname'], $mailcontent);

                    $mailcontent    = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontent);

                    $mailcontent    = str_replace("[PASSWORD]", $this->data["User"]["password"], $mailcontent);

                    $mailcontent    = str_replace("[LOGIN_URL]", $logurl, $mailcontent);

                    $pdtad          =   $this->Cmspage->findByTitle('Registration intimation mail to admin');

                    $mailcontentad  =   $pdtad["Cmspage"]["content"];

                    $mailcontentad  = str_replace("[User_Name]", $user['uname'], $mailcontentad);

                    $mailcontentad  = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontentad);

                    //$mailsent         = mail($user['email'],$subject,$mailcontent,$headers);

                    //$mailsent1        = mail($cnfg["admin_email"],$subject,$mailcontentad,$headers);

                    /******************************* MAIL TO THE USER ****************************/
                    $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             = 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($user['email'], ""); 
                    $mail->Send();
                    
                    /******************************* MAIL TO THE 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($admin_email, "Administrator"); 
                    $mail->Send();

                    
                    /************************** MAIL TO THE ADMINISTRATOR ************************/

                }


             
                if($this->data["User"]["news_letter"]==1) {

                    $this->Newsletteruser->create($newsletteruser = array());

                    $newsletteruser["id"]   =   $this->User->id;

                    $newsletteruser["uname"]    =   $user["uname"];

                    $newsletteruser["email"]    =   $user["email"];

                    $newsletteruser["sub_date"] =   date('Y-m-d h:i:s');

                    $newsletteruser["status "]  =   'Y';

                    $dups = $this->Newsletteruser->findByEmail(trim($user["email"]));

                     

                    if (empty($dups['Newsletteruser']['email'])=== true) {

                        $this->Newsletteruser->save($newsletteruser);

                        //*****************Add user to Streamsend ************
                        if(isset($cnfg['streamsendLoginID']) && isset($cnfg['streamsendKey']) && isset($cnfg['streamsendListID']) && $cnfg['streamsendEnable'] == 'Y'  ) {
                            $this->Streamsend->loginID    = $cnfg['streamsendLoginID'];
                            $this->Streamsend->key        = $cnfg['streamsendKey'];
                            $this->Streamsend->listID     = $cnfg['streamsendListID'];

                            //add member
                            $person = array("email" => $user["email"],
                                    "fname" => $user["uname"],
                                    "lname" => $user["uname"],
                            );

                            $this->Streamsend->addstreamsendpeople($this->Streamsend->getXMLAddEmail($person));

                            $mid = $this->Streamsend->getpeople($person['email']);
                           
                            $this->Streamsend->addmembership($mid);
                            
                        }
                        //***********************************

                    }

                    unset($newsletteruser);

                }

                else {

                    $this->Newsletteruser->create($newsletteruser = array());

                    $newsletteruser["id"]   =   $this->User->id;

                    $newsletteruser["uname"]    =   $user["uname"];

                    $newsletteruser["email"]    =   $user["email"];

                    $newsletteruser["sub_date"] =   date('Y-m-d h:i:s');

                    $newsletteruser["status"]   =   'N';

                    $dups = $this->Newsletteruser->findByEmail(trim($user["email"]));

                    if (empty($dups['Newsletteruser']['email'])=== true)

                        $this->Newsletteruser->save($newsletteruser);

                    unset($newsletteruser);

                }

               

                $user['username']   =   $user['uname'];

                $user['password']   =   $this->data["User"]["conpassword"];

                unset($user['email'],$user['uname']);
                
                if(($user = $this->User->validateLogin($user)) == true) {

                    $this->Session->write('Userlog', $user);

                    $this->redirect(array('controller' =>'Carts','action'=>'show'));

                }

            }


        }

        $countrylist    =   $this->Country->find('list',array('fields'=>array('Country.country_iso_code_2','Country.country_name')));

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

        $this->layout = 'default';

    }

    function edit($id=0){
        global $currency;
        $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");
        }
        
        $style  = $cnfg["style"];
        $this->set('style', "admin/".$style);
        $curr = $this->Currency->findByCode($currency);

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

        if($id == 0) {

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

            exit();

        }

        $this->__validateLoginStatus();

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

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

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

            exit();

        }

        $this->User->id = $id;

        $ship   =   array();

        $bill   =   array();

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

            $user["email"]      =   $this->data["User"]["email"];

            $user["uname"]      =   $this->data["User"]["uname"];

            $user["user_credit"]        =   $this->data["User"]["user_credit"];

            /*if(trim($this->data["User"]["user_credit"] != "")) {
                if (!eregi("^[0-9]*+$", trim($this->data["User"]["user_credit"])) ) {
                                    $this->Session->setFlash(__('Invalid user credit point<br>.', true));
                                    $this->redirect(array('controller' => 'users','action'=>'edit/'.$id));
                                    exit();

                }
            }*/

            $this->data["User"]["reg_date"] =   date('Y-m-d h:i:s');

            if(isset($this->data["User"]["password"]) && !empty($this->data["User"]["password"])) {

                $new_pswd=$this->data["User"]["password"];

                $pswd_dups = $this->User->find('count', array('conditions' => array('User.id' => $id ,'User.password' =>  md5($this->data["User"]["password"]))));

                if($pswd_dups  > 0) {

                    $this->Session->setFlash(__('Password entered is same as existing password.Please provide a different password.', true));

                    $this->redirect(array('controller' => 'users','action'=>'edit/'.$id));

                    exit();

                }

                else {

                    $this->data["User"]["password"]=md5($this->data["User"]["password"]);

                    if(isset($_POST["notify"]) &&  !empty($_POST["notify"])) {

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

                        $subject        = "New Password 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('Forgot password mail');

                        $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>";

                        $mailcontent    =   $mcont.$pdt["Cmspage"]["content"];

                        $mailcontent    = str_replace("[User_Name]", $user["uname"], $mailcontent);

                        $mailcontent    = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontent);

                        $mailcontent    = str_replace("[PASSWORD]", $new_pswd, $mailcontent);

                        //$mailsent         = mail($user["email"],$subject,$mailcontent,$headers);
                        

                        /*#################################### 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 USER ****************************/
                            $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($user["email"], ""); 
                            $mail->Send();
                            /******************************* MAIL TO THE USER ****************************/ 
                        
                        /*#################################### EMAIL SEGMENT ###############################*/

                    }

                }

            }

            else {

                $usr_pswd = $this->User->findById($id);

                $this->data["User"]["password"]= trim($usr_pswd["User"]["password"]);

            }

            //See if a user with that username exists

            $ussr = $this->User->findByEmail($user["email"]);



            // Invalidate the field to trigger the HTML Helper's error messages

            if (!empty($ussr['User']['uname']) && $ussr['User']['id'] <> $id) {

                $this->Session->setFlash(__('The Email Address Already exists.', true));

            }else {



                if($this->User->save($this->data)) {

                    $ship["fname"]      =   $this->data["User"]["sfname"];

                    $ship["fname"]      =   $this->data["User"]["sfname"];

                    $ship["lname"]      =   $this->data["User"]["slname"];

                    $ship["address"]    =   $this->data["User"]["saddress"];

                    $ship["country"]    =   $this->data["User"]["scountry"];

                    //$ship["state"]        =   $this->data["User"]["sstate"];

                    //echo "<pre>";
                    //print_r($this->data);
                    //echo "</pre>";
                    //exit();


                    if($this->data["User"]["scountry"] == 'US') {
                        $ship["state"] = $this->data["User"]["us_sstate"];
                    }
                    else {
                        $ship["state"]      =   $this->data["User"]["sstate"];
                        unset($this->data["User"]["us_sstate"]);
                    }

                    $ship["city"]       =   $this->data["User"]["scity"];

                    $ship["zip"]        =   $this->data["User"]["szip"];

                    $ship["phone"]      =   $this->data["User"]["sphone"];

                    $ship["fax"]        =   $this->data["User"]["sfax"];

                    $ship["mobile"]     =   $this->data["User"]["smobile"];

                    $ship["user_id"]    =   $id;

                    $ship["addr_type"]  =   "Shipping";

                    $this->User->save_address($ship);

                    $bill["fname"]      =   $this->data["User"]["bfname"];

                    $bill["lname"]      =   $this->data["User"]["blname"];

                    $bill["address"]    =   $this->data["User"]["baddress"];

                    $bill["country"]    =   $this->data["User"]["bcountry"];

                    //$bill["state"]        =   $this->data["User"]["bstate"];
                    if($this->data["User"]["bcountry"] == 'US') {
                        $bill["state"] = $this->data["User"]["us_bstate"];
                    }
                    else {
                        $bill["state"]      =   $this->data["User"]["bstate"];
                        unset($this->data["User"]["us_bstate"]);
                    }

                    $bill["city"]       =   $this->data["User"]["bcity"];

                    $bill["zip"]        =   $this->data["User"]["bzip"];

                    $bill["phone"]      =   $this->data["User"]["bphone"];

                    $bill["fax"]        =   $this->data["User"]["bfax"];

                    $bill["mobile"]     =   $this->data["User"]["bmobile"];

                    $bill["user_id"]    =   $id;

                    $bill["addr_type"]  =   "Billing";

                    $this->User->save_address($bill);

                    $this->Session->setFlash(__('User details has been edited Successfully.', true));

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

                }

            }

        }else {

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

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

            foreach($this->data ["UserAddress"] as $add) {

                if($add["addr_type"]    ==  "Billing") {

                    $bill["fname"]      =   $add["fname"];

                    $bill["lname"]      =   $add["lname"];

                    $bill["address"]    =   $add["address"];

                    $bill["city"]       =   $add["city"];

                    $bill["state"]      =   $add["state"];

                    $bill["country"]    =   $add["country"];

                    $bill["zip"]        =   $add["zip"];

                    $bill["phone"]      =   $add["phone"];

                    $bill["fax"]        =   $add["fax"];

                    $bill["mobile"]     =   $add["mobile"];

                }

                if($add["addr_type"]    ==  "Shipping") {

                    $ship["fname"]      =   $add["fname"];

                    $ship["lname"]      =   $add["lname"];

                    $ship["address"]    =   $add["address"];

                    $ship["city"]       =   $add["city"];

                    $ship["state"]      =   $add["state"];

                    $ship["country"]    =   $add["country"];

                    $ship["zip"]        =   $add["zip"];

                    $ship["phone"]      =   $add["phone"];

                    $ship["fax"]        =   $add["fax"];

                    $ship["mobile"]     =   $add["mobile"];

                }

            }

            $this->set('shipp', $ship);

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

        }

        $countrylist    =   $this->Country->find('list',array('fields'=>array('Country.country_iso_code_2','Country.country_name')));

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

        //Setting the US States dtails
        $us_cntrydet = $this->Country->find("Country.country_iso_code_2 ='US'");
        if(isset($us_cntrydet["Country"]["country_id"])) {
            $us_states  =   $this->Statecode->findAll("Statecode.country_id ='".$us_cntrydet["Country"]["country_id"]."'");
            $this->set('us_states', $us_states);
        }
        //Setting the US States dtails
        $cnfg       = Configure::read('Neutrino');
        $this->set('userCreditAmount',$cnfg['user_credit']);
        $this->layout = 'adm';

    }

    function delete($id) {

        $this->__validateLoginStatus();

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

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

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

            exit();

        }

        $this->User->delete_user($id);

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

        $this->redirect('index');

    }

    function login($ulg='n') {

        $this->data['Users']    =   $_POST;

        if(empty($this->data['Users']) == false) {

            if(($user = $this->User->validateLogin($this->data['Users'])) == true) {

                if($this->Session->check('Coupon') == true) {
                    $this->Session->delete('Coupon');
                }

                $this->Session->write('Userlog', $user);

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

                //$this->History->goBack(4);

                $this->redirect(array('controller' => 'pages', 'action' => 'display'));

                exit();

            }

            else {

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

            }

        }else {

            if($this->Session->check('Userlog') == true) {

                $this->redirect(array('controller' => 'pages', 'action' => 'display'));

                exit();

            }

        }

        $this->set('ulog',$ulg);

        //$this->layout = 'user_log';

    }

    function logout() {

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

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

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

        $this->redirect(array('controller' => 'pages', 'action' => 'display'));

        exit();

    }



    ############# Function to forgot password.....................................

    function forgotpword() {

        $this->Setting->load();

        $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");
        }

        //print_r($cnfg);exit;

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

            $chk    =   $this->User->findAll("uname='".$_POST["username"]."' AND email='".$_POST["email"]."'");

            if(empty($chk)==false) {

                $pword  =   time().$_POST["username"];

                $this->User->pwordset($_POST["username"],$pword);

                /*$this->Email->template = 'email/confirm';

                // You can use customised thmls or the default ones you setup at the start 

                $data["password"]   =   $pword;

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

                $this->Email->to        =   $_POST["email"]; 

                $this->Email->subject   =   'your new password';

                $this->Email->from      =   $cnfg['admin_email']; 

                $this->Email->fromName  =   $cnfg['site_name']; 

                $this->Email->smtpUserName  =   $cnfg['smtpUserName']; 

                $this->Email->smtpPassword  =   $cnfg['smtpPassword']; 

                $this->Email->smtpHostNames =   $cnfg['smtpHostNames']; 

           //     $this->Email->attach($fully_qualified_filename, optionally $new_name_when_attached); 

                // You can attach as many files as you like. 

                $result = $this->Email->send(); */

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

                $subject        = "New Password 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('Forgot password mail');

                $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>";

                $mailcontent    =   $mcont.$pdt["Cmspage"]["content"];

                $mailcontent    = str_replace("[User_Name]", $_POST["username"], $mailcontent);

                $mailcontent    = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontent);

                $mailcontent    = str_replace("[PASSWORD]", $pword, $mailcontent);

                //echo $mailcontent; exit;

                //$mailsent         = mail($_POST["email"],$subject,$mailcontent,$headers);
                
                $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 USER ****************************/
                $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($_POST["email"], ""); 
                $mailsent = $mail->Send();
                
                /******************************* MAIL TO THE USER ****************************/   
                
                if($mailsent    ==  true) {
                    $this->Session->setFlash(__('Your Password has been reset and sent to your email address.', '/users'));
                }else{
                    $this->Session->setFlash(__('An error occurred in sending the email. Please try again later!', '/users'));                    
                }

                    
               // $this->redirect('/index.php');

               

            }else {

                $this->Session->setFlash(__('You have entered an invalid username or email address!', '/users'));

            }

        }

        //exit;

    }

    ##################### My Account Page###########################

    function myaccount() {


        $this->__validateLoginStatus('U');

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

        if(!empty($sus)===true) {
            $user_id        =   $sus["id"];
        }

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

        $this->set('userid', $user_id);

        $curr_email=$this->User->findById($user_id);



        if(!empty($curr_email['User']['email'])) {
            $newsletter = $this->Newsletteruser->find('first', array('conditions' => array('Newsletteruser.email' => trim($curr_email['User']['email']))));

            $newsletterStatus = 'N';
            $newsletterId = '';

            if(isset($newsletter) && empty($newsletter)===false) {
                $newsletterStatus = $newsletter["Newsletteruser"]["status"];
                $newsletterId = $newsletter["Newsletteruser"]["id"];
            }

            $this->set('status',$newsletterStatus);
            $this->set('newsid',$newsletterId);
        }

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


            If(!empty($_POST['hidnewsid'])) {
                $this->Newsletteruser->id = $_POST['hidnewsid'];
                $this->Newsletteruser->saveField('status',$_POST['hidnews']);
            } else {
                if($_POST['hidnews']=='Y') {
                    $this->Newsletteruser->create($newsletteruser = array());

                    $newsletteruser["id"] = $user_id;

                    $newsletteruser["uname"] = $sus["uname"];

                    $newsletteruser["email"] = $curr_email['User']['email'];

                    $newsletteruser["sub_date"] = date('Y-m-d h:i:s');

                    $newsletteruser["status"] = 'Y';

                    $dups = $this->Newsletteruser->findByEmail($curr_email['User']['email']);

                    if (empty($dups['Newsletteruser']['email']) === true) {
                        $this->Newsletteruser->save($newsletteruser);                       
                        //*****************Add user to Streamsend ************
                        if(isset($cnfg['streamsendLoginID']) && isset($cnfg['streamsendKey']) && isset($cnfg['streamsendListID']) && $cnfg['streamsendEnable'] == 'Y'  ) {
                            $this->Streamsend->loginID    = $cnfg['streamsendLoginID'];
                            $this->Streamsend->key        = $cnfg['streamsendKey'];
                            $this->Streamsend->listID     = $cnfg['streamsendListID'];

                            //add member
                            $person = array("email" => $curr_email['User']['email'],
                                    "fname" => $sus["uname"],
                                    "lname" => $sus["uname"],
                            );

                            $this->Streamsend->addstreamsendpeople($this->Streamsend->getXMLAddEmail($person));

                            $mid = $this->Streamsend->getpeople($person['email']);

                            $this->Streamsend->addmembership($mid);
                            
                        }
                        //***********************************
                    }
                    unset($newsletteruser);
                }
            }

            if($_POST['hidnews']=='Y')

                $msg='You have Successfully Subscribed for Newsletters!';

            else  if($_POST['hidnews']=='N')

                $msg='You have Successfully Unsubscribed for Newsletters!';

            $this->Session->setFlash(__($msg, '/users'));

            $this->redirect(array('controller' => 'users', 'action' => 'myaccount'));

            exit();

        }

    }

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



    function chngpword($uid) {

        $this->__validateLoginStatus('U');

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

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

        $user_id    =   $sus["id"];







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

            $flag       =   true;

            $udet       =   $this->User->findById($user_id);

            $orpword    =   $udet["User"]["password"];

            $msg ='';

            /*

            if($_POST["email"] <> ''){          

                $ussr = $this->User->findByEmail($_POST["email"]);

                // Invalidate the field to trigger the HTML Helper's error messages

                if (!empty($ussr['User']['uname']) && $ussr['User']['id'] <> $user_id)

                {

                    $msg = 'The Email Address Already exists.<br>';

                }else{

                    if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email'])){

                        $msg = " Invalid email <br>";

                    }else{

                        if($this->User->editemail($user_id,$_POST["email"])){                          

                            $msg = " Your email has been updated Successfully! <br>";

                        }

                    }

                }

            }

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

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

                    $msg    .=  '<font color=red>The current password you entered is wrong!</font><br>';

                    $flag   =   false;

                }

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

                    $msg    .=  'The New Passwords are not matching!<br>';

                    $flag   =   false;

                }

                if($flag === true){

                    if($this->User->chngpword($user_id,$_POST["npword"])){

                        $msg    .=  'Your password has been changed successfully!';

                         

                    }

                }

                $this->Session->setFlash(__($msg, '/users'));

                $this->redirect(array('controller' => 'users', 'action' => 'chngpword/'.$user_id)); 

                exit;

            }

            */

            if($_POST["email"] <> '') {

                $flag=true;

                $ussr = $this->User->findById($user_id);
                $usse  = $this->User->find('first', array('conditions' => array('NOT' => array('User.id'     => $user_id), 'User.email' => $_POST["email"])));


                if (!empty($usse['User']['uname'])) {


                    $msg = "Email Address Already Exists! <br>";
                } else {

                    $this->User->editemail($user_id,$_POST["email"],$ussr['User']['uname']);

                    $msg = " Your profile has been updated Successfully! <br>";
                }

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

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

                        $msg    =   '<font color=red>The current password you entered is wrong!</font><br>';

                        $flag   =   false;

                    }

                    if($flag === true) {

                        if($this->User->chngpword($user_id,$_POST["npword"])) {

                            $msg    =   'Your password has been changed successfully!';



                        }

                    }
                }


                $this->Session->setFlash(__($msg, '/users'));

                $this->redirect(array('controller' => 'users', 'action' => 'chngpword/'.$user_id));

                exit;

            }

        }

        $usdet      =   $this->User->findById($user_id);
      
        $this->set('email',$usdet["User"]["email"]);

        $this->set('uname',$usdet["User"]["uname"]);        

    }





    function checkoutlogin() {

        $this->data['Users']    =   $_POST;

        if(empty($this->data['Users']) == false) {

            if(($user = $this->User->validateLogin($this->data['Users'])) == true) {

                $this->Session->write('Userlog', $user);

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

                // $this->redirect(array('controller' => 'userAddresses', 'action' => 'show_bill_ship'));

                $this->redirect(array('controller' => 'carts', 'action' => 'show'));

                exit();

            }

            else {

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

            }

        }else {

            if($this->Session->check('Userlog') == true) {

                $this->redirect(array('controller' => 'userAddresses', 'action' => 'show_bill_ship'));

                exit();

            }

        }



    }

    function guestuser() {

        $guest_username=$this->User->getGuestUsername();

        $guest_password=md5($guest_username);

        $this->Session->write('guestuser', $guest_username);

        $this->Session->write('guestpswd', $guest_password);

        $user['uname']  =   $guest_username;

        $user['password']   =   $guest_password;

        $user["reg_date"]   =   date('Y-m-d h:i:s');

        $user['usertype']   =   'retail';

        $user['reg_status'] =   'G';

        $this->User->save($user);

        if(($user = $this->User->validateGuestLogin($user)) == true) {

            $this->Session->write('Userlog', $user);

            $this->redirect(array('controller' => 'userAddresses', 'action' => 'show_bill_ship'));

            exit();

        }

    }



    function reports() {


$cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);
        $user_min_date=explode(" ",$this->User->getDates_reg("min"));

//        $user_max_date=explode(" ",$this->User->getDates_reg("max"));
        $user_max_date[0]  = date("m-d-Y");
        $this->set('dflt_mindate', $user_min_date[0]); //Setting the max date for the calendar...

        $this->set('dflt_maxdate', $user_max_date[0]); //Setting the max date for the calendar...



        if(isset($_POST["user_fdate"]) &&  isset($_POST["user_tdate"]) && $_POST["user_fdate"]<>'' && $_POST["user_tdate"]<>'') {

            $frmdate=$_POST["user_fdate"];

            $todate=$_POST["user_tdate"];

        }

        else if(isset($this->passedArgs["frmdate"]) && isset($this->passedArgs["todate"]) &&

                $this->passedArgs["frmdate"] <> '' &&  $this->passedArgs["todate"] <> '') {

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

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

        }

        else {

            $frmdate=$user_min_date[0];

            $todate=$user_max_date[0];

        }

        //$cttbl=$this->Report->getTableName("users");

        $sdate=explode('-',$frmdate);

        $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];

        $tdate=explode('-',$todate);

        $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];



        $cttb2=$this->User->getTableName("user_addresses");

        $this->paginate = array(

                'conditions' => array("DATE_FORMAT(User.reg_date,'%Y-%m-%d') >= '".$srch_fdate."' AND  DATE_FORMAT(User.reg_date,'%Y-%m-%d') <= '".$srch_tdate."'"),

                'fields' => array("User.uname,User.email,DATE_FORMAT(User.reg_date,'%m-%d-%Y')as reg_date, uadd.addr_type, uadd.fname, uadd.lname, uadd.address, uadd.city, uadd.state, uadd.country, uadd.zip, uadd.phone, uadd.fax, uadd.mobile"),

                'order' => '',

                'limit' => $this->paginate["limit"],

                'joins' => array(

                        array(

                                'table' => $cttb2,

                                'alias' => 'uadd',

                                'type' => 'LEFT',

                                'conditions'=> array('User.id= uadd.user_id')

                        )

                ),

                'group' => 'User.id',

                'passit' => $this->passedArgs

        );


        $reportdet = $this->paginate('User');
        $this->passedArgs['limit']=$this->paginate["limit"];
        $this->set('passedarg',$this->passedArgs);
        $this->set('reportdet',$reportdet);



        //echo "<pre>";

        //print_r($reportdet);

        //echo "<pre>";

        //exit();





        $this->set('mindate', $frmdate);

        $this->set('maxdate', $todate);



        $this->layout = 'adm';



    }



    function userxls() {

        /*

        $cttbl=$this->Report->getTableName("users");

            $sdate=explode('-',$frmdate);

            $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];

            $tdate=explode('-',$todate);

            $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];

        */



        $cttb2=$this->User->getTableName("user_addresses");



        $qry = array(

                'conditions' => array(""),

                'fields' => array("User.uname,User.email,DATE_FORMAT(User.reg_date,'%m-%d-%Y')as reg_date, uadd.addr_type, uadd.fname, uadd.lname, uadd.address, uadd.city, uadd.state, uadd.country, uadd.zip, uadd.phone, uadd.fax, uadd.mobile"),

                'order' => '',

                'limit' => '',

                'joins' => array(

                        array(

                                'table' => $cttb2,

                                'alias' => 'uadd',

                                'type' => 'LEFT',

                                'conditions'=> array('User.id= uadd.id')

                        )

                ),

                'group' => 'User.id',

                'passit' => ''

        );

        $tot_cnt=count($this->User->find('all', $qry));







        $this->paginate = array(

                'conditions' => array(""),

                'fields' => array("User.uname,User.email,DATE_FORMAT(User.reg_date,'%m-%d-%Y')as reg_date, uadd.addr_type, uadd.fname, uadd.lname, uadd.address, uadd.city, uadd.state, uadd.country, uadd.zip, uadd.phone, uadd.fax, uadd.mobile"),

                'order' => '',

                'limit' => $tot_cnt,

                'joins' => array(

                        array(

                                'table' => $cttb2,

                                'alias' => 'uadd',

                                'type' => 'LEFT',

                                'conditions'=> array('User.id= uadd.user_id')

                        )

                ),

                'group' => 'User.id',

                'passit' => ''

        );







        $data = $this->paginate('User');

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

        $this->layout = 'csvexp';

    }





    function usercsv() {

        //$cttbl=$this->Report->getTableName("users");

        /*

            $sdate=explode('-',$frmdate);

            $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];

            $tdate=explode('-',$todate);

            $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];

                        

            

        */

        $cttb2=$this->User->getTableName("user_addresses");



        $qry = array(

                'conditions' => array(""),

                'fields' => array("User.uname,User.email,DATE_FORMAT(User.reg_date,'%m-%d-%Y')as reg_date, uadd.addr_type, uadd.fname, uadd.lname, uadd.address, uadd.city, uadd.state, uadd.country, uadd.zip, uadd.phone, uadd.fax, uadd.mobile"),

                'order' => '',

                'limit' => '',

                'joins' => array(

                        array(

                                'table' => $cttb2,

                                'alias' => 'uadd',

                                'type' => 'LEFT',

                                'conditions'=> array('User.id= uadd.user_id')

                        )

                ),

                'group' => 'User.id',

                'passit' => ''

        );

        $tot_cnt=count($this->User->find('all', $qry));







        $this->paginate = array(

                'conditions' => array(""),

                'fields' => array("User.uname,User.email,DATE_FORMAT(User.reg_date,'%m-%d-%Y')as reg_date, uadd.addr_type, uadd.fname, uadd.lname, uadd.address, uadd.city, uadd.state, uadd.country, uadd.zip, uadd.phone, uadd.fax, uadd.mobile"),

                'order' => '',

                'limit' => $tot_cnt,

                'joins' => array(

                        array(

                                'table' => $cttb2,

                                'alias' => 'uadd',

                                'type' => 'LEFT',

                                'conditions'=> array('User.id= uadd.user_id')

                        )

                ),

                'group' => 'User.id',

                'passit' => ''

        );



        $data = $this->paginate('User');


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

        $this->layout = 'csvexp';

    }


    function subsnewsletter() {
        $admsess    =   $this->Session->read('Admin');
        
        if (!empty($_POST)) {

            if($_POST['txtEmail'] == '') {
                $this->Session->setFlash(__('Enter your Email Address!', true));
                $this->Session->write('NewsLetter','yes');
                $this->Session->write('NewsStatus','fail');
                $this->redirect(array('controller'=>'pages','action'=>'home'));
            }
            $emailarray                 =       explode('@', $_POST['txtEmail']);
            $user["email"]      =   $_POST['txtEmail'];
            $user["uname"]      =   $emailarray[0];
            $user["sub_date"]           =   date('Y-m-d h:i:s');
            $user["status"]     =   'Y';
            
            $usse = $this->Newsletteruser->findByEmail($user["email"]);
            if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/',$user["email"])){
               $this->Session->setFlash(__('Please Enter Valid Email Address!', true));
                $this->Session->write('NewsLetter','yes');
                $this->Session->write('NewsStatus','fail');
                $this->redirect(array('controller'=>'pages','action'=>'home'));
                exit; 
            }else if (!empty($usse['Newsletteruser']['email'])) {
                $this->Session->setFlash(__('The Email Already Exist!', true));
                $this->Session->write('NewsLetter','yes');
                 $this->Session->write('NewsStatus','fail');
                $this->redirect(array('controller'=>'pages','action'=>'home'));
                exit;
            }else if (!empty($usse['Newsletteruser']['uname'])) {
                $this->Session->setFlash(__('The User Name Already Exist!', true));
                $this->Session->write('NewsLetter','yes');
                 $this->Session->write('NewsStatus','fail');
                $this->redirect(array('controller'=>'pages','action'=>'home'));
                exit;
            }else {
                $this->Newsletteruser->save($user);
                $this->Session->setFlash(__('You have successfully subscribed for Newsletter!', true));
                $this->Session->write('NewsLetter','yes');
                 $this->Session->write('NewsStatus','success');
                $this->redirect(array('controller'=>'pages','action'=>'home'));
                exit;
            }
            
        }
        $this->layout = 'adm';
        
    }

}

?>