<?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;

//jimport('joomla.event.dispatcher');

use Joomla\Registry\Registry;
use Pagebuilderck\CKModel;
use Pagebuilderck\CKFof;

class PagebuilderckModelStyle extends CKModel {

	protected $table = '#__pagebuilderck_styles';

	var $item = null;

	private $stylecode = '';

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

	/**
	 * Method to get an ojbect.
	 *
	 * @param	integer	The id of the object to get.
	 *
	 * @return	mixed	Object on success, false on failure.
	 */
	public function getItem($id = 0) {
		if (empty($this->item)) {
			$id = $this->input->get('id', $id, 'int');
			$this->item = CKFof::dbLoad($this->table, $id);
		}

		// transform params to JRegistry object
		// if (isset($this->item->params)) $this->item->params = new JRegistry($this->item->params);

		$this->item->htmlcode = str_replace("|URIROOT|", JUri::root(true), $this->item->htmlcode);
		return $this->item;
	}

	/**
	 * Method to save the page.
	 *
	 * @param	array		The form data.
	 * @return	mixed		The id on success, false on failure.
	 */
	public function save($data) {
		$id = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('style.id');
		$user = CKFof::getUser();
		$date = JFactory::getDate();

		// if (isset($data['options']) && is_array($data['options']))
		// {
			// $registry = new Registry;
			// $registry->loadArray($data['options']);
			// $data['params'] = (string) $registry;
		// }

		if ($id) {
			//Check the user can edit this item
			$authorised = $user->authorise('core.edit', 'style.' . $id);
		} else {
			//Check the user can create new items in this section
			$authorised = $user->authorise('core.create', 'com_pagebuilderck');
			$data['created'] = $date->toSql();
		}

		if ($authorised !== true) {
			throw new Exception(JText::_('JERROR_ALERTNOAUTHOR'), 403);
			return false;
		}

		// save the date
		$data['modified'] = $date->toSql();
		// make a backup before save
		// PagebuilderckHelper::makeBackup($this->getItem());

		$data['stylecode'] = $this->getStylesFromHtml($data['htmlcode']);
//var_dump($data['stylecode']);die;
		$pageid = CKFof::dbStore($this->table, $data);
		return $pageid;
	}

	public function getElements() {
		$model = CKFof::getModel('elements');
		return $model->getItems();
	}

	private function getStylesFromHtml($htmlcode) {
		$regexStyle = "#<div\s[^>]*ckstyleresponsive([^\"]*)\"[^>]*>(.*)<\/div>#siU"; // replace all divs with class ckstyleresponsive
		$htmlcode = preg_replace_callback($regexStyle, array($this, 'replaceResponsiveStyleTag'), $htmlcode);

		$regexStyle = "#<div\s[^>]*ckstyle([^\"]*)\"[^>]*>(.*)<\/div>#siU"; // replace all divs with class ckstyle
		$htmlcode = preg_replace_callback($regexStyle, array($this, 'replaceStyleTag'), $htmlcode);

		$regexStyle2 = "#<style\s[^>]*ckcolumnwidth([^\"]*)\"[^>]*>(.*)<\/style>#siU"; // replace all divs with class ckcolumnwidth
		$htmlcode = preg_replace_callback($regexStyle2, array($this, 'replaceResponsiveStyleTag'), $htmlcode);

		return trim($this->stylecode);
	}

	public function replaceResponsiveStyleTag($matches) {
		if (!$matches[2]) return;
		$styleTag = trim($matches[2]);
		$styleTag = str_replace('<style>', '', $styleTag);
		$styleTag = str_replace('<style type="text/css">', '', $styleTag);
		$styleTag = str_replace('</style>', '', $styleTag);
		$styleTag = str_replace('&nbsp;', ' ', $styleTag);
		$styleTag = str_replace('<style wfd-invisible="true">', ' ', $styleTag);

		if ($styleTag) {
			if (stristr($matches[1], 'ckresponsiverange4')) {
				$this->responsiveStyleTags4 .= str_replace('.ckresponsiveactive[ckresponsiverange="4"] ', '', $styleTag);
				$this->responsiveStyleTags4 .= str_replace('.ckresponsiveactive[ckresponsiverange*="4"] ', '', $styleTag);
			} else if (stristr($matches[1], 'ckresponsiverange3')) {
				$this->responsiveStyleTags3 .= str_replace('.ckresponsiveactive[ckresponsiverange="3"] ', '', $styleTag);
				$this->responsiveStyleTags3 .= str_replace('.ckresponsiveactive[ckresponsiverange*="3"] ', '', $styleTag);
			} else if (stristr($matches[1], 'ckresponsiverange2')) {
				$this->responsiveStyleTags2 .= str_replace('.ckresponsiveactive[ckresponsiverange="2"] ', '', $styleTag);
				$this->responsiveStyleTags2 .= str_replace('.ckresponsiveactive[ckresponsiverange*="2"] ', '', $styleTag);
			} else if (stristr($matches[1], 'ckresponsiverange1')) {
				$this->responsiveStyleTags1 .= str_replace('.ckresponsiveactive[ckresponsiverange="1"] ', '', $styleTag);
				$this->responsiveStyleTags1 .= str_replace('.ckresponsiveactive[ckresponsiverange*="1"] ', '', $styleTag);
			} else if (stristr($styleTag, 'ckresponsiverange="4"')) {
				$this->responsiveStyleTags4 .= str_replace('[ckresponsiverange="4"] ', '', $styleTag);
				$this->responsiveStyleTags4 .= str_replace('[ckresponsiverange*="4"] ', '', $styleTag);
			} else if (stristr($styleTag, 'ckresponsiverange="3"')) {
				$this->responsiveStyleTags3 .= str_replace('[ckresponsiverange="3"] ', '', $styleTag);
				$this->responsiveStyleTags3 .= str_replace('[ckresponsiverange*="3"] ', '', $styleTag);
			} else if (stristr($styleTag, 'ckresponsiverange="2"')) {
				$this->responsiveStyleTags2 .= str_replace('[ckresponsiverange="2"] ', '', $styleTag);
				$this->responsiveStyleTags2 .= str_replace('[ckresponsiverange*="2"] ', '', $styleTag);
			} else if (stristr($styleTag, 'ckresponsiverange="1"')) {
				$this->responsiveStyleTags1 .= str_replace('[ckresponsiverange="1"] ', '', $styleTag);
				$this->responsiveStyleTags1 .= str_replace('[ckresponsiverange*="1"] ', '', $styleTag);
			} else {
				if ($styleTag) $this->stylecode .= $styleTag;
			}
		}
		return '';
	}

	/*
	 * @param array the matching strings
	 * 
	 * return the module cdoe
	 */
	public function replaceStyleTag($matches) {

		if (!$matches[2]) return;
		$styleTag = trim($matches[2]);
		$styleTag = str_replace('<style>', '', $styleTag);
		$styleTag = str_replace('<style type="text/css">', '', $styleTag);
		$styleTag = str_replace('</style>', '', $styleTag);
		$styleTag = str_replace('&nbsp;', ' ', $styleTag);
		$styleTag = str_replace('<style wfd-invisible="true">', '', $styleTag);

		$pagebuilderckParams = JComponentHelper::getParams('com_pagebuilderck');
		// check for the image path, and fix it
		if (strpos($styleTag, 'url(\'/')) {
			if ((int)$pagebuilderckParams->get('image_path_fix', 0, 'int') === 1) {
				$find = "# url\('/(.*?)\'\)#si"; // masque de recherche pour le tag
				$styleTag = preg_replace($find, ' url(\'' . JUri::root(true) . '/$1\')' , $styleTag);
			}
		}

		// if ($styleTag) $this->styleTags .= $styleTag;

		// return '';
		$this->stylecode .= $styleTag;
	}
}