<?php
/**
 * @package SP Page Builder
 * @author JoomShaper http://www.joomshaper.com
 * @copyright Copyright (c) 2010 - 2016 JoomShaper
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct accees
defined ('_JEXEC') or die ('restricted access');

jimport('joomla.form.formfield');

class JFormFieldPagebuilder extends JFormField
{
	protected	$type = 'Pagebuilder';

	protected function getInput()
	{
		$output = '';
		$id = (int) JFactory::getApplication()->input->get('id', 0, 'INT');
		if($id)
		{
			$hasData = $this->hasData($id);
			if($hasData)
			{
				$view_id = $hasData;
			}
			else
			{
				$data = $this->form->getData();
				$params = new Joomla\Registry\Registry($data->get('params'));
				$title = $data->get('title');
				$content = $params->get('content', '[]');
				
				if(!$this->isJson($content))
				{
					$content = '[]';
				}

				$view_id = $this->insertData($id, $title, $content);
			}

			$app = JApplication::getInstance('site');
			$router = $app->getRouter();
			$front_link = 'index.php?option=com_sppagebuilder&view=form&tmpl=component&layout=edit&extension=mod_sppagebuilder&extension_view=module&id=' . $view_id;
			$sefURI = str_replace('/administrator', '', $router->build($front_link));

			$output .= '<a class="btn btn-success btn-large" href="'. $sefURI .'" target="_blank">Edit with SP Page builder</a>';
		}
		else
		{
			$output .= '<div class="alert alert-info">Please save this module to activate Page Builder</div>';
		}

		$output .= '<style>#general .control-group .control-label {display: none;} #general .control-group .controls {margin-left: 0;}</style>';

		return $output;
	}

	private function hasData($id)
	{
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select($db->quoteName(array('id')));
		$query->from($db->quoteName('#__sppagebuilder'));
		$query->where($db->quoteName('extension') . ' = '. $db->quote('mod_sppagebuilder'));
		$query->where($db->quoteName('extension_view') . ' = '. $db->quote('module'));
		$query->where($db->quoteName('view_id') . ' = '. $db->quote($id));
		$query->order('ordering ASC');
		$db->setQuery($query);
		$result = $db->loadResult();

		return $result;
	}

	private function insertData($id, $title, $content)
	{
		$user = JFactory::getUser();
		$date = JFactory::getDate();
        $db = JFactory::getDbo();
		$page = new stdClass();
        $page->title = $title;
        $page->text = $content;
        $page->extension = 'mod_sppagebuilder';
        $page->extension_view = 'module';
        $page->view_id = $id;
		$page->published = 1;
		$page->created_by = (int) $user->id;
		$page->created_on = $date->toSql();
		$page->language = '*';
		$page->access = 1;
		$page->active = 1;

		$db->insertObject('#__sppagebuilder', $page);
		return $db->insertid();
	}

	function isJson($string)
	{
		json_decode($string);
		return (json_last_error() == JSON_ERROR_NONE);
	}
}
