<?php

class ModuleEvent extends Module
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Name = 'Event';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'List of dance events';
    $this->Dependencies = array();
    $this->RSSChannels = array();
  }

  function Start(): void
  {
    $this->System->RegisterPage(['udalosti'], 'PageEventList');
    $this->System->RegisterPage(['udalosti', 'udalost'], 'PageEventItem');
    $this->System->RegisterPage(['udalosti', 'aktualizace'], 'PageEventUpdate');
    $this->System->RegisterPage(['udalosti', 'rss'], 'PageEventRss');
    Core::Cast($this->System)->RegisterMenuItem('/udalosti', 'Události');
  }
}

class PageEventList extends Page
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Title = 'Události';
    $this->Description = 'Taneční události';
  }

  function Show(): string
  {
    $Filter = new Filter();
    $Filter->Items = array(
      array('Name' => 'past', 'Type' => 'Boolean', 'DbName' => '', 'Title' => 'Proběhlé'),
      array('Name' => 'title', 'Type' => 'String', 'DbName' => 'Title', 'Title' => 'Titulek'),
      array('Name' => 'description', 'Type' => 'String', 'DbName' => 'Description', 'Title' => 'Popis'),
      array('Name' => 'price', 'Type' => 'Integer', 'DbName' => 'Price', 'Title' => 'Cena'),
      array('Name' => 'location', 'Type' => 'String', 'DbName' => 'Location', 'Title' => 'Umístění'),
      array('Name' => 'source', 'Type' => 'String', 'DbName' => 'SourceName', 'Title' => 'Import'),
    );

    $Output = '';
    if (array_key_exists('lvm', $_GET) and ($_GET['lvm'] == 'seznam'))
      $this->RawPage = true;
      else $Output .= '<div class="title">Události</div>';

    $Output .= $Filter->GetOutput($this->System->Link('/udalosti/'));
    $Where = $Filter->GetWhere($this->Database);
    if ($_SESSION['past'] != 1) $Where .= ' AND (TimeFrom > NOW())';

    $DbResult = $this->Database->query('SELECT COUNT(*) FROM (SELECT *, '.
      '(SELECT EventSource.Name FROM EventSource WHERE EventSource.Id = Event.Source) AS SourceName FROM `Event`) AS T WHERE '.GetDefaultEventFilter('T').' AND '.$Where);
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList($DbRow[0]);

    $Output .= '<div id="list_content">';
    $Output .= $PageList['Output'];
    $TableColumns = array(
      array('Name' => 'TimeFrom', 'Title' => 'Začátek'),
      array('Name' => 'TimeTo', 'Title' => 'Konec'),
      array('Name' => 'Title', 'Title' => 'Titulek'),
      array('Name' => 'Description', 'Title' => 'Popis'),
      array('Name' => 'Price', 'Title' => 'Cena'),
      array('Name' => 'Location', 'Title' => 'Umístění'),
      array('Name' => 'Source', 'Title' => 'Import'),
      array('Name' => '', 'Title' => 'Detail'),
    );
    $Order = GetOrderTableHeader($TableColumns, 'TimeFrom', 0);
    $Output .= '<table class="WideTable">';
    $Output .= $Order['Output'];
    $DbResult = $this->Database->query('SELECT * FROM (SELECT *, (SELECT EventSource.Name FROM EventSource WHERE EventSource.Id = Event.Source) AS SourceName, '.
      '(SELECT EventSource.URL FROM EventSource WHERE EventSource.Id = Event.Source) AS SourceURL FROM Event) AS T WHERE '.GetDefaultEventFilter('T').' AND '.
      $Where.$Order['SQL'].$PageList['SQLLimit']);
    while ($Event = $DbResult->fetch_assoc())
    {
      $Output .= '<tr>'.
        '<td>'.HumanDate(MysqlDateToTime($Event['TimeFrom'])).'</td>'.
        '<td>'.HumanDate(MysqlDateToTime($Event['TimeTo'])).'</td>'.
        '<td>'.$Event['Title'].'</td>'.
        '<td>'.$Event['Description'].'</td>'.
        '<td>'.$Event['Price'].'</td>'.
        '<td>'.$Event['Location'].'</td>'.
        '<td><a href="'.$Event['SourceURL'].'">'.$Event['SourceName'].'</a></td>'.
        '<td><a href="'.$this->System->Link('/udalosti/udalost/'.$Event['Id']).'">Ukázat</a></td>';
      $Output .= '</tr>';
    }
    $Output .= '</table>';
    $Output .= $PageList['Output'];
    $Output .= '</div>';
    if (array_key_exists('lvm', $_GET) and ($_GET['lvm'] == 'seznam'))
    {
    }
    else
    {
      $Output .= '<div><a href="'.$this->System->Link('/udalosti/rss/').'"><img src="'.$this->System->Link('/images/rss20.png').'" alt="rss20"/></a></div>';
    }
    return $Output;
  }
}

class PageEventUpdate extends Page
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Title = 'Aktualizace událostí';
    $this->Description = 'Aktualizace tanečních událostí';
  }

  function Show(): string
  {
    $EventSources = new EventSources();
    $EventSources->Database = $this->Database;
    if (array_key_exists('i', $_GET)) $Output = $EventSources->Parse($_GET['i']);
      else $Output = $EventSources->Parse();
    return $Output;
  }
}

class PageEventItem extends Page
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Title = 'Událost';
    $this->Description = 'Taneční událost';
  }

  function Show(): string
  {
    $Output = '';
    if (count($this->System->PathItems) > 2)
    {
      $id = $this->System->PathItems[2] * 1;
    } else return 'Položka nenalezena';
    if (Core::Cast($this->System)->IsAdmin())
    {
      if (array_key_exists('hide', $_GET)) $this->Database->update('Event', 'Id='.$id, array('Hidden' => 1));
      if (array_key_exists('unhide', $_GET)) $this->Database->update('Event', 'Id='.$id, array('Hidden' => 0));
    }

    $Output .= '<div class="title">Události</div>';
    $DbResult = $this->Database->select('Event', '*, (SELECT EventSource.Name FROM EventSource WHERE EventSource.Id = Event.Source) AS SourceName, '.
      '(SELECT EventSource.URL FROM EventSource WHERE EventSource.Id = Event.Source) AS SourceURL, '.GetDefaultEventFilter().' AS Filter', 'Id='.$id);
    if ($DbResult->num_rows > 0)
    {
      $Event = $DbResult->fetch_assoc();
      if (($Event['Filter'] == '0') and !Core::Cast($this->System)->IsAdmin())
        return 'Položka nenalezena';
      if ($Event['Link'] != '') $Link = '<a href="'.$Event['Link'].'">Odkaz</a>';
        else $Link = '';
      $Output .= '<table class="ItemTable">'.
        '<tr><th>Začátek</th><td>'.HumanDate(MysqlDateToTime($Event['TimeFrom'])).'</td></tr>'.
        '<tr><th>Konec</th><td>'.HumanDate(MysqlDateToTime($Event['TimeTo'])).'</td></tr>'.
        '<tr><th>Titulek</th><td>'.$Event['Title'].'</td></tr>'.
        '<tr><th>Popis</th><td>'.$Event['Description'].'</td></tr>'.
        '<tr><th>Cena</th><td>'.$Event['Price'].'</td></tr>'.
        '<tr><th>Umístění</th><td>'.$Event['Location'].'</td></tr>'.
        '<tr><th>Původní stránka</th><td>'.$Link.'</td></tr>'.
        '<tr><th>Zdroj</th><td><a href="'.$Event['SourceURL'].'">'.$Event['SourceName'].'</a></td></tr>';
      $Output .= '</table>';
      if (Core::Cast($this->System)->IsAdmin()) {
        if ($Event['Hidden'] == '1')
          $Output .= '<div>Skrytá položka <a href="?unhide">Zviditelnit</a></div>';
          else $Output .= '<div>Viditelná položka <a href="?hide">Skrýt</a></div>';
      }
    } else $Output .= 'Položka nenalezena';
    return $Output;
  }
}

class PageEventRss extends Page
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Title = 'RSS tanečních událostí';
    $this->Description = 'RSS kanál tanečních událostí';
  }

  function Show(): string
  {
    global $Config;

    $this->RawPage = true;
    $RSS = new RSS();
    $RSS->Title = 'Taneční události';
    $RSS->Description = '';
    $RSS->Link = $this->System->AbsoluteLink('/udalosti/');

    $DbResult = $this->Database->select('Event', '*, (SELECT EventSource.Name FROM EventSource WHERE EventSource.Id = Event.Source) AS SourceName, '.
      '(SELECT EventSource.URL FROM EventSource WHERE EventSource.Id = Event.Source) AS SourceURL', GetDefaultEventFilter().' ORDER BY `TimeFrom` DESC LIMIT 30');
    while ($Event = $DbResult->fetch_assoc())
    {
      $Title = $Event['Title'];
      $Description = $Event['Description']."<br/>\n";
      $Description .= '<br/>Zdroj: <a href="'.$Event['SourceURL'].'">'.$Event['SourceName'].'</a>';
      $Time = MysqlDateTimeToTime($Event['TimeFrom']);
      $TimeImport = MysqlDateTimeToTime($Event['TimeImport']);
      // Append time part of TimeImport time to item time so new items will appear in correct time order even if item doesn't have time part specified
      if (TimeToMysqlTime($Time) == '00:00:00')
      {
        $Time = MysqlDateTimeToTime(TimeToMysqlDate($Time).' '.TimeToMysqlTime($TimeImport));
      }
      $RSS->Items[] = array(
        'Title' => $Title,
        'Description' => $Description,
        'Time' => $Time,
        'Link' => $this->System->AbsoluteLink('/udalosti/udalost/'.$Event['Id'].'/'),
      );
    }

    return $RSS->Generate();
  }
}
