<?php
 
require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');

class modDailyJournal  {
  private $baseDir;
  private $clouds;
  private $atmosphere;
  private $precip;
  private $journal;
  private $lw_id;
  private $start_time;
  private $hour_list;
  private $min_list;
  
  public function __construct($lw_id) {
    $dal = new DAL();
    if (isset($lw_id))
      $this->lw_id = $lw_id;
    else  
      $this->lw_id = 0;

    $sql = "SELECT WE.id as id,  start_time, CL.name AS cloud, AT.descr AS atmosphere, " .
           "temperature, humidity, LI.descr AS lighting, PR.descr AS precipitation " .
           "FROM weather WE, cloudcover CL, atmosphere AT, precipitation PR, lighting LI " .
           "WHERE WE.loginworkday_id = $this->lw_id AND WE.active = 1 " .
           "AND WE.cloudcover_id = CL.id AND WE.atmosphere_id = AT.id " . 
           "AND WE.precipitation_id = PR.id AND LI.id = WE.lighting_id " .
           "ORDER BY WE.start_time DESC ";
    $this->journal = $dal->query($sql);

    if (count ($this->journal) == 0) {
      $default = array('1' => array("id"=>0, "start_time"=>"", "cloud"=>"", "atmosphere"=>"", 
                       "temperature"=>"", "humidity"=>"", "lighting"=>"", "precipitation"=>"" ));
      $this->journal = $this->toObject ($default);
    }

    $sql = "SELECT id, name AS descr FROM cloudcover WHERE active = 1 ";
    $this->clouds = $dal->query($sql);

    $sql = "SELECT id, descr FROM atmosphere WHERE active = 1 ";
    $this->atmosphere = $dal->query($sql);

    $sql = "SELECT id, descr FROM precipitation WHERE active = 1 ";
    $this->precip = $dal->query($sql);

    $sql = "SELECT id, descr FROM lighting WHERE active = 1 ";
    $this->lighting = $dal->query($sql);

    $this->selJournal = 0;
    $this->baseDir = basename(__DIR__); 

    $hours = date("H");
    $minutes = date("i");
    $m = ((($minutes + 7.5)/15 | 0) * 15) % 60;
    $h = (((($minutes/105) + .5) | 0) + $hours) % 24;
    $now = sprintf("%02d", $h) . ':' . sprintf("%02d", $m);

    $this->hour_range = "00,24";
    $this->min_list  = "00,15,30,45";
    
    $default = array("id"=>0, "start_time"=>$now, "cloud"=>"0", "atmosphere"=>"0",
                     "temperature"=>"", "humidity"=>"", "lighting"=>"0", "precipitation"=>"0");
    $this->form_defs = $this->toObject ($default);

  }
  
  public function get($prop) {
    return $this->$prop;
  }
  
  private function toObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $value = $this->toObject($value);
      }
      $object->$key = $value;
    }
    return $object;
  }
 
  
}

?>