<?php
 
    class core{
        
        public $route , $module , $url, $subdomain;
        static $instance , $i;
        
        public function __construct(){
            

            // Wymuszenie https
            if( _cfg::$i->web->ssl_force AND $_SERVER['REQUEST_SCHEME'] != 'https' ){
                @header( "Location:https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
                exit;
            }

            // WILDCARD - Subdomena
            if( !in_array( $_SERVER['HTTP_HOST'] , array( 'localhost' , '127.0.0.1' ) ) ){
                
                $tmp = explode( '.' , $_SERVER['HTTP_HOST'] );
                
                // Dodać warunki lub całkowicie zmienić tą metodą rozpoznawania subdomen
                if( count($tmp)>2 ){
                    $this->subdomain = $tmp[0];
                    
                } else {
                    $this->subdomain = false;
                }
                
            } else $this->subdomain = false;
            
            
            
            
            if(isset($_SERVER['REQUEST_SCHEME']) AND !empty($_SERVER['REQUEST_SCHEME'])){
                $scheme = $_SERVER['REQUEST_SCHEME'];
            } elseif( isset($_SERVER['SCRIPT_URI']) AND !empty($_SERVER['SCRIPT_URI']) AND stristr($_SERVER['SCRIPT_URI'],'http') ){
                $scheme = ( stristr( $_SERVER['SCRIPT_URI'] , 'https' ) ? 'https' : 'http' );
            } else {
                $scheme = ( _cfg::$i->web->ssl_force ? 'https' : 'http' );
            }
            
            $this->url = $scheme . '://' . str_replace("www.","",$_SERVER['HTTP_HOST']) . ( !empty( _cfg::$i->web->dir ) ? ( '/' . _cfg::$i->web->dir ) : '' );
            
            if( $this->subdomain ){
                
                $this->url = str_replace(array('://'.$this->subdomain.'.'),array('://'),$this->url);
                
            }
            
            self::$instance = $this;
            self::$i = $this;
            
        }

        /**
         * Load std config records etc.
         */
        public static function LoadStd( $params = false )
        {
        }
        
        public function setValue( $name , $arr ){

            if(!empty($_GET[$name]) or !empty($_POST[$name])){
                
                $this -> {$name} = (!empty($_POST[$name]) ? self::parseValue($_POST[$name],$arr) : self::parseValue($_GET[$name],$arr));
                if( $arr['function'] ){
                    $this -> {$name} = $arr['function']( $this -> {$name} );
                }
            
            } else $this -> {$name} = $arr['default'];
                    

        }

        public static function parseValue( $value  , $arr ){
            
            switch( $arr['type'] ){
                
                // String
                case 'core-string':
                    return $value;
                break;
                
                // Escaped
                case 'escape':
                    return esc( $value );
                break;
                
                // Int value
                case 'int':
                    $value = intval( $value );
                    if($value<=0) return $arr['minimal'];
                    else return $value;
                break;
                
                // Float value
                case 'float':
                    $value = float( $value );
                    if($value<=0) return $arr['minimal'];
                    else return $value;
                break;
                
            }  
        
        }
        
        public static function read( $name , $subname ){
            
            $farr = db::$i->getBy( null , 'config' , array(
                'name' => esc( $name ),
                'subname' => esc( $subname )
            ),'1',true);
                
                _cfg::$i->sql->$name->$subname = $farr['value'];
                
                return $farr['value'];
            
        }

        /**
         * Get Config Group As Object
         * @param string $group_name - Config group name
         * @return object - Config group
         */
        public static function GetConfigGroup( $group_name ){
            
            $query = db::$i->q("SELECT * FROM `config` WHERE `name`='".( esc( $group_name ) )."' ORDER BY `id` ASC",true);
            if( db::$i->rows )
            {
                while( $ConfigItem = db::$i->f( $query ) )
                {
                    _cfg::$i->sql->$ConfigItem['name']->$ConfigItem['subname'] = $ConfigItem['value'];
                }
            }

                
                return _cfg::$i->sql->$group_name;
            
        }
                
        /**
         * @param array $_cfg_array - array( 'name:subname' )
         */
        public static function read_multi( $_cfg_array ){
            
            if( is_array( $_cfg_array ) ){
                
                foreach( $_cfg_array as $_cfg_item ){
                    
                    if( stristr( $_cfg_item , ':' ) ){
                        
                        list( $_cfg_name , $_cfg_subname ) = explode(":",$_cfg_item);
                        _cfg::$i->sql->$_cfg_name->$_cfg_subname = self::read( $_cfg_name , $_cfg_subname );

                    }
                    
                }
                
               //debug::printr( _cfg::$i );
                
            }
            
        }

        public function saveConfig( $name , $subname , $value = '' ){
            
            if( db::$instance->getBy( null , 'config' , array(
                'name' => esc( $name ),
                'subname' => esc( $subname )
            ),'1',true) ){
                
                // Aktualizacja
                db::$instance->update('config',array('value'=>esc($value),'mdf'=>date("Y-m-d H:i:s")),false,"`name`='".esc($name)."' AND `subname`='".esc($subname)."'");

            } else {
                // Utworzenie parametru
                db::$instance->insert('config',array(
                    'name' => esc($name),
                    'subname' => esc($subname),
                    'value' => esc($value)
                ));
            }
            
                
            
        }


        public static function page404(){
            global $tpl;
            
            page::$i->val( $tpl->fetch('tpl/404.tpl') );
        }

        
        public static function object( $array ){
            return json_decode( json_encode( $array ) , FALSE );
        }
        
		public static function POST(){
			if($_SERVER['REQUEST_METHOD']=='POST') return true;
			else return false;
		}
        
        public static function AJAX(){
            if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') return true;
            else return false;
        }
        
        public static function UCP(){
            if(stristr($_SERVER['SCRIPT_NAME'],'UI.php')) return true;
            else return false;
        }
        
		public static function back(){
            @ob_end_clean();
			@header("Location:".( isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : core::$i->url ));
            exit;
		}

        public static function get_ip(){
            return ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'] );
        }
        
        public static function go( $url = false ){
            //@ob_end_clean();
            header("Location:".self::$i->url.'/'.( $url ? $url : ''));
            exit;
        }

        /**
         * 
         */
        public static function GetMoreVarsFromURI(){
        
            $more_vars = array();
            
            $string = $_SERVER['REQUEST_URI'];
           
            if( stristr( $string , "?" ) ){
                list( $url , $vars ) = explode( "?" , $string );
                 
                // Więcej zmiennych
                if( stristr( $vars , '&') ){
                        
                     $group = explode('&',$vars);

                     foreach( $group as $single_var ){
                        
                        if( stristr( $single_var , '=' ) ){
                            list( $key , $value ) = explode('=',$single_var);
                            $more_vars[$key] = $value;
                        }
                     }
                     
                     
                        
                // Jedna zmienna
                } elseif( stristr( $vars , '=') ){
                    
                    list( $key , $value ) = explode('=',$vars);
                    $more_vars[$key] = $value;
                    
                // Brak zmiennych
                }
                
                
            }
            
                return $more_vars;
        }        
    }



?>