<?php

class mfWkhtmltopdf {
  private $html;
  private $log;
  
  public function __construct($html) {
    $this->html = $html;
    $this->log = mfLogHandler::singleton();
  }
  
  
  public function precheck() {
    // TODO: engine precheck before any tickets are being generated!
    
    if(!defined("WKHTMLTOPDF_BIN")) {
      $this->log->warn("WKHTMLTOPDF_BIN not defined!");
    }
    
    $wkbin = WKHTMLTOPDF_BIN;
    if(!file_exists($wkbin)) {
      $this->log->error("wkhtmltopdf binary not found: $wkbin");
      return false;
    }
    
    if(!is_executable($wkbin)) {
      $this->log->error("wkhtmltopdf binary not executable: $wkbin");
      return false;
    }
    
    if(!defined("PDFOUTPUTPATH")) {
      $this->log->error("PDF output path not set!");
      return false;
    }
    
    return true;
  }
  
  public function generate($filename=false,$additionalArgs=false) {
    if(!$this->precheck()) {
      $this->log->error("Precheck failed");
      return false;
    }

    $wkbin = WKHTMLTOPDF_BIN;
    
    if(!$filename) {
      $filename=date('U').".pdf";
    }
    
    $path = PDFOUTPUTPATH;

    $wkargs = WKHTMLTOPDF_ARGS;
    if($additionalArgs) {
      $wkargs.=" $additionalArgs";
    }
    $cmd = "$wkbin $wkargs - $path/$filename";
    
    $html = $this->html;
    $pipe = popen($cmd,"w");
    
    if(!$pipe) {
      $this->log->error("Error opening pipe. cmdline was: $cmd");
      return false;
    }
    
    while($html) {
      $len = fwrite($pipe,$html);
      
      if($len) {
        $html = substr($html,$len);
      }
    }
    
    $retval = pclose($pipe);
    
    if($retval != 0) {
      $this->log->error("wkhtmltopdf exited with return code $retval. cmdline was: $cmd");
      return false;
    }
    
    
    return $filename;
  }
}