<?php

class mfLayout {

  private $log;
  private $tvars = array();
  private $template = "cli";
  private $package = "default";
  private $inline;
  private $returnValue;
  protected static $instance;

  public function __construct() {
    $this->log = mfLoghandler::singleton();
    $this->inline = new stdClass();

    if (!defined("LAYOUT_DEFAULTPACKAGE")) {
      $this->package = "default";
    } else {
      $this->package = LAYOUT_DEFAULTPACKAGE;
    }

    if (method_exists($this, "init")) {
      $this->init();
    }
  }

  public static function singleton($param = false) {
    if (!isset(self::$instance)) {
      $c = __CLASS__;
      self::$instance = new $c($param);
    }
    return self::$instance;
  }

  public function set($name, $value) {
    $this->tvars[$name] = $value;
  }

  public function setPackage($package) {
    $this->package = $package;
  }

  public function setTemplate($template) {
    $this->template = $template;
  }

  private function setReturnValue($value) {
    $this->returnValue = $value;
  }

  public function getReturnedValue() {
    return $this->returnValue;
  }

  public function render() {
    $this->defaultLayoutvariables();

    foreach ($this->tvars as $name => $value) {
      if ($name === "this")
        continue;
      $$name = $value;
    }

    ob_end_clean();
    ob_start();
    include(VIEWDIR . "/" . $this->package . "/" . $this->template . ".php");
    return ob_get_clean();
  }

  public function display() {
    echo $this->render();
  }

  public function renderPDF($filename = false, $extraPdfArgs = false) {
    $html = $this->render();

    if (!$filename)
      $filename = date('U') . "-" . rand(1000, 9999) . ".pdf";

    $wk = new mfWkhtmltopdf($html);

    $pdfargs = "";
    if ($extraPdfArgs) {
      $pdfargs .= " $extraPdfArgs";
    }

    $filename = $wk->generate($filename, $pdfargs);

    if (!$filename) {
      throw new Exception("Error generating PDF document.");
    }

    $file = PDFOUTPUTPATH . "/$filename";

    return $file;
  }

  public function displayPDF($filename = false, $extraPdfArgs = false) {
    $filepath = $this->renderPDF($filename, $extraPdfArgs);

    if (!$filename && strpos($filepath, "/") !== false) {
      $path_parts = explode("/", $filepath);
      $filename = end($path_parts);
    }

    header('Content-Type: application/octet-stream');
    header('Content-disposition: attachment; filename=' . $filename);
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Type: ' . mime_content_type($filepath));
    header("Content-Length: " . filesize($filepath));
    
    readfile($filepath);
    exit;
  }

  public function setFlash($msg, $type = "info") {
    // info, warning, error
    if (!$msg) {
      return true;
    }

    if ($type == "error") {
      $_SESSION[MFAPPNAME . '_mfError'] = $msg;
    } elseif ($type == "warning" || $type == "warn") {
      $_SESSION[MFAPPNAME . '_mfWarning'] = $msg;
    } elseif ($type == "success") {
      $_SESSION[MFAPPNAME . '_mfSuccess'] = $msg;
    } else {
      $_SESSION[MFAPPNAME . '_mfInfo'] = $msg;
    }

    return true;
  }

  private function defaultLayoutvariables() {
    $this->set('mfLayoutPackage', $this->package);

    if (isset($_SESSION[MFAPPNAME . '_mfError'])) {
      $this->set("mfError", $_SESSION[MFAPPNAME . '_mfError']);
      $this->set("_flash_set", true);
      unset($_SESSION[MFAPPNAME . '_mfError']);
    }
    if (isset($_SESSION[MFAPPNAME . '_mfWarning'])) {
      $this->set("mfWarning", $_SESSION[MFAPPNAME . '_mfWarning']);
      $this->set("_flash_set", true);
      unset($_SESSION[MFAPPNAME . '_mfWarning']);
    }
    if (isset($_SESSION[MFAPPNAME . '_mfInfo'])) {
      $this->set("mfInfo", $_SESSION[MFAPPNAME . '_mfInfo']);
      $this->set("_flash_set", true);
      unset($_SESSION[MFAPPNAME . '_mfInfo']);
    }
    if (isset($_SESSION[MFAPPNAME . '_mfSuccess'])) {
      $this->set("mfSuccess", $_SESSION[MFAPPNAME . '_mfSuccess']);
      $this->set("_flash_set", true);
      unset($_SESSION[MFAPPNAME . '_mfSuccess']);
    }
  }

  /*
   * Begin inline functions
   */

  public static function strtrim($string, $chars) {
    if (strlen($string) <= $chars)
      return $string;
    return substr($string, 0, $chars) . "...";
  }

  // produces url for generating links
  public static function getUrl($mod, $action = null, $param = null) {
    if (!$mod) {
      return "";
    }


    if (MFUSEFANCYURLS) {
      // use fancy urls
      $url = MFFANCYBASEURL;
      if ($mod) {
        $url .= "/$mod";
        if ($action) {
          $url .= "/$action";
        }
      }
      $url = preg_replace('#//#', '/', $url);
    } else {
      // no fancy urls
      $url = "?action=$mod";
      if ($action) {
        $url .= "_$action";
      }
    }
    if (is_array($param) && count($param)) {
      $url .= (MFUSEFANCYURLS) ? "/" : "&amp;";
      $param_qs = http_build_query($param);
      $url .= "$param_qs";
    }

    return $url;
  }

  public static function getResourcePath() {
    if (MFUSEFANCYURLS) {
      $path = MFFANCYBASEURL;
      if (substr($path, -1, 1) != "/") {
        $path .= "/";
      }
    } else {
      $path = "";
    }
    return $path;
  }

  public function cycle() {
    $args = func_get_args();

    if (is_array($this->inline->cycle) && count($this->inline->cycle)) {
      if (array_diff($this->inline->cycle, $args)) { // if different, start new cycle
        $this->inline->cycle = $args;
        $this->inline->cyclecount = 0;
      }
    } else {
      $this->inline->cycle = $args;
      $this->inline->cyclecount = 0;
    }

    if ($this->inline->cyclecount >= count($this->inline->cycle)) {
      $this->inline->cyclecount = 0;
    }

    return $this->inline->cycle[$this->inline->cyclecount++];
  }

}

function __($string) {
  $lang = [];
  include(BASEDIR . "/lang/de.php");
  if (array_key_exists($string, $lang['de'])) {
    return $lang['de'][$string];
  }
  return $string;
}
