<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Latex extends MY_Controller
{
	private static $url = "https://pdf.nerivon.ca:55555";

	/**
	 * Using an externally hosted Python script, HTML will be converted to LaTeX code.
	 * @param  string $html HTML to be converted to LaTeX code.
	 * @return string       Converted LaTeX code.
	 */
	public static function html_latex($html)
	{
		// We need to save the HTML in a temp file so that we can POST it properly.
		$path = tempnam("/tmp", "html2latex");
		file_put_contents($path, $html);

		// Initialize cURL, set its POST fields, and grab the returned data (LaTeX code).
		$ch = curl_init();
		$fields = array('htmlfile'=>curl_file_create($path,'text/plain','main.html'));
		$opts = array(CURLOPT_URL => self::$url . "/htmltolatex",
                      CURLOPT_POST => 1,
                      CURLOPT_POSTFIELDS => $fields,
                      CURLOPT_RETURNTRANSFER => 1,
                      CURLOPT_SSL_VERIFYPEER => false);
	    curl_setopt_array($ch, $opts);
		$latex_data = curl_exec($ch);
	    curl_close($ch);

	    // Remove the temp file.
	    @unlink($path);

	    return $latex_data;
	}

	public static function latex_data($title, $subject, $content, $is_html, $template_file="template.tex")
	{
		// Grab the template LaTeX content and replace our variables with given data.
		if($template_file)
		{
			$template = file_get_contents(ABSOLUTE_PATH . "/templates/latex/" . $template_file);
		}
		else
		{
			$template = $content;
		}
		$template = str_replace("<<title>>", 			$title, 			$template);
		$template = str_replace("<<subject>>", 			$subject, 			$template);
		$template = str_replace("<<author>>", 			COMPANY_NAME, 		$template);
		$template = str_replace("<<company>>", 			COMPANY_NAME, 		$template);
		$template = str_replace("<<date>>", 			date("l, F jS, Y \a\\t g:iA"), $template);

		/**
		 * The content passed can be an object for use in the template.
		 * The template will have a matching field value so we'll loop each field in our object and replace placeholders if found.
		 */
		if(gettype($content) == "object")
		{
			$vars = get_object_vars($content);

			foreach($vars as $key=>$value)
			{
				if(gettype($value) != "object" && gettype($value) != "array")
				{
					$template = str_replace("<<" . $key . ">>", $value, $template);
				}
			}
		}
		else if(gettype($content) == "string")
		{
			// If HTML was passed in, we need to convert it to LaTeX code.
			if($is_html)
			{
				$content = self::html_latex($content);
				// This is our own little hack to preserve \newline through the HTML to LaTeX conversion.
				$content = str_replace('\{newpage\}', '\n{\newpage}\n ', $content);
				$template = ($template_file ? $template : $content);
			}

			$template = str_replace("<<content>>", $content, $template);
		}

		return $template;
	}

	/**
	 * Using an externally hosted Python script, HTML or LaTeX code will be converted to a PDF based on the supplied TEX template.
	 * @param  string $title             	Title of the document. Also used as the filename if output to the browser.
	 * @param  string $subject           	PDF subject metadata.
	 * @param  string $content           	HTML or LaTeX code to be inserted into the template.
	 * @param  boolean $is_html          	If passing HTML, set this to true.  If passing LaTeX code, set this to false.
	 * @param  boolean $output_to_browser 	If set to true, the PDF will be output to the browser as a download. Otherwise, a string of PDF data will be returned.
	 * @param  string $template_file        A template file, in TEX format, relative to the /templates/latex directory.
	 * @return mixed                    	If output_to_browser is true, returns null. Otherwise, a string of PDF data is returned.
	 */
	public static function latex_pdf($title, $subject, $content, $is_html, $output_to_browser, $filename, $template_file="template.tex")
	{
		@chmod(ABSOLUTE_PATH . "/templates/latex/", 0755);

		$template = Latex::latex_data($title, $subject, $content, $is_html, $template_file);

		// This temp file will hold our LaTeX code.
		$tempfile = tempnam(ABSOLUTE_PATH . "/templates/latex/", "main-");
		$zipfile  = $tempfile . ".zip";

		// Save the LaTeX code to our temp file.
		file_put_contents($tempfile, $template);

		// ZIP the contents of the template directory.
		$zip = new PharData($zipfile, null, null, Phar::ZIP);

		$files = scandir(ABSOLUTE_PATH . "/templates/latex/");

		// Add all files in /templates/latex except other temp files.
		foreach($files as $file)
		{
			if($file != "." && $file != "..")
			{
				$path = ABSOLUTE_PATH . "/templates/latex/" . $file;

				// Add our main tex file as "main.tex"
				if($path == $tempfile)
				{
					$zip->addFile($path, "main.tex");
				}
				// Add any other files which are not another user's temp file.
				else if(preg_match('/^main-/', $file) === 0 && $file != $template_file)
				{
					$zip->addFile($path, $file);
				}
			}
		}

		// Initialize cURL, set its POST fields, and grab the returned data (PDF code).
		$ch = curl_init();
		$fields = array('zipfile'=>curl_file_create($zipfile,'application/zip','main.zip'));
		$opts = array(CURLOPT_URL => self::$url . "/latextopdf",
                      CURLOPT_POST => 1,
                      CURLOPT_POSTFIELDS => $fields,
                      CURLOPT_RETURNTRANSFER => 1,
                      CURLOPT_SSL_VERIFYPEER => false);
	    curl_setopt_array($ch, $opts);
		$pdf_data = curl_exec($ch);
	    curl_close($ch);

	    // Remove the temp files.
	    @unlink($tempfile);
		@unlink($zipfile);

		// Output the PDF to the browser or return the PDF data.
		if($output_to_browser)
		{
			header("Content-type: application/pdf");
			header("Content-Disposition: inline; filename=" . str_replace(" ", "_", addslashes($filename)) . ".pdf");

			echo $pdf_data;
			return null;
		}
		else
		{
			return $pdf_data;
		}
	}
}
