<?php
/*=======================================================================
 *
 * html2pdf_multi.php
 *
 =======================================================================*/


include_once ("../include/mcglobal.inc.php");


$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   include_once ("../include/auth.inc.php");

   $httpVars = array("category", "objId", "cascadingObjType", "pageTitle", "sendToClientInlineDisplay", "sendToClientFileDownload", "fileTargetType", "pdfPageSize", "commNo", "jbService");
   getSecHttpVars("1", $httpVars);

   $autoMode = false;
   $isCron = false;
else :
   $category = ""; $objId = ""; $cascadingObjType = ""; $pageTitle = ""; $fileTargetType = ""; $pdfPageSize = ""; $commNo = ""; $jbService = "";

   $isCron = true;
   if ($argv[1] == "acapella7890") :
       $autoMode = true;
       $category = $argv[2];
       $objId = $argv[3];
       $cascadingObjType = $argv[4];
       $pageTitle = $argv[5];
       $fileTargetType = $argv[6];
       $pdfPageSize = $argv[7];
       $commNo = $argv[8];
       // $jbService = $argv[9];
   endif;
endif;


$pdfPathRelative = "../temp/pdf/";

$jbIsInstallationJob = false;
if (((int)$jbService & 2) == 2) : $jbIsInstallationJob = true; endif;

// Execution-Time for script
set_time_limit(120);

require_once ("../include/WkHtmlToPdf.php");

// "$objId" and "$category" (and additional "$cascadingObjType") have to be defined HERE !!!
include_once ("../include/inc_metafield.inc.php");

if ($pageTitle == "") : $pageTitle = "PDF"; endif;

$debug = false;
if ($debug) :
   echo "\n category         :" . $category;
   echo "\n objId            :" . $objId;
   echo "\n cascadingObjType :" . $cascadingObjType;
   echo "\n pageTitle        :" . $pageTitle;
   echo "\n fileTargetType   :" . $fileTargetType;
   echo "\n pdfPageSize      :" . $pdfPageSize;
   echo "\n commNo           :" . $commNo;
endif;


// Get current template stored in metafieldcategory for output
$currTemplateId = getFieldValueFromId("metafieldcategory","mtfc_id",$category,"mtft_id");
$atLeastOneImageDoesExistInForm = false;   // Init according to image file upload

// Generate output
$absoluteSystemPath = getAbsoluteSystemPath();  // Definition of absolute path, filename and extension. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
getDBData("job", $objId);                       // Get associative array for JOB data. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
getDBData("tour", $objId);                      // Get associative array for TOUR data of ALL stations. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
getDBData("tourservice", $objId);
getDBData("tourarticle", $objId);
// print_r($jobData); die();
$editMode = 3;  // Prepare for HTML email to convert e.g. to PDF
$outputMetaFieldsHtml = outputMetaFieldSpecial($currTemplateId, $editMode, $absoluteSystemPath);
$outputMetaFieldsHtmlPHP = $outputMetaFieldsHtml[0];
$outputMetaFieldsHtmlJS = $outputMetaFieldsHtml[1];

// Parse template
$jsFormularFinishPageFunc = "finishPage();";
if ($currTemplateId != "" && $currTemplateId != "0") :
   $contentOfCurrTemplate = getFieldValueFromId("metafieldtemplate","mtft_id",$currTemplateId,"mtft_content");
   if (!(strpos($contentOfCurrTemplate, "formularFinishPage") === FALSE)) :
      $jsFormularFinishPageFunc = "formularFinishPage();";
   endif;
endif;


function generateOutputHTML ($htmlSnip, $pageTitel = "") {
	$htmlOut = "";
  $htmlOut .= "<html>\n";
  $htmlOut .= "  <head>\n";
  $htmlOut .= "    <title>" . $pageTitel . "</title>\n";
  $htmlOut .= "  </head>\n";
  $htmlOut .= "  <body>\n";
  $htmlOut .=      $htmlSnip;
  $htmlOut .= "  </body>\n";
  $htmlOut .= "</html>\n";
  return $htmlOut;
}


// Generate unique filename
$categoryName = "XX";
if ($category == "300") :
   $categoryName = "AP";
elseif ($category == "305") :
   $categoryName = "FB";
endif;
$f_secretFileName = $categoryName . "_" . $objId;
if ($commNo != "") :
   $f_secretFileName .= "_" . $commNo;
endif;

// Source filename
$fileExtensionSource = "html";
$fileName = $pdfPathRelative . $f_secretFileName . "." . $fileExtensionSource;

// Target filename
$fileExtensionTarget = $fileTargetType;
$fileNameTarget = $pdfPathRelative . $f_secretFileName . "." . $fileExtensionTarget;


// Generate HTML WITH ABSOLUTE path for creating PDF, etc.
$htmlOut = generateOutputHTML($outputMetaFieldsHtmlPHP);


// Remove old file(s) [Müsste zum Aufräumen noch erweitert werden, so dass automatisch alle Dateien die alter sind als inkl. gestern gelöscht werden !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!]
/*
foreach (glob($fileName) as $fileNameToBoRemoved) {
  if (file_exists($fileNameToBoRemoved)) :
     unlink($fileNameToBoRemoved);
  endif;
}
*/


// **** Convert HTML file ****

// Check configuration for output
if (isset($sendToClientInlineDisplay) && $sendToClientInlineDisplay == "1") : $sendToClientInlineDisplay = true; else : $sendToClientInlineDisplay = false; endif;
if (isset($sendToClientFileDownload) && $sendToClientFileDownload == "1") : $sendToClientFileDownload = true; else : $sendToClientFileDownload = false; endif;
if (!isset($fileTargetType) || $fileTargetType == "") : $fileTargetType = "pdf"; endif;

$pdfGlobalOptions = "";
$pdfPageOptions = "";
if ($pdfPageSize == "DEFAULT") : 
   $pdfPageSize = "";
endif;
if ($pdfPageSize != "") :
   if ($pdfPageSize == "label60x40") :
      $pdfGlobalOptions = array('page-height' => '40mm', 'page-width' => '60mm', 'margin-bottom' => '1mm', 'margin-left' => '3mm', 'margin-right' => '1mm', 'margin-top' => '1mm');
      $pdfPageOptions = array('disable-smart-shrinking');
   else :
      $pdfGlobalOptions = array('page-size' => $pdfPageSize);
   endif;
endif;
if ($pdfGlobalOptions == "" || !is_array($pdfGlobalOptions)) :
   $pdf = new WkHtmlToPdf;
else :
   $pdf = new WkHtmlToPdf($pdfGlobalOptions);
endif;

$pdf->addPage($htmlOut, $pdfPageOptions);  // Add a HTML file, a HTML string or a page from a URL ["$pdf->addPage($fileName);" OR "$pdf->addPage('http://assecutor.de');" possible]
// $pdf->addCover('mycover.html');  // Add a cover (same sources as above are possible)
// $pdf->addToc();  // Add a Table of contents
// Save the PDF
if (!$pdf->saveAs($fileNameTarget)) :
    throw new Exception('Could not create PDF: '.$pdf->getError());
endif;
// Send to client for inline display
if ($sendToClientInlineDisplay == "1") :
   $pdf->send();
endif;
// Send to client for file download
if ($sendToClientFileDownload == "1") :
   $pdf->send($fileNameTarget);
endif;


// echo $htmlOut;
?>
