<?php

  ## Inititalisierungsteil ##
  
  require_once "DB.php";
  require_once "HTML/Template/IT.php";
  require ("../../../weblibs/config.php");

  // Kategorie zunaechst statisch vorgeben (faellt weg, sobald dieses
  // Script eine externe Kategorie darstellt)
  $kategorie = "27";

  // Brachial die deutsche Sprache erzwingen
  setlocale(LC_ALL, "de_DE");
    
  $pear_db = DB::connect($pear_db_dsn, true);
  if (DB::isError($pear_db)) {
    die("Verbindung zur Datenbank nicht moeglich!");
  }

  
  ## Funktionen zur Formatierung von Zeitangaben ##
  
  function terminzeitraum_formatieren($von, $bis) {
    if (strftime("%d.%m", iso2timestamp($von)) != strftime("%d.%m", iso2timestamp($bis))) {
      $termin = strftime("%A, %d.", iso2timestamp($von))."<br>";
      if (strftime("%m", iso2timestamp($von)) == strftime("%m", iso2timestamp($bis))) {
        $termin .= "bis ".strftime("%A, %d.", iso2timestamp($bis));
      } else {
        $termin .= "bis ".strftime("%A, %d.%m.", iso2timestamp($bis));
      }
    } else {
        $termin = strftime("%A, %d.", iso2timestamp($von));
    }
    return $termin;
  }

  function uhrzeit_formatieren($von, $bis) {
    if (substr($von,11,5) != substr($bis,11,5)) {
      $termin = substr($von,11,5);
      if (strftime("%d", iso2timestamp($von)) == strftime("%d", iso2timestamp($bis))) {
        $termin .= " bis ".substr($bis,11,5);
      } else {
        $termin .= " bis ".substr($bis,11,5).strftime(" (%d.%m.)", iso2timestamp($bis));
      }
    } elseif (substr($von,11,5) != "00:00") {
      $termin = substr($von,11,5);
    } else {
       $termin = "";
    }
    return $termin;
  }


  ## Funktion zum Formatieren von Termininformationen ##

  // TODO: Unterstuetzung fuer bildURL fehlt!
    
  function termininfos_formatieren($ueberschrift, $beschreibung, $url, $bildurl, $von, $bis) {
    $termininfos = "<b>";
    if ($ueberschrift != "") {
      $termininfos .= $ueberschrift;
    }
    if (uhrzeit_formatieren($von, $bis) != "") {
      $termininfos .= " (".uhrzeit_formatieren($von, $bis)." Uhr)";
    }
    $termininfos .= "</b><br>";
    $termininfos .= $beschreibung;
    if ($url != "") {
      if (strpos($url, ":") === false) {
        $url = "http://www.cfg-hockenheim.de".$url;
      }
      $termininfos .= " <a href=\"".$url."\">";
      $termininfos .= "<img src=\"images/scnext1.gif\" width=\"14\" height=\"14\" border=\"0\">";
      $termininfos .= "mehr...</a>\n";
    }
    return $termininfos;
  }

    
  ## Funktionen zum Zugriff auf die Datenbank ##
    
  function dbstand_abrufen() {
    global $pear_db, $kategorie;
    $artikel_ist_sichtbar = "(artikel.veroeffentlichung <= now() AND now() < artikel.archivierung AND artikel.aktiv='j')";
    $artikel_hat_kontextfreigabe = "(artikel.id=artikelkontext.artikel_id AND artikelkontext.kategorie_id='$kategorie' AND artikelkontext.freigabe='j')";
    $sql  = "SELECT if(aenderung>erstellung,aenderung,erstellung) as zeitstempel FROM artikel,artikelkontext";
    $sql .= " WHERE $artikel_ist_sichtbar AND $artikel_hat_kontextfreigabe";
    $sql .= " AND aenderung < now() AND erstellung < now()";
    $sql .= " ORDER BY zeitstempel";
    $sql .= " DESC LIMIT 1";
    $result = $pear_db->getOne($sql);
    if ((DB::isError($result)) || (!isset($result))) {
      return "<em>unbekannt</em>";
    } else {
      return(iso2german($result));
    }
  }

  function aktuelles_abrufen() {
    global $pear_db, $kategorie;
    $artikel_ist_sichtbar = "(artikel.veroeffentlichung <= now() AND now() < artikel.archivierung AND artikel.aktiv='j')";
    $artikel_hat_kontextfreigabe = "(artikel.id=artikelkontext.artikel_id AND artikelkontext.kategorie_id='$kategorie' AND artikelkontext.freigabe='j')";
    $sql  = "SELECT termin_von,termin_bis,ueberschrift,beschreibung,URL,bildURL,id FROM artikel,artikelkontext";
    $sql .= " WHERE $artikel_ist_sichtbar AND $artikel_hat_kontextfreigabe";
    $sql .= " AND termin_von > now()";
    $sql .= " GROUP BY id";
    $sql .= " ORDER BY termin_von,termin_bis,ueberschrift,beschreibung";
    $sql .= " DESC LIMIT 1";
    $result = $pear_db->getRow($sql, null, DB_FETCHMODE_ASSOC);
    if ((DB::isError($result)) || (!isset($result))) {
      return false;
    } else {
      return $result;
    }
  }
    
  function termine_abrufen() {
    global $pear_db, $kategorie;
    $artikel_ist_sichtbar = "(artikel.veroeffentlichung <= now() AND now() < artikel.archivierung AND artikel.aktiv='j')";
    $artikel_hat_kontextfreigabe = "(artikel.id=artikelkontext.artikel_id AND artikelkontext.kategorie_id='$kategorie' AND artikelkontext.freigabe='j')";
    $sql  = "SELECT termin_von,termin_bis,ueberschrift,beschreibung,URL,bildURL,id FROM artikel,artikelkontext";
    $sql .= " WHERE $artikel_ist_sichtbar AND $artikel_hat_kontextfreigabe";
    # nur Halbjahr des aktuellen Schuljahres anzeigen...
    if (isset($_REQUEST['halbjahr'])) {
      if ($_REQUEST['halbjahr'] == "1")  $sql .= " AND ( YEAR(termin_bis) >= YEAR(NOW()) ) AND ( MONTH(termin_bis) > 9 OR MONTH(termin_bis) = 1 )";
      if ($_REQUEST['halbjahr'] == "2")  $sql .= " AND ( YEAR(termin_bis) >= YEAR(NOW()) ) AND ( MONTH(termin_bis) >= 2 AND MONTH(termin_bis) <= 8 )";
    # ...oder nur künftige Termine
    } else {
      $sql .= " AND ( YEAR(termin_bis) = YEAR(NOW()) AND MONTH(termin_bis) >= MONTH(NOW()) OR ( YEAR(termin_bis) > YEAR(NOW()) ) )";
    }
    $sql .= " GROUP BY id";
    $sql .= " ORDER BY termin_von,termin_bis,ueberschrift,beschreibung";
    $result = $pear_db->getAll($sql, null, DB_FETCHMODE_ASSOC);
    if (DB::isError($result)) {
      echo $result->getMessage();
      return false;
    }
    $termine = array();
    foreach ($result as $row) {
      $monat = substr($row['termin_von'], 0, 7);
      if (!array_key_exists($monat, $termine)) {
        $termine[$monat] = array();
      }
      array_push($termine[$monat], $row);
    }
    return $termine;
  }


  ## Hauptprogramm ##
  
  // Template-Objekt initialisieren
  $tpl = new HTML_Template_IT();
  $tpl->loadTemplatefile("termine.tpl.html", true, true);

  // Aktuelles
  $termin = aktuelles_abrufen();
  if ($termin !== false) {
    $termin_zeit = terminzeitraum_formatieren($termin['termin_von'], $termin['termin_bis']);
    $termin_info = termininfos_formatieren('', $termin['beschreibung'], $termin['URL'], $termin['bildURL'], $termin['termin_von'], $termin['termin_bis']);
    $tpl->setCurrentBlock("aktuell_termin");
    $tpl->setVariable("TERMIN_ZEIT", $termin_zeit);
    $tpl->setVariable("TERMIN_INFO", $termin_info);
    $tpl->parseCurrentBlock();
    $monatsname = get_mname(substr($termin['termin_von'], 5, 2))."&nbsp;".substr($termin['termin_von'], 0, 4);
    $tpl->setCurrentBlock("aktuell");
    $tpl->setVariable("AKTUELL_MONAT", $monatsname);
    $tpl->setVariable("AKTUELL_TITEL", $termin['ueberschrift']);
    $tpl->parseCurrentBlock();
  }

  // Termine
  $termine = termine_abrufen();
  if ($termine === false) {
    die("Fehler: Keine anzuzeigenden Termine gefunden!");
  }
  foreach ($termine as $monatsbezeichnung => $monatstermine) {
    foreach ($monatstermine as $termin) {
      $termin_zeit = terminzeitraum_formatieren($termin['termin_von'], $termin['termin_bis']);
      $termin_info = termininfos_formatieren($termin['ueberschrift'], $termin['beschreibung'], $termin['URL'], $termin['bildURL'], $termin['termin_von'], $termin['termin_bis']);
      $tpl->setCurrentBlock("monat_termin");
      $tpl->setVariable("TERMIN_ZEIT", $termin_zeit);
      $tpl->setVariable("TERMIN_INFO", $termin_info);
      $tpl->parseCurrentBlock("monat_termin");
    }
    $monatsname = get_mname(substr($monatsbezeichnung, 5, 2))."&nbsp;".substr($monatsbezeichnung, 0, 4);
    $tpl->setCurrentBlock("monat");
    $tpl->setVariable("TERMIN_MONAT", $monatsname);
    $tpl->parseCurrentBlock("monat");
  }

  // Template fertig parsen und Dokument darstellen
  $tpl->setCurrentBlock("dokument");
  $tpl->setVariable("AKTUELLE_ZEIT", strftime("%e. %B %Y"));
  $tpl->setVariable("STAND", dbstand_abrufen());  
  $tpl->show();
  
?>
