<?php

/* * *************************************************************
 *  Copyright notice
 *
 *  (c) 2007 Original Software by Thomas Waggershauser <waggershauser@airware.de>
 *  (c) 2018 Stefan Beyer SEDAT GmbH <stefan@sedat.de>
 *  All rights reserved
 *
 *  This script is part of Cy4Marktzeitung. The Cy4Marktzeitung project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 * ************************************************************* */
if (!defined('ENTRY_POINT'))
  die('Falscher Aufruf');

define('CLI', php_sapi_name() === 'cli');

include 'system-test.php';

require_once $config;


include 'config-test.php';



require_once "HTMLCleaner.php";
require_once "ExtraFieldManager.php";
require_once 'class.AdsManager.php';
require_once 'class.AdsPDF.php';

if (!isset($custom_functions))
  $custom_functions = 'custom_functions.php';
if (file_exists($custom_functions) && filesize($custom_functions) > 0) {
  include $custom_functions;
} else {
  require_once "default_functions.php";
}

require_once 'o.php';

# Update Check
if (!defined('CALL_HOME') || CALL_HOME) {
  if (!defined('CALL_HOME_APP')) define('CALL_HOME_APP', 'Cy4Marktzeitung');
  if (!defined('CALL_HOME_SERVER')) define('CALL_HOME_SERVER', 'https://updates.wapplications.net/');
  if (!defined('CALL_HOME_INTERVAL')) define('CALL_HOME_INTERVAL', 'P1D');
  $updateChecker = include 'CallHome.php';
  $updateCheck = $updateChecker(CALL_HOME_APP, CALL_HOME_SERVER, CALL_HOME_INTERVAL, function() {
    return include 'version.php';
  });
  if (is_object($updateCheck) && ($updateCheck->latestFull ?? false)) {
    console('Neue Version ' . $updateCheck->latestFull . ' verfügbar: ' . CALL_HOME_SERVER . CALL_HOME_APP . '/download/?version=' . $updateCheck->latestFull . '&type=full');
  }
} else {
  $updateCheck = null;
}

// TODO ggf vereinfachen
$saveFile = false;
$fileName = 'output.pdf';

if (!USE_WEB_INTERFACE || CLI || isset($_POST['generate']) || isset($_GET['output'])) {
  $name = isset($_GET['output']) ? $_GET['output'] : '';
  $name = preg_replace('`[^a-zA-Z0-9_\\-]*`', '', $name);
  if ($name || CLI) {
    $saveFile = true;
  }
  if ($name) {
    $fileName = $name.'.pdf';
  }
} else {
  include 'webinterface.php';
}

$outputMethod = PDF_OUTPUT_METHODE;
if (strpos($outputMethod, 'F') !== false) {
  $saveFile = true;
}
if ($saveFile) {
  $outputMethod = 'F';
  $fileName = realpath('./').'/'.$fileName;
}





$adsManager = new AdsManager();
$pdf = new AdsPDF();


staticContentToPDF($pdf, 'CONTENT_BEFORE');


if (CATALOG_TYPE === 1) {
  /**
   * Katalog erstellen Variante 1
   * 
   * 1. Ebene: Kategorien
   * 2. Ebene tradeTypes
   */
  $tradeTypes = TRADE_TYPE_ORDER; //['OFFER', 'SEARCH', ...];
  $catalog = $adsManager->getCatalog($tradeTypes);
  $pdf->setCount(countCatalog($catalog));
  $pdf->categories = $adsManager->getFlatCategories();
  $pdf->initialize();
  $pdf->tradetypeTop = $tradeTypes;

  $tocPage = $pdf->getPage()+1;

  $pdf->AddPage();
  $pdf->render($catalog);
  
  renderTOC($pdf, $tocPage);

} else if (CATALOG_TYPE === 2) {
  /** 
   * Katalog erstellen  Variante 2
   * 
   * 1. Ebene tradeTypes
   * 2. Ebene: Kategorien
   */
  $tradeTypes = TRADE_TYPE_ORDER; //['OFFER', 'SEARCH', ...];
  $catalog = [];
  # zählen...
  $count = 0;
  foreach ($tradeTypes as $tt) {
    $catalog[$tt] = $adsManager->getCatalog([$tt]);
    $count += countCatalog($catalog[$tt]);
  }
  $pdf->setCount($count);
  $pdf->categories = $adsManager->getFlatCategories();
  $pdf->initialize();

  $tocPage = $pdf->getPage()+1;

  for ($i = 0; $i < count($tradeTypes); $i++) {
    $tt = $tradeTypes[$i];
    $pdf->tradetypeTop = [$tt];
    $pdf->AddPage();
    $pdf->render($catalog[$tt]);
  }  

  renderTOC($pdf, $tocPage);
}


staticContentToPDF($pdf, 'CONTENT_AFTER');


// das pdf ausgeben..
$pdf->outputPDF($fileName, $outputMethod);  // 'I' = im Browser oeffnen, 'D' = download




function staticContentToPDF($pdf, $name) {
  if (!defined($name)) {
    return;
  }
  $filename = constant($name);
  if (empty($filename)) {
    return;
  }
  if (is_array($filename)) {
    foreach ($filename as $fn) {
      renderStaticContentToPDF($pdf, $fn);
    }
    return;
  }
  renderStaticContentToPDF($pdf, $filename);
}

function renderStaticContentToPDF($pdf, $filename) {
  if (!$filename || !file_exists($filename)) {
    if (defined('DEBUG') && DEBUG) {
      die('static content file '.$filename.' existiert nicht');
    }
    return;
  }
  $buffer = file_get_contents($filename);
  $mt = $pdf->getMargins()['top'];
  $pdf->SetTopMargin(PDF_MARGIN_HEADER);
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
  $pdf->printHeader = false;
  $pdf->AddPage();
  $pdf->writeHTML($buffer, true, false, true, true);
  $pdf->SetTopMargin($mt);
  $pdf->printHeader = true;
}

function countCatalog($catalog) {
  if (!is_array($catalog)) {
    return 0;
  }
  $count = 0;
  foreach ($catalog as $cat) {
    foreach ($cat as $type => $ads) {
      $count += count($ads);
    }
  }
  return $count;
}


function renderTOC($pdf, $page) {
  if (!defined('TOC')) return;
  if (!TOC) return;
  
  // doc: https://tcpdf.org/docs/srcdoc/TCPDF/classes-TCPDF/
  $pdf->printHeader = false;
  $pdf->addTOCPage();
  $pdf->selectColumn(0);
  $pdf->writeHTML('<h1>Inhaltsverzeichnis</h1>', true, false, true, false, '');
  $bookmark_templates = array();
  $bookmark_templates[0] = '<table border="0" cellpadding="0" cellspacing="0" style="background-color:#EEFAFF"><tr><td width="155mm"><span style="font-weight:bold;font-size:12pt;">#TOC_DESCRIPTION#</span></td><td width="25mm"><span style="font-family:courier;font-weight:bold;font-size:12pt;" align="right">#TOC_PAGE_NUMBER#</span></td></tr></table>';
  $bookmark_templates[1] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td width="5mm">&nbsp;</td><td width="150mm"><span style="font-size:11pt;">#TOC_DESCRIPTION#</span></td><td width="25mm"><span style="font-family:courier;font-weight:bold;font-size:11pt;" align="right">#TOC_PAGE_NUMBER#</span></td></tr></table>';
  $bookmark_templates[2] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td width="10mm">&nbsp;</td><td width="145mm"><span style="font-size:10pt;"><i>#TOC_DESCRIPTION#</i></span></td><td width="25mm"><span style="font-family:courier;font-weight:bold;font-size:10pt;" align="right">#TOC_PAGE_NUMBER#</span></td></tr></table>';
  $pdf->addHTMLTOC($page, 'INDEX', $bookmark_templates, true, 'B', array(128,0,0));
  $pdf->endTOCPage();
  $pdf->printHeader = true;
}





function webPage($title, $content, $styles) {
  echo '<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="de">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="version" content="'.(include 'version.php').'">
  <title>Marktzeitung - ' . htmlentities($title) . '</title>
  <style>
  html, body {
    font-family:sans-serif;
    padding:0;
    margin:0;
    height: 100%;
    background-color:#eee;
  }
  code {
    color: #007;
  }
  #container {
    box-sizing:border-box;
    margin-top:30px;
    max-width:600px;
    margin: 30px auto 0 auto;
    padding:60px 20px 20px 20px;
    border:1px solid #777;
    background-color:#fff;
    border-radius:3px;
    border-top-left-radius:30px;
    position:relative;
    box-shadow:2px 2px 16px 0px rgba(0,0,0,0.5);
  }
  #container h1 {
    position:absolute;
    top:0;
    right:20px;
    color:#ff9b59;
    font-weight:normal;
  }
  h3 {
    font-weight:normal;
    color:#777;
    font-size:90%;
  }
  ' . $styles . '
  </style>
  </head><body><div id="container">' . $content . '</div></body></html>';
}

function dieWithContent($html) {
  $html = str_replace('###reason###', '<h3>Das Problem</h3>', $html);
  $html = str_replace('###solution###', '<h3>Mögliche Lösung</h3>', $html);

  if (CLI) {

    function err($c) {
      if (!file_put_contents('php://stderr', $c)) {
        echo $c;
      }
    }

    $html = strip_tags($html);
    $html .= "\n\n";
    err($html);
    die();
  }

  webPage('Fehler', '<h1>Fehler</h1><img src="media/alert.png" id="alert" />' . $html, '
  img#alert {
    position:absolute;
    top:0;
    left:0;
  }');

  die();
}
