<?php

class PageSearch extends Page
{
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Title = 'Vyhledávání';
    $this->Description = 'Hledání v obsahu';
    $this->ParentClass = 'PagePortal';
  }

  function Show(): string
  {
    $Output = '';
    if (array_key_exists('t', $_GET)) $Text = $_GET['t'];
      else $Text = '';
    $Output .= '<form action="?" method="get">'.
    'Hledaný text: <input name="t" value="'.$Text.'"/>'.
    '<input type="submit" value="Hledat"/>'.
    '</form>';
    if ($Text != '')
    foreach (ModuleSearch::Cast($this->System->GetModule('Search'))->Items as $Item)
    {
      $Columns = '';
      $Condition = '';
      foreach ($Item['Columns'] as $Column)
      {
        $Columns .= ', `'.$Column.'`';
        $Condition .= ' OR (`'.$Column.'` LIKE "%'.$Text.'%")';
      }
      $Columns = substr($Columns, 2);
      $Condition = substr($Condition, 3);
      $DbResult = $this->Database->Select($Item['Table'], $Columns, $Condition.' LIMIT '.
        ModuleSearch::Cast($this->System->GetModule('Search'))->MaxItemCount);
      if ($DbResult->num_rows > 0) $Output .= '<strong>'.$Item['Name'].'</strong><br/>';
      while ($Row = $DbResult->fetch_assoc())
      {
        $Output .= '<p>';
        foreach ($Item['Columns'] as $Column)
          $Output .= $Row[$Column].'<br/>';
        $Output .= '</p>';
      }
    }
    return $Output;
  }
}

class ModuleSearch extends Module
{
  public array $Items;
  public int $MaxItemCount;

  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Search';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPLv3';
    $this->Description = 'Allow search through registered content objects';

    $this->MaxItemCount = 10;
    $this->Items = array();
  }

  function DoStart(): void
  {
    $this->System->Pages['search'] = 'PageSearch';
  }

  function RegisterSearch(string $Title, string $TableName, array $Columns): void
  {
    $this->Items[] = array('Name' => $Title, 'Table' => $TableName, 'Columns' => $Columns);
  }

  static function Cast(Module $Module): ModuleSearch
  {
    if ($Module instanceof ModuleSearch)
    {
      return $Module;
    }
    throw new Exception('Expected ModuleSearch type but got '.gettype($Module));
  }
}
