<?php

class ModuleSearch extends Module
{
  var $SearchItems;

  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Search';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Allow test search in other modules content.';
    $this->Dependencies = array();
    $this->SearchItems = array();
  }

  function DoStart(): void
  {
    $this->System->RegisterPage(['search'], 'PageSearch');
    Core::Cast($this->System)->RegisterPageBarItem('Left', 'Search', array($this, 'ShowSearchBox'));
  }

  function RegisterSearch($Name, $Title, $Columns, $Query, $Link)
  {
    // Query can be table name or subselect query
    $this->SearchItems[$Name] = array('Name' => $Title, 'Columns' => $Columns,
      'Query' => $Query, 'Link' => $Link);
  }

  function UnregisterSearch($Name)
  {
    unset($this->SearchItems[$Name]);
  }

  function ShowSearchBox()
  {
    $Output = '<strong>'.T('Search').':</strong>'.
      '<form action="'.$this->System->Link('/search/').'" method="get"><div>'.
      '<table>'.
      '<tr>'.
      '<td><input type="text" name="text" size="13" /></td>'.
      '</tr>'.
      '<tr>'.
      '<th><input type="submit" value="'.T('Do search').'" /></th>'.
      '</tr>'.
      '</table></div>'.
      '</form>';
    return $Output;
  }
}

class PageSearch extends Page
{
  function Show(): string
  {
    $this->Title = T('Search');
    if (array_key_exists('text', $_GET)) $Search = $_GET['text'];
    else if (array_key_exists('text', $_POST)) $Search = $_POST['text'];
    else $Search = '';
    $SearchHTML = urlencode($Search);

    $Output = '<table class="BaseTable"><tr><th>'.T('Section').'</th><th>'.T('Found count').'</th></tr>';
    foreach ($this->System->ModuleManager->Modules['Search']->SearchItems as $SearchItem)
    {
      $ColumnQuery = array();
      foreach ($SearchItem['Columns'] as $Column)
      {
        $ColumnQuery[] = '(`'.$Column.'` LIKE "%'.$Search.'%")';
      }
      $ColumnQuery = implode(' OR ', $ColumnQuery);
      if ($SearchItem['Query'] != '')
      {
        $DbResult = $this->Database->query('SELECT COUNT(*) FROM '.$SearchItem['Query'].' WHERE '.$ColumnQuery);
        $Line = $DbResult->fetch_row();
        $Line = $Line[0];
      } else $Line = '';
      if ($Line <> 0)
        $Output .= '<tr><td><a href="'.$SearchItem['Link'].$SearchHTML.'">'.$SearchItem['Name'].'</a></td><td>'.$Line.'</td></tr>';
    }

    $Output .= '</table>';
    return $Output;
  }
}
