<?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>             		  |



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



class User extends AppModel {



    var $name 		= 'User';



    var $hasMany 	= 'UserAddress';



    var $validate  = array('email' => array('rule' => 'email', 'message' => 'Invalid email Id'));



    function validate_unique($tablename,$fieldname,$val,$type='VARCHAR',$id=0) {



        if($id <> 0) {



            if($type <> 'INT') {



                $chk	=	$this->query("SELECT * FROM ".$tablename." WHERE ".$fieldname." = '".$val."' AND id !=".$id);



            }else {



                $chk	=	$this->query("SELECT * FROM ".$tablename." WHERE ".$fieldname." = ".$val." AND id !=".$id);



            }



        }else {



            if($type <> 'INT') {



                $chk	=	$this->query("SELECT * FROM ".$tablename." WHERE ".$fieldname." = '".$val."'");



            }else {



                $chk	=	$this->query("SELECT * FROM ".$tablename." WHERE ".$fieldname." = ".$val);



            }



        }



        if(sizeof($chk) > 0) {



            return false;



        }else {



            return true;



        }



    }



    function save_user($dat) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $ustbl = $Db->fullTableName('users');



        if(!empty($dat["id"])) {







            $sql	=	"UPDATE $ustbl SET uname = '".$dat["uname"]."', email ='".$dat["email"]."' WHERE id=".$dat["id"];



        }else {



            if(!empty($dat["password"]))



                $sql	=	"INSERT INTO $ustbl(uname,password,email,reg_date) VALUES ('".$dat["uname"]."' , '".md5($dat["password"])."', '".$dat["email"]."', '".$dat["reg_date"]."')";



            else



                $sql	=	"INSERT INTO $ustbl(uname,email) VALUES ('".$dat["uname"]."' ,'".$dat["email"]."')";



        }



        $re 		= 	$this->query($sql);



        if(!empty($dat["id"])) {



            $id =	$dat["id"];



        }else {



            $id	=	mysql_insert_id();



        }



        return $id;



    }







    function save_address($dat) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $ustbl = $Db->fullTableName('user_addresses');



        $chk	=	$this->query("SELECT * FROM $ustbl WHERE user_id = ".$dat["user_id"]." AND addr_type ='".$dat["addr_type"]."'");







        //$cnt	=	$this->findCount("UserAddress.user_id = ".$dat["user_id"]." AND UserAddress.addr_type ='".$dat["addr_type"]."'",1);



        if(sizeof($chk) > 0) {



            $sql	=	"DELETE FROM  $ustbl WHERE  user_id = ".$dat["user_id"]." AND addr_type ='".$dat["addr_type"]."'";



            $ex		=	$this->query($sql);



        }



        $sq		=	"INSERT INTO $ustbl(user_id,addr_type,fname,lname,address,city,state,country,zip,phone,fax,mobile)



			VALUES (".$dat["user_id"].",'".$dat["addr_type"]."','".$dat["fname"]."','".$dat["lname"]."','".$dat["address"]."','".$dat["city"]."','".



                $dat["state"]."','".$dat["country"]."','".$dat["zip"]."','".$dat["phone"]."','".$dat["fax"]."','".$dat["mobile"]."')";



        $re 	= 	$this->query($sq);



        return $re;



    }



    function delete_user($id) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $usatbl = $Db->fullTableName('user_addresses');



        $ustbl = $Db->fullTableName('users');



        $this->query("DELETE u.*, a.* FROM $ustbl u LEFT JOIN $usatbl a ON u.id = a.user_id WHERE u.id = ".$id);



        return  true;



    }



    function validateLogin($data) {



        $user = $this->find(array('uname' => $data['username'], 'password' => md5($data['password'])), array('id','uname','email','usertype','reg_status'));



        if(empty($user) == false)



            return $user['User'];



        return false;



    }







    function validateGuestLogin($data) {



        $user = $this->find(array('uname' => $data['uname'], 'password' => $data['password']), array('id','uname','email','usertype','reg_status'));



        if(empty($user) == false)



            return $user['User'];



        return false;



    }



    function getGuestUsername() {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $settingstbl = $Db->fullTableName('settings');



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



        $guestnumber	=	$cnfg["guestnumber"];



        $curr_guestnumber= $guestnumber+1;



        $guest_username="Guest$curr_guestnumber";



        $this->query("UPDATE  $settingstbl SET value='".$curr_guestnumber."' where fieldname='guestnumber'");



        return $guest_username;



    }







    function pwordset($uname,$pword) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $ustbl = $Db->fullTableName('users');



        $this->query("UPDATE  $ustbl SET password='".md5($pword)."' WHERE uname='".$uname."'");



    }



    function chngpword($uid,$pword) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $ustbl = $Db->fullTableName('users');



        $this->query("UPDATE  $ustbl SET password='".md5($pword)."' WHERE id='".$uid."'");



        return true;



    }



    function editemail($uid,$email,$uname) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $ustbl = $Db->fullTableName('users');



        $this->query("UPDATE  $ustbl SET email='".$email."' WHERE id='".$uid."'");



        //Updating the email in Newsletter Users Table

        $newstbl=$Db->fullTableName('newsletterusers');

        $this->query("update ".$newstbl." set email='".trim($email)."' where uname='".trim($uname)."'");



        return true;



    }







    function getTableName($tablename) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $tblnme = $Db->fullTableName($tablename);



        $tblnme=trim(str_replace('`','',$tblnme));



        return $tblnme;



    }



    function changeemailpassword($id, $email) {

        $Db = ConnectionManager::getDataSource($this->useDbConfig);

        $ustbl = $Db->fullTableName('users');

        $arr = $this->query("Select email from $ustbl Where id='".$id."'");

        $oldemail = $arr[0]['localware_demo_users']['email'];



        $nwtbl = $Db->fullTableName('newsletterusers');

        $arr = $this->query("Update $nwtbl set email = '$email' Where email='".$oldemail."'");

        return true;

    }







    //Overriding Pagination starts here...



    function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {

        if(!isset($extra['passit']['sort'])) {

            $extra['passit']['page']= 1;

            $extra['passit']['sort']='User.id';

            $extra['passit']['direction'] ='ASC';

            $order = array($extra['passit']['sort'] => $extra['passit']['direction']);

        }

        else {

            $order = array($extra['passit']['sort'] => $extra['passit']['direction']);

        }

        $group='';
        $joins = '';

        if(isset($extra['group']))$group = $extra['group'];

        if(isset($extra['joins']))$joins = $extra['joins'];

        $params = array(

                'conditions' => $conditions,

                'fields' => $fields,

                'order' => $order,

                'limit' => $limit,

                'joins' => $joins,

                'page' => $page,

                'group' => $group,

        );

        return $this->find('all', $params);

    }



    function paginateCount($conditions = null, $recursive = 0, $extra = array()) {

        $group='';
        $joins = '';

        if(isset($extra['group']))$group = $extra['group'];

        if(isset($extra['joins']))$joins = $extra['joins'];

        $params = array(

                'conditions' => $conditions,

                // 'fields' => array('id','extra_price','combination_id','product_price','SUM(quantity)','PD.stock', 'PD.skuno','P.id', 'P.pname','P.price','P.stock'),

                'fields' => '',

                'joins' => $joins,

                'group' => $group,

        );

        return count($this->find('all', $params));

    }

    //Overriding Pagination starts here...



    function getDates_reg($opt='') {

        $Db = ConnectionManager::getDataSource($this->useDbConfig);

        $usrtbl = $Db->fullTableName('users');

        if($opt=='max') {

            $maxdate	=	$this->query("SELECT DATE_FORMAT(DATE_ADD(max(reg_date),INTERVAL 1 DAY),'%m-%d-%Y') AS maxdate FROM $usrtbl");

            $gdate= $maxdate[0][0]["maxdate"];

        }

        else if($opt=='min') {

            $mindate	=	$this->query("SELECT DATE_FORMAT(DATE_SUB(min(reg_date),INTERVAL 1 DAY),'%m-%d-%Y') AS mindate FROM $usrtbl");

            $gdate= $mindate[0][0]["mindate"];

        }

        return $gdate;

    } // End Function

    function formatUserforAutocomplete($data) {
        $content = NULL;
        $dataUserArr = array();
        $dataShipAddArr = array();
        $dataBillAddArr = array();

        if(!empty($data)) {
            foreach($data as $item) {
                $uItem = $uAdItem = NULL;
                $uItem = $item['User'];
                $uAdItem = $item['UserAddress'];
                $uItemArr = array();

                $uItemArr = array('label' => $uItem['uname'],
                        'value' => $uItem['uname'],
                        'id' => $uItem['id'],
                        'uname' => $uItem['uname'],
                        'email' => $uItem['email'],
                        'usertype' => $uItem['usertype'],
                        's_id' => NULL,
                        's_fname' => NULL,
                        's_lname' => NULL,
                        's_address' => NULL,
                        's_city' => NULL,
                        's_state' => NULL,
                        's_country' => NULL,
                        's_zip' => NULL,
                        's_phone' => NULL,
                        's_fax' => NULL,
                        's_mobile' => NULL,
                        's_email' => NULL,
                        'b_id' => NULL,
                        'b_fname' => NULL,
                        'b_lname' => NULL,
                        'b_address' => NULL,
                        'b_city' => NULL,
                        'b_state' => NULL,
                        'b_country' => NULL,
                        'b_zip' => NULL,
                        'b_phone' => NULL,
                        'b_fax' => NULL,
                        'b_mobile' => NULL,
                        'b_email' => NULL);

                if(!empty($uAdItem)) {
                    foreach($uAdItem as $adItem) {

                        switch($adItem['addr_type']) {
                            case 'Shipping':
                                $dataShipAddArr = array('s_id' => $adItem['id'],
                                        's_fname' => $adItem['fname'],
                                        's_lname' => $adItem['lname'],
                                        's_address' => $adItem['address'],
                                        's_city' => $adItem['city'],
                                        's_state' => $adItem['state'],
                                        's_country' => $adItem['country'],
                                        's_zip' => $adItem['zip'],
                                        's_phone' => $adItem['phone'],
                                        's_fax' => $adItem['fax'],
                                        's_mobile' => $adItem['mobile'],
                                        's_email' => $adItem['email']);
                                $uItemArr = array_merge($uItemArr, $dataShipAddArr);
                                break;
                            case 'Billing':
                                $dataBillAddArr = array('b_id' => $adItem['id'],
                                        'b_fname' => $adItem['fname'],
                                        'b_lname' => $adItem['lname'],
                                        'b_address' => $adItem['address'],
                                        'b_city' => $adItem['city'],
                                        'b_state' => $adItem['state'],
                                        'b_country' => $adItem['country'],
                                        'b_zip' => $adItem['zip'],
                                        'b_phone' => $adItem['phone'],
                                        'b_fax' => $adItem['fax'],
                                        'b_mobile' => $adItem['mobile'],
                                        'b_email' => $adItem['email']);
                                $uItemArr = array_merge($uItemArr, $dataBillAddArr);

                                break;
                        } //End Switch
                    } // End Function
                }
                $dataUserArr[] = $uItemArr;
            } // End Foreach
        } // End If

        return json_encode($dataUserArr);
    } //End Function

    function getUserCredits($userId) {
        $cnfg = Configure::read('Neutrino');
        $userData =  $this->findById($userId);

        $creditsAvailable = $userData['User']['user_credit']; // User Balance Credits
        $creditUnitFractions = $cnfg['user_credit']; // Credit equivalent fractions like 1 unit = $xx [value]
        $creditBalance = 0;
        if(!empty($creditsAvailable) && !empty($creditUnitFractions)) {
            //Calculate Credit Amount
            $creditBalance = $creditsAvailable * $creditUnitFractions;
        }

        return $creditBalance;

    } // End Function

    function updateUserCredits($userId, $amount) {
        $cnfg = Configure::read('Neutrino');
        $Db = ConnectionManager::getDataSource($this->useDbConfig);
        $userTbl = $Db->fullTableName('users');
        $creditUnitFractions = $cnfg['user_credit']; // Credit equivalent fractions like 1 unit = $xx [value]

        $usedCredits = $amount / $creditUnitFractions;
        $usedCredits = round($usedCredits, 2);

        $deductCredits = $this->query("UPDATE $userTbl SET user_credit=(user_credit - ".$usedCredits.") where id='".$userId."'");
    } // End Function



}




?>