<?php
/**
 * @version     $Id$
 * @author      JoomlaUX
 * @package     Joomla.Site
 * @subpackage  mod_jux_easy_megamenu
 * @copyright   Copyright (C) 2008 - 2018 JoomlaUX. All rights reserved.
 * @license     License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php
 */

define('_JEXEC', 1);

// Set the path to the Joomla root directory
define('JPATH_BASE', realpath(dirname(__FILE__) . '/../../../'));

// Include the Joomla framework
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
// require_once JPATH_BASE . '/includes/app.php';

// Boot the DI container
$container = \Joomla\CMS\Factory::getContainer();

/*
 * Alias the session service keys to the web session service as that is the primary session backend for this application
 *
 * In addition to aliasing "common" service keys, we also create aliases for the PHP classes to ensure autowiring objects
 * is supported.  This includes aliases for aliased class names, and the keys for aliased class names should be considered
 * deprecated to be removed when the class name alias is removed as well.
 */
$container->alias('session.web', 'session.web.site')
    ->alias('session', 'session.web.site')
    ->alias('JSession', 'session.web.site')
    ->alias(\Joomla\CMS\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\SessionInterface::class, 'session.web.site');

// Instantiate the application.
$app = $container->get(\Joomla\CMS\Application\SiteApplication::class);

// Set the application as global app
\Joomla\CMS\Factory::$application = $app;

// Get the Joomla application object
use Joomla\Registry\Registry;
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\CMS\Updater\Update;
use Joomla\CMS\Updater\Updater; 

// no direct access
defined('_JEXEC') or die('Restricted access');

$task = isset($_REQUEST['task']) ? $_REQUEST['task'] : false ;
if ($task){
    $adminHelper = new modJUXMegaMenuAction();
    $adminHelper->$task();
}

class modJUXMegaMenuAction {

    private $app;
    private $db;
    private $lang;

    public function __construct() {
        $this->lang = Factory::getLanguage();
        $this->app  = Factory::getApplication();
        // $this->db   = Joomla\CMS\Factory::getDbo();
    }

    public function module(){
        $lang = Factory::getLanguage();
        $lang->load('mod_jux_easy_megamenu');
        $app = Factory::getApplication();
        $input = $app->input;
        $mid = $input->getInt('mid');
        $base_url =  urldecode(trim($input->getString('base_url')));

        $module = null;
        $buffer = Text::_('MOD_JUX_EASY_MEGAMENU_MODULE_DOES_NOT_EXISTS');
        
        if ($mid){
            // load module
            $db = Factory::getDbo();
            $query = $db->getQuery(true);
            $query->select('m.id, m.title, m.module, m.position, m.content, m.showtitle, m.params');
            $query->from('#__modules AS m');
            $query->where('m.id = '.$mid);
            $query->where('m.published = 1');
            $db->setQuery($query);
            $module = $db->loadObject ();
        }

        if (!empty ($module)) {
            $buffer = '<div class="module-block">';
            $buffer .= '<div class="module-icon"><span class="fa fa-puzzle-piece"></span></div><div class="module-title">'.$module->title.'</div><div class="module-id">Module ID: '.$module->id.'</div>';
            $buffer .= '</div>';
        }   

        $buffer = preg_replace(array( '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu'), array('', ''), $buffer);

        echo $buffer;
    }

    public function reloadMenuConfig()
    {
        $app = Factory::getApplication();
        $lang = Factory::getLanguage();
        $lang->load('mod_jux_easy_megamenu');
        $input = $app->input;

        $menuType = $input->getString('menu_type');
        $cur_mod_id = $input->getInt('mod_id');
        if($menuType == null || $menuType == '')
        {
            echo json_encode(array('status' => 'Failed'));
            exit();
        }
        require_once dirname(dirname(__FILE__)).'/includes/menu/menu.php';

        if($cur_mod_id != null && $cur_mod_id != "")
        {
            $module = $this->getModuleList($cur_mod_id);
        }
        else {
            $module = new stdCLass();
            $module->params = "";
        }
        $moduleParams = new Registry($module->params);
        $joomlaMenu = new JoomlaMenu($menuType, $moduleParams, 0);
        list($menu,$option,$extraData) = $joomlaMenu->render();

        $args = array(
            'status'        => 'OK',
            'menu_layout'   => $menu,
            'menu_options'  => $option,
            'extra_data'    => $extraData,
        );

        echo json_encode($args);
        exit;
    }

    public function getModuleList($module_id)
    {
        $db = Factory::getDbo();
        $lang = Factory::getLanguage();
        $lang->load('mod_jux_easy_megamenu');
        $query = $db->getQuery(true);
        $query->select('m.id, m.title, m.module, m.position, m.content, m.showtitle, m.params');
        $query->from('#__modules AS m');
        $query->where('id = '.(int) $module_id);
        $db->setQuery($query);
        $modules = $db->loadObject();
        return $modules;
    }

    public function loadPresetStyle() {
        $jinput = Factory::getApplication()->input;
        $preset_id = $jinput->getString('preset_id', '');
        $lang = Factory::getLanguage();
        $lang->load('mod_jux_easy_megamenu');
        require_once dirname(dirname(__FILE__)).'/includes/preset.php';
        global $preset;
        $preset_data = isset($preset[$preset_id]) ? $preset[$preset_id] : '';

        $app = Factory::getApplication();
        $input = $app->input;

        $menuType = $input->getString('menu_type');
        $cur_mod_id = $input->getInt('mod_id');
        if($menuType == null || $menuType == '')
        {
            echo json_encode(array('status' => 'Failed'));
            exit();
        }
        require_once dirname(dirname(__FILE__)).'/includes/menu/menu.php';

        $initParams = new stdClass();

        if($cur_mod_id != null && $cur_mod_id != "")
        {
            $module = $this->getModuleList($cur_mod_id);
            $params = (array) json_decode($module->params, true);

            if($module->params == '') {
                $module = new stdClass();
                $module->mod_menu = $menuType;
                $module->mega_config = '';
                $module->mega_options = '';
                $module->mega_style = '';
                $module->mega_order = '';
                $module->juxtime = '';
                $module->module_tag = 'div';
                $module->bootstrap_size = '0';
                $module->header_tag = 'h3';
                $module->header_class = '';
                $module->style = '0';
                $params = (array) $module;
            }
        }
        else {
            $module = new stdClass();
            $module->mod_menu = $menuType;
            $module->mega_config = '';
            $module->mega_options = '';
            $module->mega_style = '';
            $module->mega_order = '';
            $module->juxtime = '';
            $module->module_tag = 'div';
            $module->bootstrap_size = '0';
            $module->header_tag = 'h3';
            $module->header_class = '';
            $module->style = '0';
            $params = (array) $module;
        }
            $mega_option = (array)json_decode($params['mega_options'], true);
            $mega_option[$menuType] = $preset_data['style'];
            $params['mega_options'] = json_encode($mega_option);

        $moduleParams = new Registry(json_encode($params));
        $joomlaMenu = new JoomlaMenu($menuType, $moduleParams, 0);
        list($menu,$option,$extraData) = $joomlaMenu->render();
        $args = array(
            'status'        => 'OK',
            'menu_layout'   => $menu,
            'menu_options'  => $option,
            'extra_data'    => $extraData,
        );

        echo json_encode($args);
        exit;
    }

    public function deletePresetStyle() {
        jimport( 'joomla.filesystem.file' );
        $jinput = Factory::getApplication()->input;
        $preset_id = $jinput->getString('preset_id', '');
        require_once dirname(dirname(__FILE__)).'/includes/preset.php';
        global $preset;
        $preset_data = isset($preset[$preset_id]) ? $preset[$preset_id] : '';
        $presetPath = JPATH_BASE . '/modules/mod_jux_easy_megamenu/includes/preset.php';
        $presetContent = '<?php
/**
 * @version        $Id$
 * @author        JoomlaUX
 * @package        Joomla.Site
 * @subpackage    mod_jux_easy_megamenu
 * @copyright    Copyright (C) 2008 - 2018 JoomlaUX. All rights reserved.
 * @license        License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php
 */

defined(\'_JEXEC\') or die(\'Restricted access\');

global $preset;
$preset = ';
        if(!empty($preset)) {
            if(isset($preset[$preset_id]))
                unset($preset[$preset_id]);
            $presetContent .= var_export($preset, true);
        }

$presetContent .= ';';

        if(file_exists($presetPath)) {
            File::write($presetPath, $presetContent);
        }

        echo json_encode(array('status' => 'OK'));
        exit;
    }

    public function savePresetStyle()
    {
        $jinput = Factory::getApplication()->input;
        $preset_name = $jinput->getString('preset_name', '');
        jimport('joomla.filesystem.file');
        $preset_id = $this->clean($preset_name);
        $cur_time = strtotime("now");
        require_once dirname(dirname(__FILE__)) . '/includes/preset.php';
        global $preset;
        $presetPath = JPATH_BASE . '/modules/mod_jux_easy_megamenu/includes/preset.php';
        $presetContent = '<?php
/**
 * @version        $Id$
 * @author        JoomlaUX
 * @package        Joomla.Site
 * @subpackage    mod_jux_easy_megamenu
 * @copyright    Copyright (C) 2008 - 2018 JoomlaUX. All rights reserved.
 * @license        License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php
 */

defined(\'_JEXEC\') or die(\'Restricted access\');

global $preset;
$preset = ';
        $preset_file_id = $preset_id . '-' . $cur_time;
        if (isset($preset[$preset_file_id])){
            $cur_time = +1;
            $preset_file_id = $preset_id . '-' . $cur_time;
        }

        $option_data = (array) json_decode($jinput->getString('option_data', ''), true);
        $preset[$preset_file_id] = array(
            'name' => $preset_name,
            'style' => $option_data,
        );
        $presetContent .= var_export($preset, true);

        $presetContent .= ';';

        if(file_exists($presetPath)) {
            File::write($presetPath, $presetContent);
        }
        $preset_item = '<li>
                        <a class="jux-menu-apply-preset-style" href="#" data-id="'.$preset_file_id.'">'.$preset_name.'</a>
                        <span class="jux-menu-del-preset-style" data-id="'.$preset_file_id.'" data-toggle="tooltip" title="Delete preset"></span>
                    </li>';
        echo json_encode(array('status' => 'OK', 'item' => $preset_item));
        exit;
    }

    function clean($string) {
        $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

        return strtolower(preg_replace('/[^a-zA-Z0-9\-]/', '', $string)); // Removes special chars.
    }
}
