<?php
/*class Font extends FontLib\Font {
	// This is a namespace fix for $dompdf->render();
}*/

class SupsysticTablesPro_Exporter_Type_Pdf implements SupsysticTablesPro_Exporter_Interface
{
	/**
	 * @var string
	 */
	protected $domPdfPath;

	protected $fontPath;

	/**
	 * @param string $domPdfPath
	 */
	public function __construct($domPdfPath)
	{
		$this->domPdfPath = $domPdfPath;
		$this->exportFonts = !empty($_REQUEST['export_fonts']) && $_REQUEST['export_fonts'] == 'on';
		add_filter('dom2pdf_font_families', array($this, 'setExportFont'));
		add_filter('dom2pdf_get_fonts_path', array($this, 'setExportFontPath'));
	}

	public function setExportFontPath($fontPath)
	{
		$fontsUploadDir = $this->_getFontsDir();
		$fontPath = str_replace('\\', '/', $fontsUploadDir . '/');

		return $fontPath;
	}

	public function setExportFont($originalFonts)
	{
		if(!$this->exportFonts) {
			$originalFonts = 'arial';
		} else {
			$families = array_filter(array_map(function($item) {
				//remove leading and trailing whitespace, leading and trailing string delimiters (e.g. on font names with spaces)
				return trim($item, " \t\n\r\x0B\"'");
			}, explode(',', $originalFonts)));

			foreach($families as $f) {
				$originalFonts = strtolower(str_replace('"', '', strtolower(str_replace(' ', '', $f))));
				$font = Font_Metrics::get_font($originalFonts);

				if(empty($font)) {
					$fontName = implode('+', array_map('ucfirst', explode(' ', $f)));
					$response = wp_remote_get('http://fonts.googleapis.com/css?family='.$fontName);
					if(!is_wp_error($response)) {
						$fontStylesheet = wp_remote_retrieve_body($response);
						if(!empty($fontStylesheet)) {
							preg_match_all('/src:.*url\((.*)\).*;/Usim', $fontStylesheet, $fontUrls);

							//var_dump('http://fonts.googleapis.com/css?family=' . $fontName);
							if(!empty($fontUrls[1])) {
								$dir = $this->_getFontsDir();

								if(!empty($dir)) {
									foreach($fontUrls[1] as $url) {
										$httpReq = new WP_Http();
										$fontFileBaseName = implode('', array_map('ucfirst', explode(' ', $f)));
										$fontFileName = $fontFileBaseName . '.ttf';
										$fontFilePath = $dir . DS . $fontFileName;

										if(!file_exists($fontFilePath)) {
											$fontFilePath = '';
											$fontFileData = $httpReq->request($url, array('timeout' => 25));

											remove_filter('upload_mimes', array($this, '_removeFontFromWpUpload'));
											add_filter('upload_dir', array($this, '_changeUploadDir'));
											add_filter('upload_mimes', array($this, '_addFontToWpUpload'));
											$uploaded = wp_upload_bits($fontFileName, null, $fontFileData['body']) ;
											remove_filter('upload_dir', array($this, '_changeUploadDir'));
											add_filter('upload_mimes', array($this, '_removeFontFromWpUpload'));

											if(!empty($uploaded) && !empty($uploaded['url'])) {
												$fontFilePath = $uploaded['url'];
											}
										}

										if(!empty($fontFilePath)) {
											$styles = array('bold', 'bold_italic', 'italic', 'normal');

											foreach($styles as $s) {
												Font_Metrics::register_font(array(
													'family' => $originalFonts,
													'style' => $s,
													'weight' => 400,
												), $fontFileBaseName);
											}
										}
									}
								}
							}

						}
					}
				}

			}
		}
		return $originalFonts;
	}
	
	/**
	 * {@inheritdoc}
	 */
	public function export(array $data)
	{
		$hostnames = array(
			implode('', array('http', '://', $_SERVER['HTTP_HOST'])),
			implode('', array('https', '://', $_SERVER['HTTP_HOST'])),
			implode('', array('//', $_SERVER['HTTP_HOST']))
		);
		$data['paper_size'] = $this->_getPaperSize($data['paper_size'], $data['columns']);
		$html = '<html><head>
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8;"/>
				<style type="text/css">
					* {
						-webkit-print-color-adjust: exact;
					}
					body {
						font-family: Arial, sans-serif !important;
						font-size:13px;
						line-height: 25px;
					}
					table.supsystic-table {
						width: 100% !important;
						max-width: 100% !important;
						border-collapse: collapse;
						border-spacing: 0;
						-webkit-border-horizontal-spacing: 0;
						-webkit-border-vertical-spacing: 0;
					}
					table.supsystic-table img {
						max-width: none;
						max-height: none;
					}
					@media print{
						@page {
							size: ' . $data['orientation'] . ';
						}
					}
				</style>
				</head><body><div id="wrapper">';
		if (is_array($data['pdf-table-data'])) {
			foreach ($data['pdf-table-data'] as $piece) {
//				$htmlData = urldecode(base64_decode($piece));
				$htmlData = base64_decode($piece);
				$html .= $htmlData;
			}
		} else {
//			$html .= urldecode(base64_decode($data['pdf-table-data']));
			$html .= base64_decode($data['pdf-table-data']);
		}
		$html .= '</div></body></html>';
		$html = str_replace($hostnames, '.', $html);
//		echo $html;
//		exit;

		if(strlen(ini_get('memory_limit')) < 4) {
			ini_set('memory_limit', '12000M');
		}
		$dompdf = new Dompdf();
		$dompdf->set_option('temp_dir', get_temp_dir());
		$dompdf->set_option('enable_html5_parser', true);
		if(!$this->exportFonts) {
			$dompdf->set_option('font_height_ratio', 1.7);
		}
		$dompdf->set_base_path($_SERVER['DOCUMENT_ROOT']);
		$dompdf->load_html($html);
		$dompdf->set_paper($data['paper_size'], $data['orientation']);

		@$dompdf->render();

		print $dompdf->output();
	}
	
	public function _getPaperSize($paper_size, $columns)
	{
		if($paper_size == 'auto') {
			if($columns > 20) {
				$paper_size = 'A1';
			} else if($columns > 10) {
				$paper_size = 'A2';
			} else if($columns > 5) {
				$paper_size = 'A3';
			}
		}
		return $paper_size;
	}

	public function _getFontsDir()
	{
		$uploads = wp_upload_dir();
		$basedir = $uploads['basedir'];
		$dir = $basedir . '/supsystic-tables/fonts';

		if(!is_dir($dir)) {
			if(false === @mkdir($dir, 0775, true)) {
				return false;
			}
		} else {
			if(!is_writable($dir)) {
				return false;
			}
		}
		return $dir;
	}

	public function _changeUploadDir($uploads)
	{
		$uploads['subdir'] = DS . 'supsystic-tables' . DS . 'fonts';
		$uploads['path'] = $uploads['basedir'] . $uploads['subdir'];
		$uploads['url'] = $uploads['baseurl'] . '/'.$uploads['subdir'];

		return $uploads;
	}

	public function _addFontToWpUpload($mimes = array())
	{
		$mimes['ttf'] = 'font/ttf';
		return $mimes;
	}

	public function _removeFontFromWpUpload($mimes = array())
	{
		if(isset($mimes['ttf']))
			unset($mimes['ttf']);
		return $mimes;
	}
}
