<?php
/*class Font extends FontLib\Font {
	// This is a namespace fix for $dompdf->render();
}*/
ini_set('max_execution_time', '300');
ini_set("pcre.backtrack_limit", "5000000");

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

	protected $fontPath;

	protected $mpdf;

	/**
	 * @param string $domPdfPath
	 */

	public function __construct($path) {
	}

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

		return $fontPath;
	}

	public function setExportFont($originalFonts) {
			$families = array_filter(array_map(function($item) {
				return trim($item, " \t\n\r\x0B\"'");
			}, explode(',', $originalFonts)));
			$fontFamilyList = array();
			foreach($families as $f) {
				$originalFonts = strtolower(str_replace('"', '', strtolower(str_replace(' ', '', $f))));
					$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);
							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 . DIRECTORY_SEPARATOR . $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'));
											$filePath = $uploaded['file'];
											$fileName = basename($uploaded['file']);
											$fileDestination = DTGS_PRO_PLUGIN_DIR_PATH.'vendor'.DS.'mpdf'.DS.'uploads'.DS.'mpdf'.DS.'ttfontdata'.DS.$fileName;
											rename($filePath, $fileDestination);
											$fontFamilyListArr['name'] = str_replace('+',' ',$fontName);
											$fontFamilyListArr['fileName'] = $fileName;
											$fontFamilyList[] = $fontFamilyListArr;
											if(!empty($uploaded) && !empty($uploaded['url'])) {
												$fontFilePath = $uploaded['url'];
											}
										}
									}
								}
							}
						}
					}
			}
			return $fontFamilyList;
	}

	/**
	 * {@inheritdoc}
	 */
	public function export(array $data) {
		$htmlStart = '<html>';
		$htmlHead = '<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8;"/>';
		$css = '<style>
					body {
						display:block;
						position:relative;
						width:100%;
					}
					* {
						-webkit-print-color-adjust: exact;
					}
					.supsystic-tables-wrap table.supsystic-table tr .invisibleCell {
					    display: none;
					}
					table.supsystic-table {
						width: 100%;
						line-height: 100%;
						border-collapse: collapse;
						border-color: gray;
					}
					table.supsystic-table * {
						line-height: 100%;
					}
					table.supsystic-table img {
						max-width: none;
						max-height: none;
					}
					.supsystic-tables-features {
						display:none;
					}
					@media print{
						@page {
							size: ' . $data['orientation'] . ';
						}
					}
				</style>';
		$htmlEndHead = '</head>';
		$htmlBody = '<body><div id="wrapper">';
		$htmlInner = '';
		if (is_array($data['pdf-table-data'])) {
			foreach ($data['pdf-table-data'] as $key => $piece) {
		    $piece = preg_replace('/<a href="#" class="delete-upload-file" title="(.*?)">(.*?)<\/a>/', '', base64_decode($piece));
				$htmlInner .= $piece;
			}
		} else {
			$data['pdf-table-data'] = preg_replace('/<a href="#" class="delete-upload-file" title="(.*?)">(.*?)<\/a>/', '', base64_decode($data['pdf-table-data']));
			$htmlInner .= $data['pdf-table-data'];
		}
		$htmlBodyEnd = '</div></body></html>';
		$htmlInner = str_replace("!important", "", $htmlInner);
		$htmlRes = $htmlStart . $htmlHead . $css . $htmlEndHead . $htmlBody . $htmlInner . $htmlBodyEnd;
		$htmlRes = str_replace('@import url("//', '@import url("http://', $htmlRes);
		$fontFamilyHtml = str_replace('&quot;','"',$htmlRes);
		$fontFamilyList = array();
		$re = '/font-family:(.*?);/m';
		preg_match_all($re, $fontFamilyHtml, $fontFamilyMatches, PREG_SET_ORDER, 0);

		foreach ($fontFamilyMatches as $key => $font) {
			$fontFamily = str_replace('"','',$font[1]);
			$fontFamily = str_replace(',','',$font[1]);
			$fontFamily = str_replace('!important','',$fontFamily);
			$fontFamily = trim($fontFamily);
			if (!in_array($fontFamily, $fontFamilyList)) {
				$fontFamilyList[] = $fontFamily;
			}
		}
		$fontFamilyList = $this->setExportFont(implode(',', $fontFamilyList));
		$fonts = array();
		foreach ($fontFamilyList as $font) {
			$fontPath = DTGS_PRO_PLUGIN_DIR_PATH . '/vendor/dompdf/lib/fonts/' . $font['fileName'];
			$fontName = mb_strtolower($font['name']);
			$fontName = str_replace(' ', '', $fontName);
			$fonts[$fontName] = array(
				'R' => $font['fileName'],
				'B' => $font['fileName'],
				'I' => $font['fileName']
			);
			$replace = 'font-family: '.$font['name'];
			$replaceOn = 'font-family: '.$fontName;
			$htmlRes = str_replace($replace, $replaceOn, $htmlRes);
			$replace = 'font-family:'.$font['name'];
			$replaceOn = 'font-family:'.$fontName;
			$htmlRes = str_replace($replace, $replaceOn, $htmlRes);
			$replace = 'font-family: &quot;'.$font['name'].'&quot;';
			$replaceOn = 'font-family:'.$fontName;
			$htmlRes = str_replace($replace, $replaceOn, $htmlRes);
			$replace = 'font-family:&quot;'.$font['name'].'&quot;';
			$replaceOn = 'font-family:'.$fontName;
			$htmlRes = str_replace($replace, $replaceOn, $htmlRes);
		}
		if ($data['full_width'] != 'off') {
			$htmlRes = preg_replace('/<table (.*?)>/', '<table class="supsystic-table" cellpadding="5px" autosize="1" border="0" width="100%" style="overflow: wrap">', $htmlRes);
		}
		$orientation = !empty($data['orientation']) && $data['orientation'] == 'portrait' ? 'P' : 'L';

		require_once DTGS_PRO_PLUGIN_DIR_PATH . '/vendor/php-dom-wrapper/vendor/autoload.php';
		@$domWrapper = new DOMWrap\Document();
		@$domWrapper->html($htmlRes);
		@$domWrapper->find('.invisibleCell')->wrapAll('<div style="display:none"><p/></div>');
		@$htmlRes = $domWrapper->html();

		require_once DTGS_PRO_PLUGIN_DIR_PATH . '/vendor/mpdf/vendor/autoload.php';
		$defaultConfig = (new Mpdf\Config\ConfigVariables())->getDefaults();
		$customFontDir = DTGS_PRO_PLUGIN_DIR_PATH . '/vendor/mpdf/uploads/';
		$fontDirs = $defaultConfig['fontDir'];
		$defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults();
		$fontData = $defaultFontConfig['fontdata'];
		$format = mb_strtoupper($data['paper_size']);
		if ($format == 'AUTO') $format = 'A4';
		if ($orientation == 'L') $format = $format . '-L';
		$this->mpdf = new \Mpdf\Mpdf([
			'tempDir' => DTGS_PRO_PLUGIN_DIR_PATH . '/vendor/mpdf/uploads/',
			'fontDir' => array_merge($fontDirs, [$customFontDir]),
			'fontdata' => $fontData + $fonts,
			//'orientation' => $orientation,
			'format' => $format
		]);
		$this->mpdf->AddFontDirectory(DTGS_PRO_PLUGIN_DIR_PATH . '/vendor/mpdf/uploads/mpdf/ttfontdata/');
		$this->mpdf->simpleTables = true;
		$this->mpdf->packTableData = true;
		$this->mpdf->keep_table_proportions = TRUE;
		$this->mpdf->shrink_tables_to_fit = 1;

		@$this->mpdf->WriteHTML($htmlRes);
		$this->mpdf->Output('table.pdf','D');
	}
	public function _getFontsDir()
	{
		$uploads = wp_upload_dir();
		$basedir = $uploads['basedir'];
		$dir = plugin_dir_path( __FILE__ ) . '/supsystic-tables/fonts';
		//$dir = DTGS_PRO_PLUGIN_DIR_PATH.'vendor'.DS.'dompdf'.DS.'lib'.DS.'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'] = DIRECTORY_SEPARATOR  . 'supsystic-tables' . DIRECTORY_SEPARATOR  . '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;
	}
}
