<?php
class GapsXmlInfoController
{
	private $xmlConfigPath;
	private $reportFiles;
	private $reportPaths;

	public static function Run ($argv)
	{
		echo "* Erstelle Info-Dateien fuer Portal und Versand\r\n";
		$gapsXmlCtrl = new GapsXmlInfoController($argv[1]);
		$gapsXmlCtrl->execute();
	}

	public function __construct ($path = "")
	{
		$this->xmlConfigPath = $path;
		@mkdir("{$this->xmlConfigPath}\\info");
		$this->reportFiles = array();
		$this->reportPaths = array();
		ini_set("default_charset", "iso-8859-1");
	}


	public function execute ()
	{
		$this->applyToAllXmlFiles("getExistingReportFiles");

		$result = array();
		$result['reports'] = $this->applyToAllXmlFiles("reports");
		$this->writeCsvFile($this->getFileName("reports"), $result['reports']);

		$result['versand'] = $this->applyToAllXmlFiles("versand");
		$this->writeCsvFile($this->getFileName("versand"), $result['versand']);

		$result['scorecards'] = $this->applyToAllXmlFiles("scorecards");
		$this->writeCsvFile($this->getFileName("scorecards"), $result['scorecards']);

		$result['ppr'] = $this->applyToAllXmlFiles("ppr");
		$result['ppr'] = array_values(array_merge($result['ppr'], $this->getUnusedReportFiles($result['ppr'])));
		$this->writeCsvFile($this->getFileName("ppr"), $result['ppr']);
		
		$this->writeJsonFile($this->getFileName("info", ".json"), $result);
	}

	private function applyToAllXmlFiles ($callback)
	{
		$configDir = dir($this->xmlConfigPath);
		$result = array();

		while ($xmlFile = $configDir->read()) {
			if (!preg_match('/\.xml$/i', $xmlFile) || $xmlFile == "auth.xml") {
				continue;
			}
			$doc = simplexml_load_file($this->xmlConfigPath . "\\" . $xmlFile);
			$add = @call_user_func(array($this, $callback), $xmlFile, $doc);
			$result = array_merge($result, $add);
		}
		return $result;
	}

	private function reports ($fileName, $doc)
	{
		$result = array();
		$subPath = $this->getReportsSubDir($doc);

		foreach ($doc->Publishes->Publish as $publish) {
			/** @var SimpleXMLElement $publish */
			$attr = $publish->attributes();
			foreach ($publish->Images->Image as $image) {
				$rep = strtolower(trim($subPath . (string)$image->Report));

				$r = array();
				$r['Datei'] = $fileName;
				$r['Benutzer'] = substr((string)$image->Directory, 0, -1);
				$r['Struktur'] = (string)$attr->Name;
				$r['Report'] = (string)$image->Report;
				$r['Name'] = str_replace(";", ",", (string)$image->Name);
				$r['GIF'] = (string)$image->GIFGenerate;
				$r['Schicht'] = (string)$image->ImageLayer;
				$r['PDF'] = (string)$image->PDFGenerate;
				$r['PDF-Schicht'] = (string)$image->PDFImageLayer;
				$r['XLS'] = (string)$image->XLSGenerate;
				$r['Versand'] = (string)$image->SendEmail;
				$r['Empfaenger'] = str_replace(";", ",", (string)$image->Email);
				$r['Cube'] = (isset($this->reportFiles[$rep])) ? $this->reportFiles[$rep] : "";

				$result[] = $r;
			}
		}
		return $result;
	}


	private function versand ($fileName, $doc)
	{
		$result = array();
		$subPath = $this->getReportsSubDir($doc);

		foreach ($doc->Publishes->Publish as $publish) {
			/** @var SimpleXMLElement $publish */
			$attr = $publish->attributes();
			foreach ($publish->Images->Image as $image) {
				if (stripos((string)$image->Report, "_graf")) {
					continue;
				}
			
				$empfaenger = explode(";", (string)$image->Email);
				if ($empfaenger[0] == "") {
					continue;
				}
				$rep = strtolower(trim($subPath . (string)$image->Report));

				foreach ($empfaenger as $eintrag) {
					$e = array();
					$e['Datei'] = $fileName;
					$e['Benutzer'] = substr((string)$image->Directory, 0, -1);
					$e['Struktur'] = (string)$attr->Name;
					$e['Empfaenger'] = strtolower($eintrag);
					$e['Report'] = (string)$image->Report;
					$e['Name'] = str_replace(";", ",", (string)$image->Name);
					$e['Versand'] = (string)$image->SendEmail;
					$e['PDF'] = (string)$image->PDFGenerate;
					$e['PDF-Schicht'] = (string)$image->PDFImageLayer;
					$e['XLS'] = (string)$image->XLSGenerate;
					$e['Cube'] = (isset($this->reportFiles[$rep])) ? $this->reportFiles[$rep] : "";

					$result[] = $e;
				}
			}
		}
		return $result;
	}

	private function scorecards ($fileName, $doc)
	{
		$result = array();

		foreach ($doc->Scorecards->Scorecard as $publish) {
			/** @var SimpleXMLElement $publish */
			$attr = $publish->attributes();
			foreach ($publish->Reports->Report as $sc) {
				$r = array();
				$r['Datei'] = $fileName;
				$r['Benutzer'] = substr((string)$attr->Directory, 0, -1);
				$r['Struktur'] = (string)$attr->Name;
				$r['Report'] = (string)$sc->ReportFile;
				$r['Name'] = str_replace(";", ",", (string)$sc->Name);
				$r['Zeile'] = (string)$sc->RowData;
				$r['Spalte'] = (string)$sc->ColData;
				$r['Aktiv'] = (string)$sc->Active;

				$result[] = $r;
			}
		}
		return $result;
	}

	public function getExistingReportFiles ($fileName, $doc, $getSubPath = true, $cubefilter = false)
	{
		$pprPath = (is_dir($doc)) ? $doc : (string)$doc->General->ReportPath;
		$this->reportPaths[$pprPath][$fileName] = 1;
		if (count($this->reportPaths[$pprPath]) > 1) {
			return array();
		}
		if (!is_dir($pprPath)) return array();
		$pprDir = dir($pprPath);
		$subPath = ($getSubPath) ? $this->getReportsSubDir($doc) : "";

		while ($file = $pprDir->read()) {
			if (preg_match('/(.*)\.pp[rx]$/i', $file, $matches)) {
				$cube = GapsXmlInfoController::openFileAndExtractCubeInfo($pprPath.$file);
				$rep = strtolower($subPath.$matches[1]);
				if (!$cubefilter || $cubefilter == $cube) {
					$this->reportFiles[$rep] = $cube;
				}
			}
		}
		return $this->reportFiles;
	}

	public static function openFileAndExtractCubeInfo ($fileName)
	{
		$fh = fopen($fileName, "r");
		for ($i = 0; $i < 200; $i++) {
			$row = fread($fh, 300);
			if (preg_match("/cube_out.([\w\s\d]*)\.mdc/i", $row, $matches)) {
				fclose($fh);
				return strtolower($matches[1]);
			}
		}
		fclose($fh);
		return "";
	}


	private function ppr ($fileName, $doc)
	{
		$subPath = $this->getReportsSubDir($doc);

		$linksArray = array();

		$result = array();
		foreach ($doc->Publishes->Publish as $publish) {
			/** @var SimpleXMLElement $publish */
			$attr = $publish->attributes();
			foreach ($publish->Images->Image as $image) {
				$rep = strtolower(trim($subPath . (string)$image->Report));
				$layer = 0 + (int)$image->ImageLayer + (int)$image->PDFImageLayer;
				if (isset($linksArray[$rep])) {
					$linksArray[$rep][$layer] = 1;
					continue;
				}
				$linksArray[$rep][$layer] = 1;

				$r = array();
				$r['Datei'] = $fileName;
				$r['Report'] = $rep;
				$r['Name'] = trim(str_replace(";", ",", (string)$image->Name));
				$r['PPR'] = (isset($this->reportFiles[$rep])) ? "" : "fehlt";
				$r['Cube'] = (isset($this->reportFiles[$rep])) ? $this->reportFiles[$rep] : "";
				$r['Typ'] = $this->getImageType($image);
				$r['Schichten'] = "";

				$result[$rep] = $r;
			}
		}

		foreach ($doc->Scorecards->Scorecard as $publish) {
			/** @var SimpleXMLElement $publish */
			$attr = $publish->attributes();
			foreach ($publish->Reports->Report as $sc) {
				$rep = strtolower(trim($subPath . (string)$sc->ReportFile));
				if (isset($linksArray[$rep])) {
					continue;
				}
				$linksArray[$rep][0] = 1;

				$r = array();
				$r['Datei'] = $fileName;
				$r['Report'] = $rep;
				$r['Name'] = trim(str_replace(";", ",", (string)$sc->Name));
				$r['PPR'] = (isset($this->reportFiles[$rep])) ? "" : "fehlt";
				$r['Cube'] = (isset($this->reportFiles[$rep])) ? $this->reportFiles[$rep] : "";
				$r['Typ'] = "SC";
				$r['Schichten'] = "";

				$result[$rep] = $r;
			}
		}

		foreach ($linksArray as $rep => $layer) {
			$lay = array_keys($layer);
			sort($lay);
			$result[$rep]['Schichten'] = "[" . implode(",", $lay) . "]";
		}
		return $result;
	}

	private function getUnusedReportFiles ($linksArray)
	{
		$result = array();
		$rest = array_diff(array_keys($this->reportFiles), array_keys($linksArray));
		foreach ($rest as $rep) {
			$r = array();
			$r['Datei'] = "nicht verwendet";
			$r['Report'] = $rep;
			$r['Name'] = "";
			$r['PPR'] = "";
			$r['Cube'] = $this->reportFiles[$rep];
			$r['Typ'] = "";
			$r['Schichten'] = "";

			$result[$rep] = $r;
		}
		return $result;
	}

	private function writeCsvFile ($fileName, $content)
	{
		if (count($content) > 0) {
			$c = array();
			$c[] = implode(";", array_keys(current($content)));

			foreach($content as $row) {
				$c[] = implode(";", $row);
			}
			file_put_contents($fileName, mb_convert_encoding(implode("\r\n", $c), "ISO-8859-1", "UTF-8"));
			echo "* Schreibe Datei '{$fileName}'\r\n";
		}
	}
	
	private function writeJsonFile ($fileName, $content)
	{
		file_put_contents($fileName, json_encode($content));
		echo "* Schreibe Datei '{$fileName}'\r\n";
	}

	private function getFileName ($fileName, $extension = ".csv")
	{
		$fileName = "{$this->xmlConfigPath}\\info\\{$fileName}{$extension}";
		return $fileName;
	}

	private function getReportsSubDir ($doc)
	{
		$pprPath = (string)$doc->General->ReportPath;
		$parentDir = dirname($pprPath);
		$subDir = str_replace($parentDir . "\\", "", $pprPath);
		return $subDir;
	}

	private function getImageType ($image)
	{
		if ((string)$image->PDFGenerate == "J") return "PDF";
		if ((string)$image->GIFGenerate == "J") return "GIF";
		if ((string)$image->XLSGenerate == "J") return "XLS";
		if ((string)$image->Active == "J") return "PPR";
		return "?";
	}

}

?>