<?php
class DataBrowse {
  private $_table;
  private  $_filtr;
  private  $_field_id;
  private  $_field_name;
  private  $_field_link;
  private  $_field_style;
  private  $_quantity;
  private  $_select;
  private  $_field_simple_id;
  private  $_param;
  private  $_field_action;
  private  $_field_tran;
  private  $_row_number;
  private  $_count;
  private  $_page_number;
  private  $_sort;
  private  $_filtr_id;
  private  $_filtr_name;
  private  $_filtr_field_tran;
  private  $_filtr_quantity;
  private  $_db_filtr;
  private  $_db_filtr_value;
  private  $_is_lp;
  private  $_lp;
  private  $_group_by;
  private  $_filtr_type;
  private  $_debug;
  private  $_limit = 25;
  private  $_filed_sort;
  private  $_sort_name;
  private  $_sort_way;
  private  $_paging_adress = 'index.php';
  private  $_checkbox = false;

  function DataBrowse( $table , $filtr = '' , $debug = false )
  {
    $this -> _table           = $table;
    $this -> _filtr           = $filtr;
    $this -> _quantity        = 0;
    $this -> _filtr_quantity  = 0;
    $this -> _debug           = $debug;
  }
  
  public function addCheckbox()
  {
    $this -> _checkbox = true;
  }

  function addGroupBy( $value )
  {
    $this -> _group_by = $value;
  }

  function addLp()
  {
    $this -> _is_lp = true;
    $this -> _lp    = true;
  }

  function setLimit( $val )
  {
    $this -> _limit = $val;
  }

  function addFiltr( $id , $nazwa , $tab = '' , $sql = '' )
  {
    global $db;
    if ( $nazwa )
    {
      $this -> _filtr_id[ $this -> _filtr_quantity ]    = $id;
      $this -> _filtr_name[ $this -> _filtr_quantity ]  = $nazwa;
      if ( $sql )
      {
        $query = $db -> prepare( $sql );
        $query -> execute();
        if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
          $tab[ $row[0] ] = $row[1];
        $query -> closeCursor();
      }
      if ( is_array($tab) )
        $this -> _filtr_field_tran[$this -> _filtr_quantity] = $tab;
      else
      {
        if ( !$tab )
          $tab = 'text';
        $this -> _filtr_type[ $this -> _filtr_quantity ] = $tab;
      }
      $this -> _filtr_quantity++;
    }
  }

  function addPosition( $id , $nazwa , $link = '' , $tab = '' , $style = '' , $sort = false )
  {
    global $db;
    if ( $nazwa )
    {
      $this -> _field_id[ $this -> _quantity ]    = $id;
      $this -> _field_name[ $this -> _quantity ]  = $nazwa;
      $this -> _field_link[ $id ]                 = $link;
      $this -> _field_style[ $id ]                = $style;
      $this -> _filed_sort[ $this -> _quantity ]  = $sort;
      if ( is_array( $tab ) )
        $this -> _field_tran[$id] = $tab;
      else
      {
        if ( $tab )
        {
          $query = $db -> prepare($tab);
          $query -> execute();
          if ( $query -> rowCount() ) while ( $res = $query -> fetch() )
            $tabs[$res[0]] = $res[1];
          $query -> closeCursor();
          $tabs[0] = '';
          $this -> _field_tran[$id] = $tabs;
        }
      }
      $this -> _quantity ++;
    }
  }

  function addPositionSimple( $id , $nazwa , $link = '' , $akcja = '' , $style = '' )
  {
    $this -> _field_simple_id[$this -> _quantity] = $id;
    $this -> _field_name[$this -> _quantity]      = $nazwa;
    $this -> _field_link[$id]                     = $link;
    $this -> _field_action[$id]                   = $akcja;
    $this -> _field_style[$id]                    = $style;
    $this -> _quantity++;
  }

  function setParam( $param )
  {
    $this -> _param = $param;
  }

  function addSort( $sort )
  {
    $this -> _sort = $sort;
  }

  function draw()
  {
    global $sys , $db , $bs , $lang;

    $out          = '';
    $filtr_ttext  = '';
    $filtr_combo  = '';
    $table_values = '';
    $filtr_text   = '';

    if ( $sys -> formGet( 'bs' ) ) {
      $sys -> setSessionVar( $this -> _table . '_bs' , $sys -> formGet('bs' ) );
    }
    $bs = $sys -> getSessionVar( $this -> _table . '_bs' );

    $page_type  = $sys -> getSessionVar( 'page_type' );
    $sort       = $sys->formGet( 's' );
    if ( $sort )
    {
      if ( $sys -> getSessionVar( $this -> _table . '_sort' . $sort ) == 'DESC' )
      {
        $this -> _sort      = $sort . ' ASC';
        $this -> _sort_name = $sort;
        $this -> _sort_way  = 'ASC';
        $sys->setSessionVar( $this -> _table . '_sort' . $sort , 'ASC' );
      }
      else
      {
        $this -> _sort      = $sort . ' DESC';
        $this -> _sort_name = $sort;
        $this -> _sort_way  = 'DESC';
        $sys->setSessionVar( $this -> _table . '_sort' . $sort , 'DESC' );
      }
    }

    if ( $sys->formGetInt( 'r' ) )
      $sys->setSessionVar( $this -> _table . '_limit' , $sys->formGetInt( 'r' ) );

    $limit = $sys->getSessionVar( $this -> _table . '_limit' );
    if ( !$limit )
      $limit = $this -> _limit;
    switch ( $limit )
    {
      case 5:
        $this -> _limit = 5;
      break;
      case 10:
        $this -> _limit = 10;
      break;
      case 25:
        $this -> _limit = 25;
      break;
      case 50:
        $this -> _limit = 50;
      break;
      case 100:
        $this -> _limit = 100;
      break;
      default:
        $this -> _limit = 25;
      break;
    }

    if ( $sys -> formGet( 'set_db_filtr' ) == 'yes' )
    {
      if ( is_array( $_POST ) ) foreach ( $_POST as $key => $val )
      {
        if ( $key != 'set_db_filtr' && $val != '' && $key != 'rows' )
        {
          $this -> _db_filtr_value[$key]  = $val;
          $pos_title  = array_search( $this -> _db_filtr_value[ $key ] , $this -> _db_filtr_value );
          $position   = array_search( $pos_title , $this -> _filtr_id );

          if ( $this -> _db_filtr && strpos( $key , '{trans}_trans' ) === false )
            $this -> _db_filtr .= ' AND ';

          if ( isset( $this -> _filtr_type[ $position ] ) && $this -> _filtr_type[ $position ] == 'text' )
            $this -> _db_filtr .= " $key LIKE '%$val%' ";
          else
          {
            if ( strpos( $key , '{trans}_trans' ) === false )
            {
              if ( strpos( $key , '{trans}' ) && is_array( $sys -> formGet( $key . '_trans' ) ) )
              {
                $count = 0;
                foreach ( $sys -> formGet( $key . '_trans' ) as $value_tmp )
                {
                  $value_tmp = explode( '[]' , $value_tmp );
                  if ( strpos( strtolower( $value_tmp[1] ) , strtolower( $val ) ) !== false )
                  {
                    if ( $this -> _db_filtr )
                      $this -> _db_filtr .= ' OR ';
                    $this -> _db_filtr .= str_replace( '{trans}' , '' , $key ) . " = '" . $value_tmp[0] . "'";
                  }
                  else
                    $count++;
                }
                if ( count( $sys -> formGet( $key . '_trans' ) ) == $count )
                  $this -> _db_filtr .= str_replace( '{trans}' , '' , $key ) . " = ''";
              }
              else
                $this -> _db_filtr .= " $key = '$val'";
            }
          }
        }
      }
      $sys -> setSessionVar( 'db_filtr_' . $page_type     , $this -> _db_filtr );
      $sys -> setSessionVar( 'db_filtr_value_' . $page_type   , $this -> _db_filtr_value );
    }

    if ( $sys -> formGet( 'set_db_filtr' ) == 'no' )
    {
      $sys -> deleteSessionVar( 'db_filtr_' . $page_type );
      $sys -> deleteSessionVar( 'db_filtr_value_' . $page_type );
    }
    $this -> _db_filtr          = $sys->getSessionVar( 'db_filtr_' . $page_type );
    $this -> _db_filtr_value  = $sys->getSessionVar( 'db_filtr_value_' . $page_type );

    $tpl = new \Savant3;

    if ( is_array( $this -> _filtr_id ) )
    {
      $tpl -> _filtr = true;
      for ( $x = 0; $x < $this -> _filtr_quantity; $x++ )
      {
        if ( isset( $this -> _filtr_field_tran[$x] ) )
        {
          if ( strpos( $this -> _filtr_id[$x] , '{trans}' ) !== false )
          {
            $filtr_tt['name']     = $lang -> getTrans( $this -> _filtr_name[ $x ] );
            $filtr_tt['seo_name'] = $this -> _filtr_id[ $x ];
            if ( isset( $this -> _db_filtr_value[ $this -> _filtr_id[ $x ] ] ))
              $filtr_tt['value']  = $this -> _db_filtr_value[ $this -> _filtr_id[ $x ] ];
            else
              $filtr_tt['value']  = '';
            if ( is_array($this -> _filtr_field_tran[$x]) ) foreach ( $this -> _filtr_field_tran[$x] as $key => $val )
              $filtr_tt['select'][$key] = $val;

            $filtr_ttext[]        = $filtr_tt;
          }
          else
          {
            $filtr_c              = '';
            $filtr_c['name']      = $lang -> getTrans( $this -> _filtr_name[$x] );
            $filtr_c['seo_name']  = $this -> _filtr_id[$x];

            if ( is_array( $this -> _filtr_field_tran[$x] ) ) foreach ( $this -> _filtr_field_tran[$x] as $key => $val )
              $filtr_c['value'][$key] = $val;

            if ( isset( $this -> _db_filtr_value[$this -> _filtr_id[$x]] ) )
              $filtr_c['val']     = $this -> _db_filtr_value[$this -> _filtr_id[$x]];

            $filtr_combo[]        = $filtr_c;
          }
        }

        if ( isset( $this -> _filtr_type[$x] ) && $this -> _filtr_type[$x] == 'text' )
        {
          $filtr_t['name']      = $lang -> getTrans($this -> _filtr_name[$x]);
          $filtr_t['seo_name']  = $this -> _filtr_id[$x];
          if ( isset( $this -> _db_filtr_value[$this -> _filtr_id[$x]] ) )
            $filtr_t['value']   = $this -> _db_filtr_value[$this -> _filtr_id[$x]];
          else
            $filtr_t['value']   = '';
          $filtr_text[]         = $filtr_t;
        }

        if ( isset( $this -> _filtr_type[$x] ) && $this -> _filtr_type[$x] == 'text-trans' )
        {
          $filtr_tt['name']       = $lang -> getTrans( $this -> _filtr_name[ $x ] );
          $filtr_tt['seo_name'] = $this -> _filtr_id[ $x ];
          $filtr_tt['value']    = $this -> _db_filtr_value[ $this -> _filtr_id[ $x ] ];
          if ( is_array($this -> _filtr_field_tran[$x]) ) foreach ( $this -> _filtr_field_tran[$x] as $key => $val )
            $filtr_tt['select'][$key] = $val;
          $filtr_ttext[]        = $filtr_tt;
        }
      }
      $tpl -> _filtr_ttext  = $filtr_ttext;
      $tpl -> _filtr_combo  = $filtr_combo;
      $tpl -> _filtr_text   = $filtr_text;
    }

    if ( is_array($this -> _field_id) ) foreach ( $this -> _field_id as $p )
    {
      if ( !$this -> _select )
      {
        $this -> _select = $p;
        if ( !$this -> _param )
          $this -> _param = $p;
      }
      else
        $this -> _select .= ", $p";
    }
    if ( is_array( $this -> _field_id ) && !in_array( $this -> _param,$this -> _field_id ) )
      $this -> _select .= ", " . $this -> _param;

    $sql_t = "SELECT count(1) FROM " . $this -> _table;

    $sql = "SELECT " . $this -> _select . " FROM " . $this -> _table;
    if ( $this -> _filtr )
    {
      $sql .= " WHERE " . $this -> _filtr;
      $sql_t .= " WHERE " . $this -> _filtr;
    }
    if ( $this -> _filtr && $this -> _db_filtr )
    {
      $sql .= " AND " . $this -> _db_filtr;
      $sql_t .= " AND " . $this -> _db_filtr;
    }
    else if ( !$this -> _filtr && $this -> _db_filtr )
    {
      $sql .= " WHERE " . $this -> _db_filtr;
      $sql_t .= " WHERE " . $this -> _db_filtr;
    }
    if ( $this -> _group_by )
    {
      $sql .= ' GROUP BY ' . $this -> _group_by;
      $sql_t .= ' GROUP BY ' . $this -> _group_by;
    }
    if ( $this -> _sort )
    {
      $sql .= " ORDER BY " . $this -> _sort;
      $sql_t .= " ORDER BY " . $this -> _sort;
    }

    $query = $db -> prepare ($sql_t) ;
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      $count_rows = $row[0];

    $ls = ceil( $count_rows / $this -> _limit );
    if ( (int)$bs > $ls )
      $bs = $ls;
    if ( (int)$bs < 1 )
      $bs = 1;
    $a  = $sys -> getPagingVar( 'a' , $bs , $ls );
    $b  = $sys -> getPagingVar( 'b' , $bs , $ls );

    $tpl -> _a    = $bs - $b;
    $tpl -> _b    = $bs + $a;
    $tpl -> _ls   = $ls;
    $tpl -> _link = $this -> _paging_adress;
    $tpl -> _bs   = $bs;

    if ( $this -> _limit )
      $sql .= " LIMIT " . ( $bs - 1 ) * $this -> _limit . "," . $this -> _limit;

    $query = $db -> prepare( $sql );
    $query -> execute();

    if ( $this -> _debug )
      print_r ($query -> errorInfo() );

    $tpl -> _row_count = $query -> rowCount();

    for ( $i = 0; $i < $this -> _quantity; $i++ )
    {
      if ( $this -> _is_lp )
      {
        $header[0]['value'] = $lang -> getTrans( 'T_LP' );
        $this -> _is_lp     = false;
      }
      $row['value']   = $this -> _field_name[$i];
      if ( isset( $this -> _filed_sort[$i] ) )
      {
        $row['sort'] = $this -> _field_id[$i];
        if ( $this -> _sort_name == $this -> _field_id[$i] )
          $row['way'] = $this -> _sort_way;
        else
          $row['way'] = '';
      }
      else
        $row['sort'] = false;
      $header[]   = $row;
    }
    $tpl -> _table_headers = $header;

    $i = $this -> _row_number * ( $bs - 1 ) + 1;
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      
      if ( $this -> _lp )
      {
        $values['lp']['style'] = 'text-align:center;';
        $values['lp']['value'] = ( $bs - 1 ) * $this -> _limit + $i . '.';
      }
      
      if ( $this -> _checkbox )
      {
        $values['checkbox']['value'] = '<input type="checkbox" name="checkbox" value="' . $row[ $this -> _param ] . '">';
      }
      
      if ( is_array($this -> _field_id) ) foreach ( $this -> _field_id as $key )
      {
        if ( isset( $this -> _field_tran[$key] ) && is_array($this -> _field_tran[$key]) )
        {
          if ( isset( $this -> _field_tran[$key][$row[$key]] ) ) {
            if ( strlen( $this -> _field_tran[$key][$row[$key]] ) > 50 )
            $values[$key]['value'] = mb_substr( $this -> _field_tran[$key][$row[$key]] , 0 , 50 , 'UTF-8' ) . '...';
            else
              $values[$key]['value'] = $this -> _field_tran[$key][$row[$key]];
          }
        }
        else
        {
          if ( strlen( $row[$key] ) > 50 )
          $values[$key]['value'] = mb_substr( $row[$key] , 0 , 50 , 'UTF-8' ) . '...';
          else
          $values[$key]['value'] = $row[$key];
        }
        $values[$key]['style'] = $this -> _field_style[$key];
      }
      if ( is_array( $this -> _field_simple_id ) ) foreach ( $this -> _field_simple_id as $key )
      {
        $val_temp = '';

        if ( $this -> _field_link[$key] )
          $val_temp .= '<a href="' . $this -> _field_link[$key] . '&id=' . $row[$this -> _param] . '">';

        if ( $this -> _field_action[$key] )
          $val_temp .= '<a ' . str_replace('[param]',$row[$this -> _param],$this -> _field_action[$key]) . '>';

        if ( $key == $lang -> getTrans( 'T_USUN' ) )
          $val_temp .= "<span class='icon delete'></span>";
        else if ( $key == $lang -> getTrans( 'T_EDYTUJ' ) )
          $val_temp .= "<span class='icon edit'></span>";
        else if ( $key == $lang -> getTrans( 'T_POKAZ' ) )
          $val_temp .= "<span class='icon show'></span>";
        else
          $val_temp .= $key;

        if ( $this -> _field_link[$key] || $this -> _field_action[$key] )
          $val_temp .= '</a>';

        $values[$key]['style'] = $this -> _field_style[$key];
        $values[$key]['value'] = $val_temp;
      }
      $table_values[] = $values;
      $i++;
    }
    $tpl -> _table_values   = $table_values;
    $tpl -> _limit          = $this -> _limit;
    $tpl -> _start          = $count_rows == 0 ? 0 : $this -> _limit * ( $bs - 1 ) + 1;
    $tpl -> _end            = $this -> _limit * $bs > $count_rows ? $count_rows : $this -> _limit * $bs;
    $tpl -> _total          = $count_rows;
    $tpl -> _checkbox       = $this -> _checkbox;
    $out .= $tpl -> fetch( 'templates/data-browse.php' );
    return $out;
  }

}
?>