<?php

class DbPageListView extends PageListView
{
  var $SQL;
  var $Table;
  var $Database;
  var $ShowTotal;
  var $Filter;
  var $OnRowDraw;
  var $OrderDirSQL;

  function __construct()
  {
    parent::__construct();
    $this->ShowTotal = true;
    $this->SQL = '';
    $this->OrderDirSQL = array('ASC', 'DESC');
  }

  function Show(): string
  {
    // Get total item count in database
    $Query = 'SELECT COUNT(*) FROM '.$this->SQL;
    $DbResult = $this->Database->query($Query);
    $DbRow = $DbResult->fetch_assoc();
    $TotalCount = $DbRow['COUNT(*)'];

    $ColumnSQL = array();
    foreach ($this->Columns as $Column)
    {
      $ColumnSQL[] = $Column->Name;
    }
    $ColumnSQL = implode(', ', $ColumnSQL);

    // Get total filtered item count in database
    if ($this->Filter != '')
    {
      $Query = 'SELECT COUNT(*) FROM (SELECT '.$ColumnSQL.' FROM '.$this->SQL.') AS `TS` '.$this->Filter;
      $DbResult = $this->Database->query($Query);
      $DbRow = $DbResult->fetch_row();
      $TotalFilteredCount = $DbRow[0];
    } else $TotalFilteredCount = $TotalCount;
    $this->PageSelect->Count = $TotalFilteredCount;

    $this->Rows = array();
    $VisibleItemCount = 0;
    if (($this->SortOrder != 0) and ($this->SortOrder != 1)) $this->SortOrder = 0;
    //if ($this->SortColumn)
    $this->SortColumn = $this->Columns[0]->Name;
    $this->OrderSQL = ' ORDER BY `'.$this->SortColumn.'` '.$this->OrderDirSQL[$this->SortOrder];
    $SQLLimit = ' LIMIT '.$this->PageSelect->Position * $this->PageSelect->PageSize.', '.$this->PageSelect->PageSize;
    $Query = 'SELECT * FROM (SELECT '.$ColumnSQL.' FROM '.$this->SQL.') AS `TS` '.
      $this->Filter.' '.$this->OrderSQL.$SQLLimit;
    $DbResult = $this->Database->query($Query);
    while ($DbRow = $DbResult->fetch_assoc())
    {
      if (method_exists($this->OnRowDraw[0], $this->OnRowDraw[1]))
        $DbRow = call_user_func($this->OnRowDraw, $DbRow);
      $this->Rows[] = $DbRow;
      $VisibleItemCount = $VisibleItemCount + 1;
    }
    $Row = '<td colspan="'.count($this->Columns).'" style="text-align: right;">Zobrazeno <strong>'.$VisibleItemCount.'</strong>';
    if ($this->Filter != '') $Row .= ' z filtrovaných <strong>'.$TotalFilteredCount.'</strong>';
    $Row .= ' z celkem <strong>'.$TotalCount.'</strong>';
    $ListView->Rows[] = $Row;
    $Output = parent::Show();
    return $Output;
  }
}
