<?php
/**
 * @copyright 0arkcode
 * @author 0arkcode@gmail.com
 * @license 0arkcode
 * 
 * [:UPDATE:] 02.05.2016
 * - Dodano metody "ValueUP", "ValueDOWN", "ValueCLEAR"
 */
 
	class user{

        public static $sql_table = 'user';
        
        static $DT_stamp = "+12 HOURS";
        static $DT_format = "Y-m-d H:i:s";
        static $instance , $i;
        
        public $debug = array();
        	
        public $redirect , $status, $id , $mode ,  $login_error_code,  $toactive, $AllData, $login;
        public $geo_continent, $geo_country, $geo_state , $geo_city, $country;

        public $SFA = false;
        
 	 	public static $_hash = array('0' => 'X','1' => 'D','2' => 'C','3' => 'H','4' => 'B','5' => 'F','6' => 'E','7' => 'Y','8' => 'J','9' => 'U');
        public static $_cookie_check = 'j384c74jw4n13r4m80';

        public static $own_listing = true;
        public static $own_listing_parse = true;
        public static $own_options = true;

        public static $edit = array(
            'login' => 'login'
        );

		public function __construct(){
		  
            self::$instance = $this;
            self::$i = $this;
          
			$this -> id = $_SESSION['id'];
            //$this -> checkCookie();
            
			$this -> online = $this -> online();
    
            if( $this->online ){
                $this->setParams();
            } else {
                $this->setOfflineParams();
            }

		}

        public static function create( $params ){
            
            // VIA EMAIL
            if( isset( $params['email'] ) AND valid::email( $params['email'] ) ){
                
                // Istnieje uzytkownik o wybranym adresie email
                $check = db::$i->row("SELECT * FROM `user` WHERE `email`='".( esc( $params['email'] ) )."'");
                if( $check )
                {

                    return l('Taki użytkownik już istnieje');
                    
                }
                
                $sql['email'] = esc( $params['email'] );
                
                
            } else return l('Adres email jest wymagany.');
             
            
            // Hasło
            if( isset( $params['pass'] ) AND strlen( $params['pass'] ) >= 5 ){
                
                if( $params['pass'] == $params['repass'] ){
                    
                    $sql['pass'] = self::pass_encoder( $params['pass'] );
                    
                } else {
                    
                    return l('Hasła muszą być identyczne.');
                    
                }
                
            } else {
                return l('Minimalna długość hasła to 5 znaków.');
            }

            if( $params['umode'] == 'user' AND empty( $params['therapist'] ) )
            {
                return l('Wybierz terapeutę');    
            } 
            else 
            {
                $sql['therapist'] = $params['therapist'];
            }
            
            // Imie
            if( isset( $params['firstname'] ) ) $sql['firstname'] = esc( $params['firstname'] );
            
            // Nazwisko
            if( isset( $params['lastname'] ) ) $sql['lastname'] = esc( $params['lastname'] );
         
            switch( $params['umode'] )
            {
                case 'user':
                case 'therapist':
                case 'admin':
                    $sql['mode'] = $params['umode'];  
                break;
                
                default:
                    $sql['mode'] = 'user'; 
                break;
            }
            
            if( db::$i->insert( self::$sql_table , $sql ) ){
                
                $data = db::$i->row("SELECT * FROM `user` WHERE `id`='".( db::$i->insert_id )."'");
                
                return true;
                
            } else return l('Wystąpił błąd podczas tworzenia konta, spróbuj ponownie za chwilę');
        }
        
        /**
         * Odzyskiwanie hasła
         */
        public function PasswordRecover( $params ){
            
            if( isset( $params['email'] ) ){
                
                if( !valid::email( $params['email'] ) ) return l('Podaj poprawny adres email');
                
                $data = self::getBy(array(
                    'email' => $params['email']
                ));
                
                if( !$data ) return l('Użytkownik o podanym adresie email nie istnieje w naszym systemie');
            }
            
        }

       public static function CreateHash( $input ){
            return strtoupper(md5(rand(100000,999999).rand(100000,999999).microtime(true))) . str_replace( array_flip( self::$_hash ) , self::$_hash , $input );
        }
        
       public static function ReadHash( $input ){
            return str_replace( self::$_hash , array_flip(self::$_hash) , substr($input,32) );
        }
        
        public static function UpdateLog( $with_reff = false , $uid = false ){

        }
        
        public static function VerifyCookie(){

        }
        
        public static function BanIP( $ip , $reason=1 ){
            db::$i->insert('banip',array(
                'ip' => esc($ip),
                'reason' => intval($reason),
                'crt' => crt()
            ));
        }
        
        public static function BlackList(){
            if( db::$i->row("select * from banip where ip='".esc(core::get_ip())."'") ){
                header("Location:https://www.google.com/?q=what+is+banned&gws_rd=cr&ei=KPAUV5jGOYOVsgHYmqHoCw#");
                die();
            }
        }
        
		public static function pass_encoder( $password ){
               return md5( $password );
		}

		public function login( $email = false , $facebook_id = false , $password = false , $back = false , $sfa = false ){
            
			if( $email ) $email = esc( $email );
            
            
			if( 
                ( $email AND $data = db::$i -> row( "SELECT * FROM `user` WHERE `email` = '".( $email )."'" ) )
            ){
				
                $data['status'] = 1;
                
				$this -> id = $data['id'];
                
                // Via email and password
				if( $email ) $password = self::pass_encoder( $password );
		
 
				if( ( !empty( $password ) and $password == $data['pass'] ) OR $facebook_id ){

					$expire = new DateTime( date("Y-m-d H:i:s") );
					$expire -> modify( self::$DT_stamp );
					$expire = $expire -> format( self::$DT_format );  

                    db::$i->q("DELETE FROM `session` WHERE `sid`='".( session_id() )."' OR `uid`='".( $this->id )."'");
                    /*
					if( db::$i -> row("SELECT 1 FROM `session` WHERE `uid`='{$data['id']}' OR `sid`='".( session_id() )."'") ){
						
                        if(db::$i -> update('session',array(
                            'uid' => esc( $data['id'] ),
                            'sid' => session_id(),
                            'datetime' => $expire,
                            'ip' => core::get_ip()
                        ), $this -> id ,'uid')){
                            debug::printr( '1' );
                            $this -> online = true;
                            
                        } else $this -> online = false;
                    
 
					} else {

					}
	               */

                    if( db::$i -> insert('session',
					array(
						'uid' => $this -> id,
						'sid' => session_id(),
						'datetime' => $expire,
						'ip' => core::get_ip()
					)) ) $this -> online = true;
                    else $this -> online = false;
                        
					if( $this -> online ){
				   
                        setcookie( self::$_cookie_check , self::CreateHash($this->id) , time()+(60*60*24*90) , '/' , '.'.$_SERVER['SERVER_NAME'] );
                        
                        
						$_SESSION['id'] = $this -> id;
						$this -> redirect = $redirect;
                        $this -> setParams();
                        
                            return true;
                            
					}
                    
				} elseif( $data['status']!=1 ){
				    
				    if( $data['status'] == 2 ){
				        $this -> login_error_code = 3;
				    } else {
				        $this -> login_error_code = 2;
				    }
                    
                    $this -> online = false;
                    
				} else { 
				    
				    $this -> online = false;
                    $this -> login_error_code = 1;	
                    	
                }
			} else {
			 $this -> login_error_code = 1;
             $this -> online = false;
            }
			
			return false;
		}
		
		public function online(){

			if( $this -> sessionExists() ){
			 
                                 
				$data = db::$i -> row( "select * from `session` where `sid`='".session_id()."'" );
                
				if( 
                    new DateTime( date("Y-m-d H:i:s") ) > new DateTime( $data['datetime'] ) 
                    OR 
                    $data['sid'] != session_id()/* OR $data['ip'] != core::get_ip() */){

                    //$this -> logout();
					$this -> online = false;
                    $this -> id = false;
                    
                    	return false;
				} else {

                    
                    $this -> id = $data['uid'];
                    $_SESSION['id'] = $this->id;
                    $this -> online = true;
					$this -> expireSession();
						
						return true;
				}				
			} else return false;
					
		}
        
        public function Reload()
        {
            self::$i->setParams();
        }
        
        public function setParams(){

            $this->AllData = self::byid( $this->id );
            
			if( !$this->AllData ) return false;
			
			// Primary Data
			$this->login = $this->AllData['login'];
			$this->mode = $this->AllData['mode'];
			
			// Other account details_parse
			$this->firstname = $this->AllData['firstname'];
			$this->lastname = $this->AllData['lastname'];
            
            
            $this->parsed = core::object( self::parse( $this->AllData ) );
            
        }
        
        public static function refresh(){
            self::$i->setParams();
        }
        
        public function setOfflineParams(){

            $this->id = false;

            $this->AllData = array(
                'login' => 'offline',
                'country' => geo::$replacer,
                'mode' => 'public'
            );
            

            $this->login = $this->AllData['login'];

            // Location
            $this->country = $this->AllData['country']; 

            
            // Tryb użytkownika
            $this -> mode = 'guest';
        }
        
        public function update( $params , $uid = false ){
			
            if( db::$i->update('user', $params , ( $uid ? $uid : $this->id ) ) ){
                
                return true;
            }
            else return false;
        }

        /**
         * Logout & Kill sql session :)
         */
		public function logout(){
                    
			$this -> online = false;
			db::$i -> delete('session',session_id(),'sid');
			
		}
		
		public function checkCookie(){
		}
        
		public function sessionExists(){
		  
          $this->debug[] = 'sessionExists-1';
		  return db::$i -> chk( esc(session_id()) , 'session' , 'sid' );
          
		}
		
		public function expireSession(){

			$expire = new DateTime( date("Y-m-d H:i:s") );
			$expire -> modify( self::$DT_stamp );
			$expire = $expire -> format( self::$DT_format );
			db::$i->update( 'session' , array( 'datetime' => $expire ) , session_id() , 'sid');
            
		}

        /**
         * Get user sql field value
         * @param string $name - Name of sql field user.$name
         * @return mixed - STRING, INT OR NULL
         */
		public function getField( $name ){
		      
              $data = db::$i->row("SELECT `{$name}` FROM `user` WHERE `id`='{$this->id}'");
          
				return $data[$name];
		}
        				

		public function getData( $id = false ){
		  if(!$id) $id = $this->id;
          
			$data = db::$i->row( "select user.* FROM `user` user WHERE user.id='{$id}'" );
            if( $data['ref'] ){
                list( $data['reflogin'] ) = db::$i->row("select `login` from `user` where `id`='".intval( $data['ref'] )."'");    
            }
            
            return $data;
		}
        
        /**
         * @param int $id - User ID
         * @return object - User SQL Row
         */
        public static function get( $id ){
            return core::object( db::$i->row("SELECT * FROM `user` WHERE `id`='".esc( $id )."'") );
        }

        /**
         * @param int $id - User ID
         * @return object - User SQL Row
         */
        public static function getParsedObject( $id ){
            return core::object( self::parse( db::$i->row("SELECT * FROM `user` WHERE `id`='".esc( $id )."'") ) );
        }
                
        public function setData(){
			
            $data = db::$i->row("select * from `user` where `id`='".intval($this->id)."'");
            $this->AllData = $data;
            $this->setParams();
			
        }

        
        public static function parse( $data , $as_object = false ){
            
            $tmp = self::parseMinData( $data );
            
            
            // Full name
            if( $data['firstname'] AND $data['lastname'] )
            {
                $data['fullname'] = $data['firstname'] . ' ' . $data['lastname'];
            }
            else
            {
                $data['fullname'] = '<i class="fa fa-user-secret"></i> ' . $data['email'];
            }
            
            $data['ModeName'] = self::ModeName( $data['mode'] );

                return ( $as_object ? core::object( $data ) : $data );
        }
        
        public static function parse_admin( $item ){
            
            $item['display_login'] = $item['email'];
            

            $item['url_ip'] = admin::$i->url . '?mode='. core::$i->mode .'&ip=' . $item['regip'];
            $item['url_ref'] = admin::$i->url  . '?mode=' . core::$i->mode . '&ref=' . $item['id'];
            
                return $item;
        }
        
        public static function ModeName( $mode )
        {
            switch( $mode )
            {
                case 'admin':
                
                    $data = '<i class="fa fa-cog"></i> Administrator';
                    
                break;
                
                case 'therapist':
                
                    $data = '<i class="fa fa-user-md"></i> Terapeuta';
                    
                break;
                
                case 'user':
                default:
                    
                     $data = '<i class="fa fa-user"></i> Decydent';
                    
                break;
            }
            
                return $data;
        }

        
        public function getParse( $id ){
            return $this->parse( $this->getData( $id ) );
        }
        
        public static function parseMinData( $data ){
            
            if( !$data['login'] )
            {
                $data['login'] = 'Konto usunięte';
                $data['link'] = 'javascript:;';
            }
            
                return $data;
        }

        public static function parseInfo( $data ){
            
            if( is_object( $data ) )
            {
                $data = (array)$data;
            }
            
            $data['stars_desc'] = l( _cfg::$i->sql->stars->{$data['stars']} );
            
                return $data;
            
        }
            
        public static function byid( $id ){
            if( $data = db::$i->byid( 'user' , $id ) ) return $data;
            
            return false;
        }
        
        /**
         * @params array $params - 'field_name' => 'field_value'
         */
        public static function getBy( $params ){
            
            $conditions = array();
            
            foreach( $params as $field_name => $field_value ){
                $conditions[] = "`".$field_name."`='".esc( $field_value )."'";
            }
            
            if( count( $conditions ) ){
                
                $data = db::$i->row("SELECT * FROM `".( self::$sql_table )."` WHERE " . ( join(' AND ',$conditions) ) . " LIMIT 1" );
                
                if( $data ) return $data;
                
            }
            
             return false;
        }
         
         public static function listing( $params ){
            
            
         }
         
         public static function listing_parse( $item ){

                if( is_array( $item ) ){
                    
                    foreach( $item as $key => $value ){
                        
                        switch( $key ){
                            
                            case 'FIELD_NAME':
                                
                                
                                
                            break;
                            
                        }
                        
                        
                    }
                    
                }
                
                
                return $item;

         }
         
         public static function options( $item ){
            
            if( user::$i->mode == 'admin' )
            {
                
                $options[l('Szczegóły')] = array(
                        'mode' => 'user',
                        'id' => $item['id'],
                        'class' => 'row_details'
                );

                $options[l('Edytuj')] = array(
                        'mode' => 'user',
                        'id' => $item['id']
                );

                                                
                $options[l('Usuń')] = array(
                        'mode' => 'user',
                        'id' => $item['id']
                );
            } 
            else 
            {
                

            }     

                
                    return $options;
         }
         
            public static function details_parse( $html_rows ){
                
                foreach( $html_rows as $field_index => $field ){
                    
                    switch( $field['key'] ){
                        
                        case 'FIELD_SOME_NAME':
                        
                            $html_rows[$field_index]['name'] = $field['name'];        
                            $html_rows[$field_index]['html'] = $field['html'];  
                                                      
                        break;

                    }
                    
                }

                    return $html_rows;
            }
            
            public static function method_delete( $id ){
                
                return db::$i->del( 'user' , $id , 'id' );
                
            }


            public static function data($name){
                return self::$i->AllData[$name];
            }
            
            public static function get_all_count( $params = false ){
                
                if( $params ){
                    
                } else {
                    list( $count ) = db::$i->row("SELECT COUNT(1) FROM `user`");
                }
                
                    return intval( $count );
            }




            
	}
	

?>