<?php
/**
 * @name		Page Builder CK
 * @package		com_pagebuilderck
 * @copyright	Copyright (C) 2015. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 * @author		Cedric Keiflin - https://www.template-creator.com - https://www.joomlack.fr
 */

// No direct access.
defined('_JEXEC') or die;

use Pagebuilderck\CKController;
use Pagebuilderck\CKFof;

class PagebuilderckControllerFonts extends CKController {

	protected $imagespath;

	function __construct() {
		parent::__construct();
	}

	/**
	 * Load the needed interface
	 * 
	 * @return void
	 */
	/*public function load() {
		// security check
		CKFof::checkAjaxToken();

		$layout = $this->input->get('layout', '', 'cmd');
		if (! $layout) return;

//		$this->interface = new CKInterface();
		$this->imagespath = PAGEBUILDERCK_MEDIA_URI . '/images/menustyles/';

		require_once(PAGEBUILDERCK_PATH . '/interfaces/' . $layout . '.php');
		exit;
	}*/

	/**
	 * Save the font in the BDD and store the files locally if needed
	 * 
	 * @return void
	 */
	public function save() {
		// security check
		CKFof::checkAjaxToken();

		// only store the font files locally if local is 1
		$local = $this->input->get('local', '', 'int');
		if ($local === 1) {
			$variants = $this->input->get('fontvars', '', 'string');
			$url = $this->input->get('url', '', 'string');
			$url = str_replace('http:', 'https:', $url);
			if (! $url) {
				echo '{"status" : "0", "msg" : "No url given"}';
				exit;
			}

			$fontname = $this->input->get('fontname', '', 'string');
			if (! $fontname) {
				echo '{"status" : "0", "msg" : "No font name given"}';
				exit;
			}

			$gfontFolderPath = PAGEBUILDERCK_MEDIA_PATH . '/gfonts/';
			// create fonts folder
			if (!JFolder::exists($gfontFolderPath)) {
				if (!JFolder::create($gfontFolderPath)) {
					// $msg = '<p class="errorck">' . JText::_('CK_ERROR_CREATING_FOLDER') . ' /fonts</p>';
				} else {
					// $msg = '<p class="successck">' . JText::_('CK_SUCCESS_CREATING_FOLDER') . ' /fonts</p>';
				}
				// $messages[] = $msg;
			}

			// check if file exists
			$filePath = $gfontFolderPath . $fontname . '.css';

			// get the file from url
			set_time_limit(0);

			if (extension_loaded('curl')) {
				try {
					$ch = curl_init();  
					$timeout = 30;  
					curl_setopt($ch, CURLOPT_URL, $url);  
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
					curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
					curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

					$file = curl_exec($ch);  
					if($file === false)
					{
						echo '{"status" : "0", "msg" : "Curl error: ' . curl_error($ch) . '"}';
						// echo 'Curl error: ' . curl_error($ch);
					}
					else
					{
						// echo 'Operation completed without any errors';
					}
					curl_close($ch);  
				} catch (Exception $e) {
				// echo 'Exception : ',  $e->getMessage(), "\n";
				echo '{"status" : "0", "msg" : "' . $e->getMessage() . '"}';
				exit;
				}
			} else {
				try {
					$file = file_get_contents(urldecode($url));
				} catch (Exception $e) {
					// echo 'Exception : ',  $e->getMessage(), "\n";
					echo '{"status" : "0", "msg" : "' . $e->getMessage() . '"}';
					exit;
				}
			}

			// store the file locally
			$result = file_put_contents($filePath, $file);
			if (! $result) {
				echo '{"status" : "0", "file" : "", "msg" : "Error on file creation"}';
				exit();
			}

			// download the ttf files
			$filesize = 0;
			preg_match_all('/url\((.*?)\)/', $file, $matches);
			if (isset($matches[0]) && ! empty($matches[1])) {
				if (is_array($matches[1])) {
					foreach($matches[1] as $fontfile) {
						try {
							$ch = curl_init();  
							$timeout = 30;  
							curl_setopt($ch, CURLOPT_URL, $fontfile);  
							curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
							curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
							curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
							curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
							curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

							$ttffile = curl_exec($ch);  
							if($ttffile === false)
							{
								echo '{"status" : "0", "msg" : "Curl error: ' . curl_error($ch) . '"}';
							}
							else
							{
								// echo 'Operation completed without any errors';
							}
							curl_close($ch);  
						} catch (Exception $e) {
							echo '{"status" : "0", "msg" : "' . $e->getMessage() . '"}';
							exit;
						}
						$filename = explode('/', $fontfile);
						$filename = end($filename);
						$filePath = $gfontFolderPath . $filename;
						$result = file_put_contents($filePath, $ttffile);
						if (! $result) {
							echo '{"status" : "0", "file" : "", "msg" : "Error on file creation"}';
							exit();
						}
						$filesize += filesize($filePath);
					}
				}
			}

			$model = $this->getModel();
			$result = $model->saveFont($fontname, $url, $local, $filesize, $variants);

			if ($result) {
				echo '{"status" : "1", "file" : "' . $fontname . '.css' . '", "filesize" : "' . $filesize . '"}';
			} else {
				echo '{"status" : "0", "file" : "' . $fontname . '.css' . '", "filesize" : "' . $filesize . '"}';
			}
		} else {
			$model = $this->getModel();
			$result = $model->saveFont($fontname, $url, $local, $filesize, $variants);

			if ($result) {
				echo '{"status" : "1", "file" : "", "filesize" : ""}';
			} else {
				echo '{"status" : "0", "file" : "", "filesize" : ""}';
			}
		}
		exit;
	}

	public function delete() {
		// security check
		CKFof::checkAjaxToken();

		$fontname = $this->input->get('fontname', '', 'string');
		$fontname = str_replace(' ', '+', $fontname);
		$model = $this->getModel();
		$result = $model->delete($fontname);
		if ($result) {
			echo '{"status" : "1", "msg" : ""}';
		} else {
			echo '{"status" : "0", "msg" : "' . $result . '"}';
		}
		exit;
	}
}