<?php

include_once(dirname(__FILE__).'/../../Common/Global.php');

class PageSubjectOpenTime extends Page
{
  var $FullTitle = 'Otvírací doby místních subjektů';
  var $ShortTitle = 'Otvírací doby';
  var $DaysOfWeek = array('Pondělí', 'Úterý', 'Středa', 'Čtvrtek', 'Pátek', 'Sobota', 'Neděle');
  var $EventType = array('Žádný', 'Otevřeno', 'Zavřeno');
  var $ParentClass = 'PagePortal';

  function ToHumanTime($Time)
  {
    $Hours = floor($Time / 60);
    $Minutes = $Time - $Hours * 60;
    if ($Minutes < 10) $Minutes = '0'.$Minutes;
    $Hours = $Hours % 24;
    return $Hours.':'.$Minutes;
  }

  function ToHumanTime2($Time)
  {
    $Days = floor($Time / 24 / 60);
    $Time = $Time - $Days * 24 * 60;
    $Hours = floor($Time / 60);
    $Time = $Time - $Hours * 60;
    $Minutes = $Time;
    $Output = '';
    if ($Days > 0) $Output .= $Days.' dnů, ';
    if ($Hours > 0) $Output .= $Hours.' hodin, ';
    if ($Minutes > 0) $Output .= $Minutes.' minut';
    return $Output;
  }

  function EditSubject($Id)
  {
    if ($this->System->User->CheckPermission('OpeningHours', 'Edit'))
    {
      $Output = '<div class="Centred">';
      $DbResult = $this->Database->select('Subject', 'Name', 'Id='.$Id);
      $DbRow = $DbResult->fetch_assoc();
      $Output .= '<form method="post" action="save?Subject='.$Id.'" enctype="multipart/form-data">'.
      '<strong>'.$DbRow['Name'].'</strong>'.
      '<table class="WideTable"><tr><th>Den</th><th>Od</th><th>Do</th><th>Od</th><th>Do</th></tr>';
      $Day = array();
      $DbResult = $this->Database->query('SELECT * FROM SubjectOpenTimeDay WHERE Subject = '.$Id);
      while ($DbRow = $DbResult->fetch_assoc())
        $Day[$DbRow['Day']] = $DbRow;
      foreach ($this->DaysOfWeek as $Index => $Name)
      {
        if (!array_key_exists($Index, $Day)) $Day[$Index] = array('Open1' => 0, 'Close1' => 0, 'Open2' => 0, 'Close2' => 0);
        $Output .= '<tr><td>'.$Name.'</td>'.
          '<td><input type="text" name="day'.$Index.'_open1_h" value="'.floor($Day[$Index]['Open1'] / 60).'" size="2" />'.
          ':<input type="text" name="day'.$Index.'_open1_m" value="'.($Day[$Index]['Open1'] - floor($Day[$Index]['Open1'] / 60) * 60).'" size="2" /></td>'.
          '<td><input type="text" name="day'.$Index.'_close1_h" value="'.floor($Day[$Index]['Close1'] / 60).'" size="2" />'.
          ':<input type="text" name="day'.$Index.'_close1_m" value="'.($Day[$Index]['Close1'] - floor($Day[$Index]['Close1'] / 60) * 60).'" size="2" /></td>'.
          '<td><input type="text" name="day'.$Index.'_open2_h" value="'.floor($Day[$Index]['Open2'] / 60).'" size="2" />'.
          ':<input type="text" name="day'.$Index.'_open2_m" value="'.($Day[$Index]['Open2'] - floor($Day[$Index]['Open2'] / 60) * 60).'" size="2" /></td>'.
          '<td><input type="text" name="day'.$Index.'_close2_h" value="'.floor($Day[$Index]['Close2'] / 60).'" size="2" />'.
          ':<input type="text" name="day'.$Index.'_close2_m" value="'.($Day[$Index]['Close2'] - floor($Day[$Index]['Close2'] / 60) * 60).'" size="2" /></td>'.
          '</tr>';
      }
      $DbResult = $this->Database->select('SubjectOpenTime', 'Notice', 'Subject='.$Id);
      $DbRow = $DbResult->fetch_assoc();
      $Output .= '</table>'.
      'Poznámka: <input type="text" name="notice" value="'.$DbRow['Notice'].'" size="50" /><br />'.
      'Fotka: <input type="file" name="photo" size="38" /><br />'.
      '<input type="submit" value="Uložit" />'.
      '</form></div>';
    } else $Output = 'Nemáte oprávnění';
    return $Output;
  }

  function SaveSubject($Id)
  {
    global $Config;

    $Output = '';
    if ($this->System->User->CheckPermission('OpeningHours', 'Edit'))
    {
      $this->Database->delete('SubjectOpenTimeDay', 'Subject='.$Id);
      foreach ($this->DaysOfWeek as $Index => $Name)
      {
        if ($_POST['day'.$Index.'_open1_h'] > 24) $_POST['day'.$Index.'_open1_h'] = 24;
        if ($_POST['day'.$Index.'_close1_h'] > 24) $_POST['day'.$Index.'_close1_h'] = 24;
        if ($_POST['day'.$Index.'_open2_h'] > 24) $_POST['day'.$Index.'_open2_h'] = 24;
        if ($_POST['day'.$Index.'_close2_h'] > 24) $_POST['day'.$Index.'_close2_h'] = 24;
        if ($_POST['day'.$Index.'_open1_m'] > 59) $_POST['day'.$Index.'_open1_m'] = 59;
        if ($_POST['day'.$Index.'_close1_m'] > 59) $_POST['day'.$Index.'_close1_m'] = 59;
        if ($_POST['day'.$Index.'_open2_m'] > 59) $_POST['day'.$Index.'_open2_m'] = 59;
        if ($_POST['day'.$Index.'_close2_m'] > 59) $_POST['day'.$Index.'_close2_m'] = 59;
        $Day = array('Subject' => $Id, 'Day' => $Index);
        $Day['Open1'] = $_POST['day'.$Index.'_open1_m'] + $_POST['day'.$Index.'_open1_h'] * 60;
        $Day['Close1'] = $_POST['day'.$Index.'_close1_m'] + $_POST['day'.$Index.'_close1_h'] * 60;
        $Day['Open2'] = $_POST['day'.$Index.'_open2_m'] + $_POST['day'.$Index.'_open2_h'] * 60;
        $Day['Close2'] = $_POST['day'.$Index.'_close2_m'] + $_POST['day'.$Index.'_close2_h'] * 60;
        $this->Database->insert('SubjectOpenTimeDay', $Day);
      }
      $Output .= 'Uloženo';

      $File = new File($this->Database);

      // Delete old file
      $DbResult = $this->Database->select('SubjectOpenTime', 'Photo', 'Subject='.$Id);
      $DbRow = $DbResult->fetch_assoc();
      $File->Delete($DbRow['Photo']);

      // Create new file
      $FileId = $File->CreateFromUpload('photo');
      $this->Database->update('SubjectOpenTime', 'Subject='.$Id, array('UpdateTime' => 'NOW()', 'Notice' => $_POST['notice'], 'Photo' => $FileId));
    } else $Output = 'Nemáte oprávnění';
    return $Output;
  }

  function ShowAll()
  {
    $Output = '<div class="Centred">';
    $DbResult = $this->Database->query('SELECT SubjectOpenTime.*, DATE_FORMAT(SubjectOpenTime.UpdateTime, "%e.%c.%Y") as UpdateTime, Subject.Id, Subject.Name as Name FROM SubjectOpenTime JOIN Subject ON Subject.Id = SubjectOpenTime.Subject ORDER BY Name');
    while ($Subject = $DbResult->fetch_assoc())
    {
      $Output .= '<strong>'.$Subject['Name'].':</strong><br />';

      // Load time event list
      $Events = array();
      $DbResult2 = $this->Database->query('SELECT * FROM `SubjectOpenTimeDay` WHERE Subject='.$Subject['Subject'].' ORDER BY Day ASC');
      while ($DbRow = $DbResult2->fetch_assoc())
      {
        if (($DbRow['Open1'] != $DbRow['Close1']) and ($DbRow['Open1'] < $DbRow['Close1']))
        {
          $Events[] = array('Time' => $DbRow['Open1'] + $DbRow['Day'] * 24 * 60, 'Type' => 1);
          $Events[] = array('Time' => $DbRow['Close1'] + $DbRow['Day'] * 24 * 60, 'Type' => 2);
        }
        if (($DbRow['Open2'] != $DbRow['Close2']) and ($DbRow['Open2'] < $DbRow['Close2']) and ($DbRow['Close1'] < $DbRow['Open2']))
        {
          $Events[] = array('Time' => $DbRow['Open2'] + $DbRow['Day'] * 24 * 60, 'Type' => 1);
          $Events[] = array('Time' => $DbRow['Close2'] + $DbRow['Day'] * 24 * 60, 'Type' => 2);
        }
      }
      //print_r($Events);

      // Calculate time to next event
      if (count($Events) > 0)
      {
        $CurrentTime = ((date('w') + 6) % 7) * 24 * 60 + date('G') * 60 + date('i');

        $I = 0;
        while (($I < count($Events)) and ($Events[$I]['Time'] < $CurrentTime))
          $I++;
        if ($I < count($Events))
        {
          $NextTime = $Events[$I]['Time'];
          $NextEventType = $Events[$I]['Type'];
        } else
        {
          $NextTime = $Events[0]['Time'] + 7 * 24 * 60;
          $NextEventType = $Events[0]['Type'];
        }

        $TimeDelta = $NextTime - $CurrentTime;
        //$Output .= $CurrentTime.' '.$NextTime;
        if ($NextEventType == 2) $Output .= 'Zavírá za '.$this->ToHumanTime2($TimeDelta);
          else $Output .= 'Otevírá za '.$this->ToHumanTime2($TimeDelta);
      }

      // Show time inteval table
      $Output .= '<table class="WideTable"><tr><th>Den</th><th>Čas</th></tr>';
      foreach ($this->DaysOfWeek as $DayIndex => $DayOfWeek)
      {
        $DbResult2 = $this->Database->query('SELECT * FROM SubjectOpenTimeDay WHERE Subject = '.$Subject['Subject'].' AND Day='.$DayIndex);
        $Output .= '<tr><td>'.$DayOfWeek.'</td><td align="center">';
        if ($DbResult2->num_rows)
        {
          $DbRow = $DbResult2->fetch_assoc();
          if (($DbRow['Open1'] != $DbRow['Close1']) and ($DbRow['Open1'] < $DbRow['Close1']))
          {
            $Output .= $this->ToHumanTime($DbRow['Open1']).' - '.$this->ToHumanTime($DbRow['Close1']).' &nbsp;&nbsp; ';
          }
          if (($DbRow['Open2'] != $DbRow['Close2']) and ($DbRow['Open2'] < $DbRow['Close2']) and ($DbRow['Close1'] < $DbRow['Open2']))
          {
            $Output .= $this->ToHumanTime($DbRow['Open2']).' - '.$this->ToHumanTime($DbRow['Close2']).'';
          }
        } else
          $Output .= '&nbsp;';
        $Output .= '</td></tr>';
      }
      $Output .= '</table>Aktualizováno: '.$Subject['UpdateTime'].'<br />';
      if ($Subject['Notice'] != '') $Output .= 'Poznámka: '.$Subject['Notice'].'<br />';

      if ($Subject['Photo'] != 0) $Output .= '<a href="file?id='.$Subject['Photo'].'">Fotka</a> ';

      if ($this->System->User->CheckPermission('SubjectOpenTime', 'Edit'))
        $Output .= '<a href="edit?Subject='.$Subject['Id'].'">Editovat</a><br />';
      $Output .= '<br />';
    }
    $Output .= '</div>';
    return $Output;
  }

  function Show()
  {
    if (count($this->System->PathItems) > 1)
    {
      if ($this->System->PathItems[1] == 'edit') $Output = $this->EditSubject($_GET['Subject']);
      else if ($this->System->PathItems[1] == 'save')
      {
        $Output = $this->SaveSubject($_GET['Subject']);
        $Output .= $this->ShowAll();
      } else $Output = PAGE_NOT_FOUND;
    } else $Output = $this->ShowAll();
    return $Output;
  }
}

class ModuleOpeningHours extends AppModule
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Name = 'OpeningHours';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Show subject opening hours with time to open or time to close';
    $this->Dependencies = array();
  }

  function DoStart()
  {
    $this->System->Pages['otviraci-doby'] = 'PageSubjectOpenTime';
  }

  function DoInstall()
  {
  }

  function DoUnInstall()
  {
  }
}
