<?php

    class listing{
        
        public $query;
        public $results;
        public $options;
        
        public $items = false;
        
        public $table; // SQL Table
        public $fields; // SQL Table Fields
        
        public $sql_fields = false;
        public $WHERE = array();
        public $WHERE_STRING = false;
        public $filter = array();
        public $filter_string = '';
        public $clear_fields;
        
        public $query_string = '';
        public $sql_query_string = '';
        
        public $order_field, $order_dir;
        public $ORDERBY_STRING = false;
        
        public $all_data;
        public $rows = 0;
        
        public $parse_class = false;
        public $own_listing = false;
        public $own_listing_parse = false;
        public $own_options = true;
        
        public $buttons = false;
                
        public $url;
        public static $i;
        
        public $skip_sql_fields = array(
            'proces_details'
        ); 
            
                    
        public static $no_order = 'NO_ORDER';
        
        /**
         * @param string $table - SQL Table
         * @param array $fields - Fields Array( 'key (SQL FIELD NAME)' => array( 'name' => FIELD DISPLAY NAME , 'order' => order (TRUE or FALSE) ) )
         * order default is true
         * @param string $order_field - SQL Field Name
         * @param string $order_dir - ASC or DESC
         */
        public function __construct( $table , $fields = false , $order_field = false , $order_dir = false , $where = false ){


            if( $where ) array_push( $this->WHERE , $where );

            $this->parse_filters_from_query_string();
            
            $this->url = admin::$i->url . '?' . ( !empty( $this->query_string ) ? $this->query_string : '' );

            // Set params
            $this->table = $table;
            $this->order_field = $order_field ? $order_field : 'id';
            $this->order_dir = $order_dir ? $order_dir : 'DESC';

            
            // Set fields from param or get fields from SQL Table
            if( !$fields ){
                
                $this->fields = array();
                $fields_query = db::$i->q("DESCRIBE " . esc( $this->table ),true);
                
                if( db::$i->rows ){
                    
                    while( $item = db::$i->f( $fields_query ) ){
                        
                        if( array_key_exists( $item['Field'] , row_details::$name_map ) ){
                            
                            if( is_array( row_details::$name_map[$item['Field']] ) ) $Name = ( isset( row_details::$name_map[$item['Field']][$this->table] ) ? row_details::$name_map[$item['Field']][$this->table] : row_details::$name_map[$item['Field']]['default'] );
                            else $Name = row_details::$name_map[$item['Field']];
                            
                        } else $Name = ucfirst( $item['Field'] );
                    
                        //if( !in_array( $item['Field'] , row_details::$hidden_fields ) ){
                            $this->fields[$item['Field']] = array(
                                'name' => $Name,//( row_details::$name_map[$item['Field']] ? row_details::$name_map[$item['Field']] : ucfirst( l($item['Field']) ) ),
                                'order' => ( ( $item['type'] == 'TEXT' OR $item['Type'] == 'LONGTEXT' ) ? false : true )
                            );
                        //}
                    }
                    
                }
                
            } else {

                foreach( $fields as $field_key => $field ){

                    
                    //if( !in_array( $field , row_details::$hidden_fields )){
                    
                        // Full Array
                        if( is_array( $field ) ){
                            
                            if( !isset($field['name']) ) $field['name'] = ( row_details::$name_map[$field_key] ? row_details::$name_map[$field_key] : ucfirst( l($field_key) ) );
                            
                            $this->fields[$field_key] = $field;
                        
                        // Simple Field Name
                        } else {
                            
                            $this->fields[$field] = array(
                                'name' => self::key_name( $field , $this->table ),
                                'order' => ( in_array( $field , $this->skip_sql_fields ) ? false : true ),
                                'sql' => false
                            );
                            
                        }
                    
                    //}
                    
                }
                
                
            }

            
            $this->parse();
            
            self::$i = $this;
        }
        
        /**
         * Parse Results / Listing
         */
        public function parse(){


            // Limits
            if( is_numeric( $_REQUEST['order_limit'] ) ){
                str::$i->modify( 'limit' , intval( $_REQUEST['order_limit'] ) );
            }

            // Order
            if( count( $this->fields ) ){
                
                //$str_orders['f_select'] = 'select';
                
                foreach( $this->fields as $field_name => $field_value ){
                    
                    $str_orders['f_'.$field_name] = ( $field_value['order'] ? $field_name : 'NO_ORDER' );
                
                }
                
                // Multiple orders
                if( is_array( $this->order_field ) ){
                    
                    foreach( $this->order_field as $order_key => $order_value ){
                        
                        $order_params[] = "listing.".esc( $order_key )." " . esc( $order_value );
                        
                    }
                    
                    str::$i->orders( $str_orders , join(',',$order_params) );
                    
                // Single order
                } else {
                    
                    str::$i->orders( $str_orders ,"listing.".( esc( $this->order_field ) )." " . esc( $this->order_dir ));
                
                }
                
                               
            }
            

            $this->ORDERBY_STRING = str::$i->order_by ? str::$i->order_by : '';
            
            // Where
            $this->catch_where();
            
            if( count( $this->WHERE ) ) $this->WHERE_STRING = ' WHERE ' . join( ' AND ' , $this->WHERE  );
            else $this->WHERE_STRING = '';
            
            // Query & Listing
            
            $class_name = row_details::$class_map[$this->table] ? row_details::$class_map[$this->table] : $this->table;

            if( class_exists( $class_name , true ) ){
                $this->parse_class = $class_name;
                $this->own_listing = $class_name::$own_listing;
                $this->own_listing_parse = $class_name::$own_listing_parse;
                $this->own_options = $class_name::$own_options;
                
                if( method_exists( $class_name , 'buttons' ) ){
                    $this->buttons = $class_name::buttons( $_REQUEST );
                }
            }
            
            // Own Listing
            $this->results = $this->get_rows();

            
        }

        /**
         * Catch Where Params
         */
        public function catch_where(){
            
            foreach( $_REQUEST as $request_key => $request_value ){
                
                if( !empty( $request_value ) ){
                    
                    switch( $request_key ){

                        default:
                        
                            if( substr( $request_key , 0 , 2 ) == 'w_' ){
                            
                                $this->filter = true;
                                
                                array_push( $this->WHERE , "listing.".( esc( str_replace( "w_" , "" , $request_key ) ) )."='".( esc( $request_value ) )."'" );
                                // Debug
                                //debug::printr( $this->WHERE );
                            }
                        break;
                        
                    }
                    
                }
                
            }
            
        }
        
        /**
         * Return Data Array( 'rows' => SQL ROWS COUNT , 'data' => SQL ROWS )
         */
        public function get_rows(){
            
            // Bulding Query Select String
            foreach( $this->fields as $filed_name => $field_value ){
                
                // Check field name in skip_sql_fields array (no sql field names base)
                
                // DEBUG
                //$secondfields[] = $filed_name;
                
                if( !in_array( $filed_name , $this->skip_sql_fields ) ){
                    if( $field_value['sql'] ){
                        $sql_select[] = $field_value['sql'] . ' AS '.$filed_name;
                    } else {
                        $sql_select[] = 'listing.'.$filed_name;
                    }
                }

                
            }
            
            
            // Get listing 
            $this->sql_query_string = "SELECT ".( count($sql_select) ? join(',',$sql_select) : "listing.*" )." FROM `".( $this->table )."` listing{$this->WHERE_STRING}{$this->ORDERBY_STRING}";
            $this->query = db::$i->q( $this->sql_query_string ,false,true);
            
            // Debug SQL query
            //debug::printr( 'querry:' . db::$i->query );
            
            if( $this->rows = db::$i->rows ){
                
                $data = array();
                
                while( $item = db::$i->f( $this->query ) ){
                    
                    /**
                    // Own Parse
                    if( $this->own_listing_parse ){
                        
                        $class_name = $this->parse_class;
                        $data[] = $class_name::listing_parse( $item );
                        
                    // Default Parse
                    } else {
                        
                        $data[] = $this->row_parse( $item );
                        
                    }
                    **/
                    
                    //<i class="fa fa-edit"></i> $item );

                    $this->clear_fields[] = $item;
                    
                    if( !$item['hidden'] ) $data[] = $this->row_parse( $item );

                }
                
                $this->items = $data;
                
            }
            
        }
        
        /**
         * Row Parse = $class::listing_parse()
         */
        public function row_parse( $item ){

            
            $results = array();
                   
            // Display & Parse Fields
            if( !is_numeric( $item ) ){
                

                //$results['display']['select'] = '<input type="checkbox" name="series['.( $item['id'] ).']" value="'.( $item['id'] ).'" />';

                
                foreach( $this->fields as $key => $value ){
                    
                    if( !in_array( $key , row_details::$hidden_fields ) ){
                        
                        $parsed = false;
                        
                        // If key in field list
                        
                        switch( $key ){
                            
                            case 'id':
                                
                                switch( $this->table ){
                                    
                                    case 'ads_banner':
                                        $parsed = $item[$key];
                                    break;
                                    
                                    default:
                                        $parsed = $item[$key];
                                    break;
                                    
                                }
                                
                            break;
                            
                            case 'user':
                            case 'therapist':

                                if( $item[$key] )
                                {

                                    if( user::$i->mode == 'admin' )
                                    {
                                        $parsed = self::row_parse_html( array(
                                            'html' => '#'.$item[$key],
                                            'params' => array(
                                                'data-uid' => $item[$key],
                                                'data-table' => 'user',
                                                'data-id' => $item[$key],
                                                'class' => 'row_details'
                                            )
                                        ) , 'a' );
        
            
                                        $parsed .= ' ' . self::row_parse_html( array(
                                            'html' => '<i class="fa fa-filter"></i>',
                                            'params' => array(
                                                'href' => ( admin::$i->url . '?mode=' . core::$i->mode . '&function=' . core::$i->function . '&w_'.( $key ).'=' . $item[$key] ),
                                                'title' => l('Filter')
                                            )
                                        ) , 'a' );
                                    } 
                                    else 
                                    {
                                        
                                        
                                        
                                        if( $item[$key] == user::$i->id )
                                        {
                                            $parsed = 'JA';
                                        } 
                                        else 
                                        {
                                            list( $email , $firstname , $lastname ) = db::$i->row("SELECT `email`,`firstname`,`lastname` FROM `user` WHERE `id`='".( $item[$key] )."'");
                                            $parsed = ( $firstname ? ( $firstname . ( $lastname ? ( ' ' . $lastname ) : '' ) ) : $email );
                                        }
            
                                        $parsed .= ' ' . self::row_parse_html( array(
                                            'html' => '<i class="fa fa-filter"></i>',
                                            'params' => array(
                                                'href' => ( admin::$i->url . '?mode=' . core::$i->mode . '&function=' . core::$i->function . '&w_'.( $key ).'=' . $item[$key] ),
                                                'title' => l('Filter')
                                            )
                                        ) , 'a' );
                                    }
                                
                                } 
                                else 
                                {
                                    $parsed = '<span style="color:#C7C7C7">'.l('Predefiniowany').'</span>';
                                }
                                
                            break;
                            
                            case 'uid':
                                
                                $parsed = self::row_parse_html( array(
                                    'html' => '#'.$item[$key],
                                    'params' => array(
                                        'data-uid' => $item[$key],
                                        'data-table' => 'user',
                                        'data-id' => $item[$key],
                                        'class' => 'row_details'
                                    )
                                ) , 'a' );

    
                                $parsed .= ' ' . self::row_parse_html( array(
                                    'html' => '<i class="fa fa-filter"></i>',
                                    'params' => array(
                                        'href' => ( admin::$i->url . '?mode=' . core::$i->mode . '&function=' . core::$i->function . '&w_'.( $key ).'=' . $item[$key] ),
                                        'title' => l('Filter')
                                    )
                                ) , 'a' );
                                                            
                            break;
                            
                            case 'src':
                            case 'image':
                                
                                if( $item[$key] )
                                {
                                    $parsed = '<a href="javascript:;" data-image="'.( $item[$key] ).'"><i class="fa fa-search"></i></a>';
                                } 
                                else 
                                {
                                    $parsed = '<span style="color:#C7C7C7">'.l('brak').'</span>';
                                }
                                
                            break;
                            
                            //
                            case 'email':
                            
                                $parsed = self::row_parse_html( array(
                                    'html' => $item[$key],
                                    'params' => array(
                                        'href' => 'mailto:'.$item[$key],
                                        'title' => l('Wyślij wiadomość')
                                    )
                                ) , 'a' );
                                
                            break;
                            
                            
                            case 'mode':
                            
                                $parsed = user::ModeName( $item[$key] );
                                
                            break;
                            
                            case 'crt':
                            case 'mdf':
                            case 'end';
                                
                                if( $this->table == 'procesy' )
                                {
                                    if( !$item['user'] )
                                    {
                                        $parsed = '<span style="color:#C7C7C7">'.l('nie dotyczy') .'</span>';
                                    } 
                                    else 
                                    {
                                        if( !$item[$key] )
                                        {
                                            $parsed = ( $key == 'end' ? '<span style="color:#C7C7C7">'.l('Trwa').'</span>' : '-' );
                                        } 
                                        else 
                                        {
                                            $parsed = str_replace( " " , "<br />" , $item[$key] );
                                        }
                                    }
                                } 
                                else 
                                {
                                    if( !$item[$key] )
                                    {
                                        $parsed = ( $key == 'end' ? '<span style="color:#C7C7C7">'.l('Trwa').'</span>' : '-' );
                                    } 
                                    else 
                                    {
                                        $parsed = str_replace( " " , "<br />" , $item[$key] );
                                    }
                                }
                            break;
                            
                            
                            case 'status':
                    

                                $parsed = display::status_name( $item[$key] );

                    
                            break;
                            

                            case 'proces_id':
                                
                                if( $item[$key] )
                                {
                                    list( $parsed ) = db::$i->row("
                                        SELECT `nazwa` 
                                        FROM `procesy` 
                                        WHERE `id`='".intval( $item[$key] )."'
                                    ");  
                                    
                                    if( empty( $parsed ) ) $parsed = '<span style="color:#C7C7C7">'.l('Usunięty').'</span>';
                                    
                                    $parsed .= ' ' . self::row_parse_html( array(
                                        'html' => '<i class="fa fa-filter"></i>',
                                        'params' => array(
                                            'href' => ( admin::$i->url . '?mode=' . core::$i->mode . '&function=' . core::$i->function . '&w_'.( $key ).'=' . $item[$key] ),
                                            'title' => l('Filter')
                                        )
                                    ) , 'a' );
                                } 
                                else 
                                {
                                    $parsed = '<span style="color:#C7C7C7">predefiniowany</span>';
                                    //$parsed = '<span style="color:#C7C7C7">'.l('Predefiniowana').'</span>';
                                }
                                
                            break;

                            case 'temat_id':
                                
                                if( $item[$key] )
                                {
                                    
                                    list( $parsed ) = db::$i->row("
                                        SELECT `nazwa` 
                                        FROM `tematy` 
                                        WHERE `id`='".intval( $item[$key] )."'
                                    ");  
                                    
                                    $parsed .= ' ' . self::row_parse_html( array(
                                        'html' => '<i class="fa fa-filter"></i>',
                                        'params' => array(
                                            'href' => ( admin::$i->url . '?mode=' . core::$i->mode . '&function=' . core::$i->function . '&w_'.( $key ).'=' . $item[$key] ),
                                            'title' => l('Filter')
                                        )
                                    ) , 'a' );
                                } 
                                else 
                                {
                                        debug::printr( $item[$key] );
                                    $parsed = '<span style="color:#C7C7C7">'.l('Predefiniowana').'</span>';
                                }
                                
                            break;
                            
                            case 'kryterium_id':
                                
                                if( $item[$key] )
                                {
                                    
                                    list( $parsed ) = db::$i->row("
                                        SELECT `nazwa` 
                                        FROM `kryteria` 
                                        WHERE `id`='".intval( $item[$key] )."'
                                    ");  
                                    
                                    $parsed .= ' ' . self::row_parse_html( array(
                                        'html' => '<i class="fa fa-filter"></i>',
                                        'params' => array(
                                            'href' => ( admin::$i->url . '?mode=' . core::$i->mode . '&function=' . core::$i->function . '&w_'.( $key ).'=' . $item[$key] ),
                                            'title' => l('Filter')
                                        )
                                    ) , 'a' );
                                } 
                                else 
                                {
                                        debug::printr( $item[$key] );
                                    $parsed = '<span style="color:#C7C7C7">'.l('Brak').'</span>';
                                }
                                
                            break;
                            
                            case 'proces_details':
                            
                                $parsed = '<div class="wmax tar">';
                                
                                if( $item['end'] OR user::$i->mode == 'therapist' )
                                {
                                    $parsed  .= '<a href="index.php?mode='.( user::$i->mode == 'user' ? 'user' : 'therapist' ).'&function=proces&id='.( $item['id'] ).'" class="btn btn-primary SetTooltip" title="Szczegóły"><i class="fa fa-search"></i></a>';
                                    
                                } 

                                if( $item['end'] AND user::$i->mode == 'therapist' )
                                {
                                    $parsed  .= ' <a href="index.php?mode=therapist&function=proces_copy&id='.( $item['id'] ).'" class="btn btn-primary SetTooltip" title="Kopiuj"><i class="fa fa-copy"></i></a>';
                                }
                                
                                if( $item['user'] !== null AND user::$i->mode == 'therapist' )
                                {
                                    $parsed  .= ' <a href="index.php?mode=therapist&function=proces_delete&id='.( $item['id'] ).'" class="btn btn-danger SetTooltip" title="Usuń"><i class="fa fa-trash"></i></a>';
                                }
                                
                                $parsed .= "</div>";
                                
                            break;

                            case 'typ_id':
                                
                                if( $item[$key] )
                                {
                                    list( $parsed ) = db::$i->row("
                                        SELECT `nazwa` 
                                        FROM `typ_kryterium` 
                                        WHERE `id`='".intval( $item[$key] )."'
                                    ");  
                                } 
                                else 
                                {
                                    $parsed = '<span style="color:#C7C7C7">'.l('Predefiniowana').'</span>';
                                }
                                
                            break;
                                                        
                            case 'wektor':
                                
                                $parsed = $item[$key] ? $item[$key] : '<span style="color:#C7C7C7">'.l('Brak').'</span>';
                                
                            break;
                                                                                
                            default:
                                
                                $parsed = $item[$key];
                                
                            break;
                            
                        }
                        
                        $results['parsed'][$key] = $parsed;

                        
                        if( array_key_exists( $key ,$this->fields ) ){
                            $results['display'][self::key_name($key)] = $parsed;
                        }
                        
                        if( !is_numeric( $key ) ) $results['sql'] = $item[$key];
                    }
                }
                
                
            }
            
            
            // Options
            if( $this->own_options ){
                
                $class_name = $this->parse_class;
                $results['options']['data'] = $class_name::options( $item );
                
            } else {
                
                $results['options']['data'] =array(
                    l('Szczegóły') => array(
                        'mode' => $this->table,
                        'id' => $item['id'],
                        'class' => 'row_details'
                    ),
                    
                    l('Usuń') => array(
                        'mode' => $this->table,
                        'id' => $item['id']
                    )
                );
                
            }
            
            
            $results['options']['display'] = admin::parse_listing_options( $results['options']['data'] );
            
            // OWN parse
            if( $this->own_listing_parse ){
                
                $class_name = $this->parse_class;
                
                // DEBUG
                //<i class="fa fa-edit"></i> 'PHP Class: ' . $class_name );
                $results['display'] = $class_name::listing_parse( $results['display'] );
     
                
            }
            
            
                return $results;
        }
        
        /**
         * Parse Row HTML Element
         * @param array $arr - Params Array
         * @param string $type - HTML Element
         */
        public static function row_parse_html( $arr , $type = 'a' ){
            
            switch( $type ){
                
                // anchor - <a href=""></a>
                case 'a':

                    $html = '<a';
                    
                    if( !array_key_exists( 'href' , $arr['params'] ) ){
                        $arr['params']['href'] = 'javascript:;';
                    }
                    
                    if( is_array( $arr['params'] ) ){
                        foreach( $arr['params'] as $param_name => $param_value ){
                            $html .= ' ' . $param_name . '="' . $param_value . '"';
                        }
                    }
                    
                    $html .= '>'.$arr['html'].'</a>';
                    
                break;
                
                default:
                    
                    $html = '<'.$type;
                    
                    if( is_array( $arr['params'] ) ){
                        foreach( $arr['params'] as $param_name => $param_value ){
                            $html .= ' ' . $param_name . '="' . $param_value . '"';
                        }
                    }
                    
                    $html .= '>'.$arr['html'].'</'.$type.'>';
                    
                break;
                
            }
            
                return $html;
        }
        
        public function parse_filters_from_query_string(){
            
            $query_array = parse::query_string();
            
            if( count( $query_array ) ){
                
                // TMP Array for $this->filter_string
                $tmp_array = array();
                
                // TMP Array for $this->query_string
                $tmp_query_string_array = array();
                
                foreach( $query_array as $key => $value ){
                    
                    if( substr( $key , 0 , 2 ) == 'w_' ){
                        $this->filter[$key] = $value;
                        array_push( $tmp_array , $key . '=' . $value );
                    }
                    
                    array_push( $tmp_query_string_array , $key . '=' . $value );
                    
                }

                $this->filter_string = ( count( $tmp_array ) ? join( '&' , $tmp_array ) : '' );
                $this->query_string = join( '&' , $tmp_query_string_array );
                
            }
            
        }
        
        public static function key_name( $key , $table = 'default' ){
           
            if( array_key_exists( $key , row_details::$name_map ) ){
                
                if( is_array( row_details::$name_map[$key] ) ) $name = ( isset( row_details::$name_map[$key][$table] ) ? row_details::$name_map[$key][$table] : row_details::$name_map[$key]['default'] );
                else $name = row_details::$name_map[$key];
                
            } else $name = ucfirst( $key );
            
            return $name;
        }

    }

?>