<?php

namespace App\Utils\Wkhtmltopdf;

/**
 * Uses wkhtmltopdf to convert a HTML document to PDF.
 * @author Gabriel Grosu
 */
class CreatePdf
{

	/**
	 * The initial HTML content.
	 * @var String
	 */
	private $htmlContent;

	/**
	 * The page orientation (landscape, portrait).
	 * @var String
	 */
	private $orientation = 'portrait';

	/**
	 * Attaches html content
	 * @param String $htmlContent
	 */
	public function __construct($htmlContent)
	{
		$this->htmlContent = $htmlContent;
	}

	/**
	 * Sets the orientation of the page
	 * @param String $orientation
	 * @throws \Exception
	 */
	public function setOrientation($orientation)
	{
		if ($orientation=='landscape' or $orientation=='portrait') {
			$this->orientation = $orientation;
		} else {
			throw new \Exception('Invalid orientation set for PDF - '.$orientation);
		}
	}

	/**
	 * Create the outputFile with the (binary) PDF content of the converted HTML document.
	 * @throws \Exception\IO\Base
	 */
	public function writePdf($outputFile)
	{

		// CHECKS AND INITS -------------------------------------------------------------------------

		$pdfInstallerCfg = \App\Utils\Wkhtmltopdf\Installer::getInstance();

		// check that the path of the output file exists
		$outputPath = \Engine\File::getPath($outputFile);
		// check output path
		if (!\Engine\Dir::check($outputPath)) {
			throw new \Exception\IO\Base(sprintf("Could not check the path of the output file (%s)", $outputPath));
		}

		// make sure that the wkhtmltopdf is installed
		$pdfInstallerCfg->install();

		// COPY HTML FILE IN THE TEMPORARY DIR ------------------------------------------------------
		$tempFileName = 'wkhtmltopdf_src_'.uniqid().'.html';
		$tempFileNameWithPath = realpath(\Engine\File::tempnam($tempFileName));
		if (!$tempFileNameWithPath) {
			throw new \Exception\IO\Base(sprintf("Could not create temporary file with html content (%s)", $tempFileNameWithPath));
		}
		if (!\Engine\File::create($tempFileNameWithPath, $this->htmlContent)) {
			throw new \Exception\IO\Base(sprintf("Could not copy HTML content onto temporary (%s)", $tempFileNameWithPath));
		}

		// CREATE PDF FILE ON DISK ------------------------------------------------------------------
		$currentDir = getcwd();
		chdir($pdfInstallerCfg->getLibFullPath());

		$command = sprintf("./wkhtmltopdf --print-media-type --footer-right [page]/[topage] --orientation %s %s %s", $this->orientation, escapeshellarg($tempFileNameWithPath), escapeshellarg($outputFile));
		$processObject = new \Engine\Os\Command\Process($command);
		$processObject->runAndCaptureErrors();
		$outputObject = $processObject->getCommandOutputObj();

		// return to current working directory
		chdir($currentDir);

		// remove temporary file name
		\Engine\File::delete($tempFileNameWithPath);

		return $outputObject;

	}

}


