<?php

class PdfForm {
  private $log;
  private $layout;
  private $template;
  private $variables;
  private $fullpath;
  private $returnValues;
  
  public function __construct($template, $variables) {
    $this->log = mfLoghandler::singleton();
    $this->layout = new Layout();
    $this->template = $template;
    $this->variables = $variables;
  }
  
  
  public function render() {
    $this->layout->setTemplate($this->template);
    $this->layout->set("ressourcePathPrefix", BASEDIR."/public/");
    foreach($this->variables as $name => $value) {
      $this->layout->set($name, $value);
    }
    
    $fullpath = $this->layout->renderPDF();
    $this->fullpath = $fullpath;
    $this->returnValues = $this->layout->getReturnedValue();
    
    return $fullpath;
  }
  
  public function download($filename = false) {
    if(!$this->fullpath) {
      $this->render();
    }
    
    $filepath = $this->fullpath;
    
    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 getFullPath() {
    return $this->fullpath;
  }
  
  public function getReturnedValues() {
    return $this->returnValues;
  }
  
}