<?php

class PageEatingPlace extends Page
{
  public array $DayNames = array('Neděle', 'Pondělí', 'Úterý', 'Středa', 'Čtvrtek', 'Pátek', 'Sobota');
  public array $DayNamesShort = array('NE', 'PO', 'ÚT', 'ST', 'ČT', 'PÁ', 'SO');
  public array $Status = array('Nezveřejněno', 'Otevřeno', 'Zavřeno - svátek', 'Zavřeno - dovolená');
  public int $DayCount = 20;    // počet dopředu zobrazených dnů

  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Title = 'Jídelníček';
    $this->Description = 'Jídleníček jídelny Na kopečku';
    $this->ParentClass = 'PagePortal';
  }

  function Show(): string
  {
    if (count($this->System->PathItems) > 1)
    {
      if ($this->System->PathItems[1] == 'tisk') return $this->ShowPrint();
        else if ($this->System->PathItems[1] == 'menuedit.php') return $this->ShowEdit();
        else return PAGE_NOT_FOUND;
    } else return $this->ShowMenu();
  }

  function ShowMenu(): string
  {
    $Output = '<table align="center" class="WideTable"><tr><th>Den</th><th>Datum</th><th>Polévka</th><th>Hlavní jídlo</th></tr>';
    $DbResult = $this->Database->select('Meals', '*, UNIX_TIMESTAMP(Date)','Date >= NOW() ORDER BY Date');
    while ($Row = $DbResult->fetch_array())
    {
      if ($Row['Status'] == 1) $Output .= '<tr><td>'.$this->DayNames[date('w', $Row['UNIX_TIMESTAMP(Date)'])].'</td><td align="right">'.HumanDate($Row['Date']).'</td><td>'.$Row['Soup'].'</td><td>'.$Row['Meal'].'</td></tr>';
      else if (($Row['Status' ] == 2) or ($Row['Status'] == 3))
      {
        $Output .= '<tr><td>'.$this->DayNames[date('w', $Row['UNIX_TIMESTAMP(Date)'])].'</td><td align="right">'.HumanDate($Row['Date']).'</td><td colspan="2" align="center">'.$this->Status[$Row['Status']].'</td></tr>';
      }
    }
    $Output .= '</table><br />';

    $DbResult = $this->Database->select('MealsInfo', '*');
    $Row =  $DbResult->fetch_array();
    $Output .= 'Cena jednoho menu: '.$Row['Price'].' Kč<br />';
    $Output .= $Row['Info'];
    return $Output;
  }

  function ShowPrint(): string
  {
    $this->RawPage = true;

    $Output = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset='.$this->System->Config['Web']['Charset'].'">
<meta http-equiv="Content-language" content="cs">
<title>Tisk jídelníčku</title>
</head><body style="margin: 0px 0px 0px 0px;">'; // onload="print()">');

    $Output .= '<table height="99%" width="100%" align="center" border="0" cellspacing="0" cellpadding="3">';
    $Date = explode('-', $_GET['date']);
    $Output .= '<tr><td style="border-bottom-style: solid; border-bottom-color: black; border-bottom-width: 2;" colspan="2">
<table cellspacing="0" cellpadding="0" width="100%"><tr><td width="50%"><strong>DATUM:</strong> '.HumanDate($_GET['date']).' - '.HumanDate(date('Y-m-d',mktime(0, 0, 0, $Date[1], $Date[2], $Date[0]) + 4 * 86400)).'</td>
<td align="right">CENY SMLUVNÍ</td></tr></table>
<div align="center" style="font-size: xx-large;">&bdquo;JÍDELNA NA KOPEČKU&rdquo;</div>
<div align="center" style="font-size: x-large;">JÍDELNÍČEK</div>
</td></tr>';
    $Date = explode('-', $_GET['date']);
    $Time2 = mktime(0, 0, 0, $Date[1], $Date[2], $Date[0]);
    for ($I = 0; $I < 5; $I++)
    {
      $Time = $Time2 + $I * 86400;
      $Date = date('Y-m-d', $Time);
      $DayOfWeek = date('w', $Time);
      $DbResult = $this->Database->select('Meals', '*', 'Date="'.$Date.'"');
      $Row = $DbResult->fetch_array();
      $Output .= '<tr><td style="border-style: solid; border-color: black; border-width: 2; font-size: xx-large;" width="10%">'.$this->DayNamesShort[$DayOfWeek].'</td><td style="font-size: x-large; border-style: solid; border-color: black; border-width: 2;" width="90%">';
      if ($Row['Status'] == 0) $Output .= '&nbsp;<br><br>&nbsp;';
      if ($Row['Status'] == 1) $Output .= 'Polévka: '.$Row['Soup'].'<br><br>'.$Row['Meal'];
      else if (($Row['Status'] == 2) or ($Row['Status'] == 3))
      {
        $Output .= '<br>'.$this->Status[$Row['Status']].'<br>&nbsp;';
      }
      $Output .= '</td></tr>';
    }
    $DbResult = $this->Database->select('MealsInfo','*');
    $Row = $DbResult->fetch_array();
    $Output .= '<tr><td style="border-top-style: solid; border-top-color: black; border-top-width: 2;" colspan="2"><table cellspacing="0" cellpadding="0" width="100%"><tr><td width="50%"><strong>JÍDLA PŘIPRAVILA: Matochová</strong></td>
    <td align="right"><strong>PROVOZOVATEL:</strong></td></tr></table>
    <br>
    <strong>CENA JEDNOHO MENU JE '.$Row['Price'].' Kč</strong></td></tr>';
    $Output .= '</table>';

    $Output .= '</body></html>';
    return $Output;
  }

  function PrintTableRow(array $Row): string
  {
    global $LastWeekOfYear;

    $Selected = array('', '', '', '');
    $Selected[$Row['Status']] = 'selected ';
    $Date = explode('-', $Row['Date']);
    $Week = date('w', mktime(0, 0, 0, $Date[1], $Date[2], $Date[0]));
    $WeekOfYear = date('W', mktime(0, 0, 0, $Date[1], $Date[2], $Date[0]));
    if ($WeekOfYear != $LastWeekOfYear)
      $WeekRowSpan = '<td align="center" rowspan="'.(7 - (($Week + 7 - 1) % 7)).'">'.
        $WeekOfYear.'<br /><a href="tisk/?date='.
        date('Y-m-d', mktime(0, 0, 0, $Date[1], $Date[2], $Date[0]) - ($Week - 1) * 86400).
        '">Tisk</a></td>';
      else $WeekRowSpan = '';
    if ($Week == 0) $Color = ' style="color: #ff0000;" '; else $Color = '';
    $Output = '<tr><td'.$Color.'>'.$this->DayNames[$Week].'</td><td>'.HumanDate($Row['Date']).'</td>'.$WeekRowSpan.'
    <td><input name="soup_'.$Row['Date'].'" size="30" value="'.$Row['Soup'].'"></td>
    <td><input name="meal_'.$Row['Date'].'" size="30" value="'.$Row['Meal'].'"></td>
    <td><select name="status_'.$Row['Date'].'">';
    for ($I = 0; $I < 4; $I++) $Output .= '    <option '.$Selected[$I].'value="'.$I.'">'.$this->Status[$I].'</option>';
    $Output .= '</select></td></tr>';
    $LastWeekOfYear = $WeekOfYear;
    return $Output;
  }

  function ShowEdit(): string
  {
    Header('Cache-Control: no-cache');

    $Output = '';
    if (array_key_exists('action', $_GET))
    {
      if ($_GET['action'] == 'savemenu')
      {
        for ($I = 0; $I < $this->DayCount; $I++)
        {
          $Time = time() + $I * 86400;
          $Date = date('Y-m-d', $Time);
          $this->Database->replace('Meals', array('Date' => $Date, 'Meal' => $_POST['meal_'.$Date], 'Soup' => $_POST['soup_'.$Date], 'Status' => $_POST['status_'.$Date]));
        }
        $Output .= '<div style="color: red; font-size: larger;">Menu uloženo!</div>';
        ModuleLog::Cast($this->System->GetModule('Log'))->NewRecord('EatingPlace', 'MenuSave');
      }
      if ($_GET['action'] == 'saveinfo')
      {
        $this->Database->delete('MealsInfo', '1');
        $this->Database->insert('MealsInfo', array('Info' => $_POST['info'], 'Price' => $_POST['price']));
        $Output .= '<div style="color: red; font-size: larger;">Informační údaje uloženy!</div>';
        ModuleLog::Cast($this->System->GetModule('Log'))->NewRecord('EatingPlace', 'InfoSave');
      }
    }
    $Output = '<form action="?action=savemenu" method="post">
<fieldset><legend>Jídlo pro jednotlivé dny</legend>
<table align="center" class="WideTable"><tr><th>Den</th><th>Datum</th><th>Týden</th><th>Polévka</th><th>Hlavní jídlo</th><th>Stav</th></tr>';
    for ($I = 0; $I < $this->DayCount; $I++)
    {
      $Time = time() + $I * 86400;
      $DbResult = $this->Database->select('Meals', '*', 'Date = "'.date('Y-m-d', $Time).'"');
      if ($Row = $DbResult->fetch_array())
        $Output .= $this->PrintTableRow($Row);
      else
      {
        $Row = array('Status' => 0, 'Meal' => '', 'Soup' => '', 'Date' => date('Y-m-d', $Time));
        $Output .= $this->PrintTableRow($Row);
      }
    }
    $Output .= '</table><br />
<div align="center"><input type="submit" value="Uložit menu"></div>
</fieldset></form>';
    $Output .= '<form action="?action=saveinfo" method="post">
<fieldset><legend>Informační údaje</legend>';

    $DbResult = $this->Database->select('MealsInfo', '*');
    $Row = $DbResult->fetch_array();
    $Output .= '<textarea name="info" rows="20" cols="80" >'.$Row['Info'].'</textarea><br />'.
'Cena: <input type="text" name="price" size="5" value="'.$Row['Price'].'"> Kč<br />'.
'<div align="center"><input type="submit" value="Uložit údaje"></div>
</fieldset></form>';
    return $Output;
  }
}

class ModuleMeals extends Module
{
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Meals';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPLv3';
    $this->Description = 'Module for management meals. Can print week menu.';
    $this->Dependencies = array(ModuleLog::GetName());
    $this->Models = array(Meals::GetClassName(), MealsInfo::GetClassName());
  }

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

class Meals extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddDate('Date');
    $Desc->AddString('Soup');
    $Desc->AddString('Meal');
    $Desc->AddInteger('Status');
    return $Desc;
  }
}

class MealsInfo extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddText('Info');
    $Desc->AddInteger('Price');
    return $Desc;
  }
}
