<?php

class ModuleAdmin extends Module
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Name = 'Admin';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Admin interface';
    $this->Dependencies = array();
  }

  function DoStart(): void
  {
    $this->System->RegisterPage(['admin'], 'PageAdmin');
  }
}

class PageAdmin extends Page
{
  function __construct(System $System)
  {
    parent::__construct($System);
  }

  function Show(): string
  {
    if (array_key_exists('Operation', $_GET)) $Operation = $_GET['Operation']; else $Operation = '';
    switch ($Operation)
    {
      case 'Add':
        $Output = $this->ShowAdd();
        break;
      case 'Delete':
        $Output = $this->ShowDelete();
        break;
      case 'Edit':
        $Output = $this->ShowEdit();
        break;
      case 'RebuildCache':
        $Output = $this->ShowRebuildCache();
        break;
      default:
        $Output = $this->ShowNone();
    }
    return $Output;
  }

  function ShowNone(): string
  {
    $Table = array(
      'Header' => array('Název veličiny', 'Operace'),
      'Rows' => array(),
    );

    $Result = $this->Database->select('Measure', '*', '1 ORDER BY Description');
    while ($Measure = $Result->fetch_array())
    {
      array_push($Table['Rows'], array($Measure['Description'], MakeLink('?Operation=Edit&amp;MeasureId='.$Measure['Id'], 'Editovat').' '.MakeLink('?Operation=Delete&amp;MeasureId='.$Measure['Id'], 'Odstranit').' '.MakeLink('?Operation=RebuildCache&amp;MeasureId='.$Measure['Id'], 'Přestavět cache')));
    }
    $Output = '<h3>Seznam měření</h3>'.Table($Table).MakeLink('?Operation=Add', 'Přidat');
    return $Output;
  }

  function ShowEdit(): string
  {
    $DbResult = $this->Database->select('Measure', '*', 'Id='.addslashes($_GET['MeasureId']));
    $Values = array();
    $Values = $DbResult->fetch_array();
    return ShowEditTable('Measure', $Values);
  }

  function ShowAdd(): string
  {
    $Values = array();
    return ShowEditTable('Measure', $Values);
  }

  function ShowDelete(): string
  {
    return '';
  }

  function ShowRebuildCache(): string
  {
    echo("Vytvařím novou cache...<br>");
    $DbResult = $this->Database->select('Measure', '*', 'Id='.addslashes($_GET['MeasureId']));
    $Measure = $DbResult->fetch_array();

    $Measure->RebuildMeasureCache();
    echo('Dokončeno<br>');
    return '';
  }
}
