<?php

/**
 *
 * @extension       T-Marlev
 * @author          Lev Milicenco<support@marlev.it>
 * @link            http://www.marlev.it
 * @copyright       Copyright 2014 marlev.it All Rights Reserved
 * @license         http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

namespace Marlev\Component\Tmarlevv2\Administrator\Controller;
require_once JPATH_ROOT . '/administrator/components/com_tmarlevv2/src/Helper/loader.php';

use Joomla\CMS\MVC\Controller\FormController;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Filter\InputFilter;
use Joomla\CMS\Uri\Uri;

use Joomla\Registry\Registry;
//for_use


defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Cache\Cache;
use Marlev\Component\Tmarlevv2\Administrator\Helper\layout_presaved;
use Marlev\Component\Tmarlevv2\Administrator\Helper\posconfig_transfer;
use Marlev\Component\Tmarlevv2\Administrator\Helper\saveLayout;
class TemplateController extends FormController
{
    public $template;

    protected function get_form()
    {

        if (!Session::checkToken('get')) {
            Factory::getApplication()->redirect(Uri::base() . 'index.php', Text::_('JINVALID_TOKEN'));
            return false;
        }

        if (!Factory::getApplication()->getIdentity()->authorise('core.manage', 'com_templates')) {
            Factory::getApplication()->redirect(Uri::base() . 'index.php', Text::_('JERROR_ALERTNOAUTHOR'));
            return false;
        }

        $input = Factory::getApplication()->input;
        // $layout = $input->get('postdata');
        $layout = $input->get('postdata', '', 'RAW');
        $explode = explode("{{-|-}}", $layout);


        // fix max_inpup_vars
        $output = array();
        $result = array();
        foreach ($explode as $key) {
            parse_str($key, $output);
            $result = array_merge_recursive($result, $output);
        }
        return $result;
    }

    public function apply()
    {

        $result = $this->get_form();
        if ($result == false) {
            exit();
        }
        $filter = new InputFilter();

        $id = $filter->clean($result["params"]['id'], "INT");
        $activemenu = $filter->clean($result["params"]['active_menu'], "STRING");
        $this->save_apply($result);
        $this->redirectToMenu($activemenu, $id);
    }

    public function save($key = NULL, $urlVar = NULL)
    {
        $result = $this->get_form();
        if ($result == false) {
            exit();
        }
        $this->save_apply($result);
        $this->setRedirect(Uri::base() . "index.php?option=com_templates");
    }

    public function cancel($key = NULL, $urlVar = NULL)
    {
        $this->setRedirect(Uri::base() . "index.php?option=com_templates");
    }

    public function clearcache($template = false)
    {
        if ($template != false) {
            $this->template = preg_replace("$[^a-zA-Z0-9]$", "", $template);
            $this->clean_templatecache($this->template, false);
        } else {
            $result = $this->get_form();
            if ($result == false) {
                exit();
            }
            $filter = new InputFilter();
            $this->template = $filter->clean($result['params']['template'], "STRING");
            $this->clean_templatecache($this->template, true);
        }

    }

    function exportposconfig()
    {
        $data = $this->get_form();
        $input = Factory::getApplication()->input;
        $tmconfig = $input->get("jsondata", "", false);
        $getter = json_decode($tmconfig);
        $layout = $data['layout'];
        $presaved = new posconfig_transfer($getter, $layout);
        $layout = $presaved->assigner();
    }

    function updatelife()
    {
        $data = $this->get_form();
        $input = Factory::getApplication()->input;
        $hash = $input->getString("hashdata", false);
        $filter = new InputFilter();
        // Get posted data
        $layout = $data['layout']; //$this->input->post->get('layout', array(), 'array');
        $customcss = $data['customcss']; //$this->input->post->getString('customcss');
        $customjs = $data['customjs']; //$this->input->post->getString('customjs');
        $assigned = false;

        if (isset($data['jform'])) {
            $assigned = $data['jform']; //$this->input->post->get('jform', array(), 'array');
        }

        $id = $filter->clean($data['params']['id'], "INT");
        $this->template = $filter->clean($data['params']['template'], "STRING"); //$this->input->post->getString("template");

        $allowhtml = InputFilter::getInstance(array(), array(), 1, 1, 0);
        $html_texts = array();
        $langs = $this->getLangs();

        foreach ($langs as $lang) {
            foreach (array("offlinetext", "errortext") as $key => $valu) {
                $html_texts[$valu . '_' . $lang->lang_code] = $valu . '_' . $lang->lang_code;
            }
        }


        $load = array();
        foreach ($data['params'] as $key => $value) {
            switch ($key) {
                case 'title':
                    $title = $filter->clean($value, "STRING");
                    break;
                case 'home':
                    $home = $filter->clean($value, "STRING");
                    break;
                case 'socialpositions':
                    $load[$key] = $value; //(string) $registry;
                    break;
                default:
                    if (is_array($value)) {
                        $load[$key] = $value;
                    } else {
                        if (array_key_exists($key, $html_texts)) {
                            $load[$key] = $allowhtml->clean($value, "HTML");
                        } else {
                            $value = trim($value);
                            $load[$key] = $filter->clean($value, "STRING");
                        }
                    }
            }
        }

        //find templatecss array and pass to a template

        $presaved = new layout_presaved($id, $layout);
        $layout = $presaved->assigner();
        $layout_exist = true;
        require_once JPATH_SITE . '/templates/' . $this->template . '/lib/css.php';
        $templatecss = new marlev_templatecss($id, $this->template, $layout, $load);
        $get_names = $templatecss->get_names();
        $templatecss_names = array();
        foreach ($get_names as $k) {
            if (isset($load[$k])) {
                $templatecss_names[$k] = $load[$k];
            }
        }
        $additional_css = $templatecss->write_tocss($templatecss_names);


        //esclusione layout del template da yrminifier
        $template_layout = $this->template . "/css/layouts/" . $this->template . "-" . $id . '.css';
        if (!isset($load['yrminifiercss_esclude']) || !in_array($template_layout, $load['yrminifiercss_esclude'])) {
            $load['yrminifiercss_esclude'][] = $template_layout;
        }
//        if (!isset($load['yrminifiercss_esclude']) || !in_array('media/system/css/joomla-fontawesome.min.css', $load['yrminifiercss_esclude'])) {
//            $load['yrminifiercss_esclude'][] = 'media/system/css/joomla-fontawesome.min.css';
//        }
        $sender = array();
        $registry = new Registry;
        $registry->loadArray($load);
        $sender['params'] = (string)$registry;

        $lay_registry = new Registry;
        $lay_registry->loadArray($layout);
        $sender["layout"] = (string)$lay_registry;

        $make_css = new saveLayout($id, $layout, $this->template);
        $sender['css'] = $make_css->prepare_layout_css($additional_css, $load['font']);
        $result = json_encode($sender);

        $options = array('lifetime' => 10080, 'caching' => true);
        $cache = Cache::getInstance('callback', $options);
        $cache->setCaching(true);
        $cache->store("null", "null", "marlev_lifemode");
        file_put_contents(JPATH_ADMINISTRATOR . "/cache/marlev_lifemode/" . $hash . ".php", '<?php die("Access Denied"); ?>' . PHP_EOL . $result);
    }

    protected function save_apply($output)
    {

        $filter = new InputFilter();
        $data = $output['params']; //$this->input->post->get('params', array(), 'array');
        $data['custom_version'] = substr(md5(rand(0, 999999) . time()), 0, 25);

        // Get posted data
        $layout = $output['layout']; //$this->input->post->get('layout', array(), 'array');
        $ultimateinstall = $output['ultimateinstall'];
        $customcss = $output['customcss']; //$this->input->post->getString('customcss');
        $customjs = $output['customjs']; //$this->input->post->getString('customjs');
        $assigned = false;

        if (isset($output['jform'])) {
            $assigned = $output['jform']; //$this->input->post->get('jform', array(), 'array');
        }

        $id = $filter->clean($output['params']['id'], "INT");
        $this->template = $filter->clean($output['params']['template'], "STRING"); //$this->input->post->getString("template");

        if (empty($data["title"])) {
            Factory::getApplication()->enqueueMessage('Titolo &egrave; richiesto', 'warning');
            $this->redirectToMenu("tm-base", $id);
            return false;
        }

        $allowhtml = InputFilter::getInstance(array(), array(), 1, 1, 0);
        $html_texts = array();
        $langs = $this->getLangs();

        foreach ($langs as $lang) {
            foreach (array("offlinetext", "errortext") as $key => $valu) {
                $html_texts[$valu . '_' . $lang->lang_code] = $valu . '_' . $lang->lang_code;
            }
        }


        $load = array();
        foreach ($data as $key => $value) {
            switch ($key) {
                case 'title':
                    $title = $filter->clean($value, "STRING");
                    break;
                case 'home':
                    $home = $filter->clean($value, "STRING");
                    break;
                case 'socialpositions':
                    // $registry = new Registry;
                    // $registry->loadArray($value);
                    $load[$key] = $value; //(string) $registry;
                    break;
                default:
                    if (is_array($value)) {
                        $load[$key] = $value;
                    } else {
                        if (array_key_exists($key, $html_texts)) {
                            $load[$key] = $allowhtml->clean($value, "HTML");
                        } else {
                            $value = trim($value);
                            $load[$key] = $filter->clean($value, "STRING");
                        }
                    }
            }
        }

        //find templatecss array and pass to a template
        $layout_exist = false;
        if (file_exists(JPATH_SITE . '/templates/' . $this->template . '/lib/css.php')) {
            $presaved = new layout_presaved($id, $layout);
            $layout = $presaved->assigner();
            $layout_exist = true;
            require_once JPATH_SITE . '/templates/' . $this->template . '/lib/css.php';
            $templatecss = new \marlev_templatecss($id, $this->template, $layout, $load);
            $get_names = $templatecss->get_names();
            $templatecss_names = array();
            foreach ($get_names as $k) {
                if (isset($load[$k])) {
                    $templatecss_names[$k] = $load[$k];
                }
            }
            $additional_css = $templatecss->write_tocss($templatecss_names);
        }


        //Loaded css template file
        $template_layout = $this->template . "/css/layouts/" . $this->template . "-" . $id . '.css';
        $load['template_css'] = $template_layout;
        //esclusione layout del template da yrminifier
        //todo
//        $template_layout = $this->template . "/css/layouts/" . $this->template . "-" . $id . '.css';
        /*  if (!isset($load['yrminifiercss_esclude']) || !in_array('media/system/css/joomla-fontawesome.min.css', $load['yrminifiercss_esclude'])) {
              $load['yrminifiercss_esclude'][] = 'media/system/css/joomla-fontawesome.min.css';

          }*/
        //fine esclusione
        $tid = $this->check_exist_template();
        $load = $this->update_keys($load, $tid);

        $load = $this->update_cookie_pageerror($load, $tid);
        $registry = new Registry;
        $registry->loadArray($load);
        $params = (string)$registry;

        $sql = new \stdClass();
        $sql->id = $id;
        $sql->title = $title;
        $sql->params = $params;

        $result = Factory::getDbo()->updateObject('#__template_styles', $sql, 'id');

        if ($result) {
            $this->setHome($home, $id);
            if ($layout_exist) {
                $make_layout = new saveLayout($id, $layout, $this->template);
                $make_layout->setLayout($additional_css, $load['font']);
            } else {
                $make_layout = new saveLayout($id, array(), $this->template);
                $make_layout->setLayout(false, false);
            }

            $this->setAssigned($assigned, $id);
            $this->enable_yrvote($data);


            $css = $filter->clean($customcss, "STRING");
            $this->write_custom_css($css, $this->template);
            $js = $filter->clean($customjs, "STRING");
            $this->write_custom_js($js, $this->template);
            if ($ultimateinstall == 1) {
                Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_INSTALATION_IN_PROGRESS_DONE"), 'message');
            } else {
                Factory::getApplication()->enqueueMessage('Modifiche Salvate', 'message');
            }
        } else {
            Factory::getApplication()->enqueueMessage('Errore durante il salvatagio dei dati', 'warning');
        }

        $this->clean_templatecache($this->template);
    }

    protected function write_custom_css($css, $template)
    {
        $custom_css = JPATH_SITE . "/templates/" . $template . "/custom/css.css";

        if (file_exists($custom_css)) {
            file_put_contents($custom_css, $css);
        } else {
            Factory::getApplication()->enqueueMessage('File non esiste ' . $custom_css, 'notice');
        }
    }

    protected function write_custom_js($js, $template)
    {
        $custom_js = JPATH_SITE . "/templates/" . $template . "/custom/js.js";

        if (file_exists($custom_js)) {
            file_put_contents($custom_js, $js);
        } else {
            Factory::getApplication()->enqueueMessage('File non esiste ' . $custom_js, 'notice');
        }
    }

    protected function setAssigned($assigned, $templateid)
    {
        $user = Factory::getUser();

        if ($user->authorise('core.edit', 'com_menus')) {

            $db = Factory::getDbo();

//            $query = $db->getQuery(true)
//                ->update('#__menu')
//                ->set('template_style_id = ' . 0)
//                ->where('template_style_id = ' . (int)$templateid);
//            $db->setQuery($query);
//            $db->execute();
            if (!empty($assigned["assigned"]) && is_array($assigned["assigned"])) {
                ArrayHelper::toInteger($assigned["assigned"]);
                $query = $db->getQuery(true)
                    ->update('#__menu')
                    ->set('template_style_id = ' . (int)$templateid)
                    ->where('id IN (' . implode(',', $assigned["assigned"]) . ')')
                    ->where('template_style_id != ' . (int)$templateid);
                //->where('checked_out IN (0,' . (int)$user->id . ')');
                $db->setQuery($query);
                $db->execute();
            }
        }
    }

    protected function setHome($home, $id = 0)
    {
        $user = Factory::getUser();
        $db = Factory::getDbo();

        // Access checks.
        if (!$user->authorise('core.edit.state', 'com_templates')) {
            throw new Exception(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
        }

        $db->setQuery(
            'UPDATE #__template_styles' .
            ' SET home = \'0\'' .
            ' WHERE client_id = ' . (int)0 .
            ' AND home = ' . $db->Quote($home)
        );
        $db->execute();

        // Set the new home style.
        $db->setQuery(
            'UPDATE #__template_styles' .
            ' SET home = ' . $db->Quote($home) .
            ' WHERE id = ' . (int)$id
        );
        $db->execute();
        return true;
    }

    //funzioni per presets
    function loadpresets()
    {
        $array = $this->get_form();
        $id = $array["ajax_return"];
        ArrayHelper::toInteger($array['delete_preset']);
        $presets = $array['delete_preset'];

        $n = count($presets);

        if ($n > 1) {
            Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_SELECT_ONLY_ONE_PRESET"), 'error');
            $this->redirectToMenu("tm-presets", $id);
            return;
        }

        ArrayHelper::toInteger($presets);
        $result = $this->loadpresets_styles($presets[0], $id);
        $result1 = $this->loadpresets_layout($presets[0], $id);
        if ($result && $result1) {
            Factory::getApplication()->enqueueMessage('<span class="reload-page">' . Text::_("COM_TMARLEV_PRESET_UPLOADED") . '</span></br>' . Text::_("COM_TMARLEV_PRESET_UPLOADED_2"), 'message');
            $this->redirectToMenu("tm-presets", $id, true);
        } else {
            Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_PRESET_UPLOAD_ERROR"), 'error');
            $this->redirectToMenu("tm-presets", $id);
        }
    }

    function loadpresets_styles($pid, $id)
    {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.params');
        $query->from('#__tmarlevv2_presets AS a');
        $query->where('a.pid=' . $db->Quote($pid));
        $db->setQuery($query);
        $load_params = $db->loadResult();
        $params = str_replace("(|cambio_id|)", $id, $load_params);
        $object = new \stdClass();
        $object->id = $id;
        $object->params = $params;
        $result = Factory::getDbo()->updateObject('#__template_styles', $object, 'id');
        return $result;
    }

    function loadpresets_layout($pid, $id)
    {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.params');
        $query->from('#__tmarlevv2_layoutpresets AS a');
        $query->where('a.pid=' . $db->Quote($pid));
        $db->setQuery($query);
        $load = $db->loadResult();

        $object1 = new \stdClass();
        $object1->layout = $load;
        $check_exist = $this->check_exist_layout($id);
        if ($check_exist > 0) {
            $object1->id = $check_exist;
            $result1 = Factory::getDbo()->updateObject('#__tmarlevv2_layout', $object1, 'id');
        } else {
            $object1->tid = $id;
            $result1 = Factory::getDbo()->insertObject('#__tmarlevv2_layout', $object1);
        }
        return $result1;
    }

    function reloadpresets()
    {
        $id = $this->input->get->getInt("id");
        $session = Factory::getSession();
        $new = array();
        $new['presets-installed'][] = Text::_("COM_TMARLEV_PRESET_INSTALLED");
        $message = json_encode($new);
        $session->set('marlev_install_message', $message);
        //$session->set('marlev_install_message');

        $this->redirectToMenu("tm-presets", $id, true);
    }

    function cancellpresets()
    {

        if (!Session::checkToken('get')) {
            Factory::getApplication()->enqueueMessage(Text::_('JINVALID_TOKEN'), 'error');
            $this->setRedirect(Uri::base() . "index.php");
        }
        if (!Factory::getUser()->authorise('core.manage', 'com_templates')) {
            Factory::getApplication()->enqueueMessage(Text::_('JERROR_ALERTNOAUTHOR'), 'error');
            $this->setRedirect(Uri::base() . "index.php");
        }

        $array = $this->get_form();
        $id = $array["ajax_return"];
        ArrayHelper::toInteger($array['delete_preset']);
        $preset = implode(',', $array['delete_preset']);
        if (empty($preset)) {
            Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_SELECT_ONE_OR_MORE_PRESETS"), 'error');
            $this->redirectToMenu("tm-presets", $id);
            return;
        }

        function remove_preset_fromdb($preset, $table)
        {
            $return = true;
            $db = Factory::getDbo();
            $query = $db->getQuery(true);
//            $conditions = array(
//                $db->quoteName('pid') . ' IN (' . $preset . ')'
//                //$query->where('a.catid IN (' . $categoryId . ')');
//            );
            $query->delete($db->quoteName('#__tmarlevv2_' . $table));
            $query->where('pid IN (' . $preset . ')');
            //$query->where($conditions);
            $db->setQuery($query);
            $result = $db->execute();
//            $db = Factory::getDbo();
//            $query = 'DELETE FROM #__tmarlevv2_' . $table
//                    . ' WHERE pid IN ( ' . $db->escape($preset) . '  )';
//            $db->setQuery($query);
            if (!$result) {
                $return = false;
            }
            return $return;
        }

        $presets = remove_preset_fromdb($preset, "presets");
        $layoutpresets = remove_preset_fromdb($preset, "layoutpresets");
        if ($presets && $layoutpresets) {
            Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_PRESET_DELETED"), 'message');
            $this->redirectToMenu("tm-presets", $id);
        } else {
            Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_PRESET_DELETE_FAIL"), 'error');
            $this->redirectToMenu("tm-presets", $id);
        }
    }

    function savepresets()
    {
        $output = $this->get_form();

        $filter = new InputFilter();
        $data = $output['params'];
        $layout_load = $output['layout'];
        $id = $filter->clean($output['params']['id'], "INT");

        $template = $filter->clean($output['params']['template'], "STRING");
        $preset_title = $filter->clean($output['presets_name'], "STRING");
        $data['id'] = "(|cambio_id|)";

        if (empty($preset_title)) {
            Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_TITLE_PRESETS_REQUIRED"), 'warning');
            $this->redirectToMenu("tm-presets", $id);
        } else {
            $load = array();
            foreach ($data as $key => $value) {
                switch ($key) {
                    case 'title':
                        break;
                    case 'home':
                        break;
                    default:
                        $load[$key] = $filter->clean($value, "STRING");
                }
            }

            $prepare_rand = rand(0, 999999999);
            $pid = substr($prepare_rand, 0, 9);

            $registry = new Registry;
            $registry->loadArray($load);
            $params = (string)$registry;

            $sql = new \stdClass();
            $sql->title = $preset_title;
            $sql->template = $template;
            $sql->created = date('Y-m-d H:i:s');
            $sql->params = $params;
            $sql->pid = $pid;
            $result = Factory::getDbo()->insertObject('#__tmarlevv2_presets', $sql);
            if (isset($output['layout'])) {
                unset($output);
                $presaved = new layout_presaved($id, $layout_load);
                $layout_load = $presaved->assigner();
                $backup_layout = new saveLayout($pid, $layout_load);
                $run_backup_layout = $backup_layout->backupLayout();
            } else {
                $run_backup_layout = true;
            }
            if ($result && $run_backup_layout) {
                Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_PRESET_SAVED_OK"), 'message');
            } else {
                Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_PRESET_SAVED_FAIL"), 'warning');
            }
        }
        $this->redirectToMenu("tm-presets", $id);
    }

    protected function redirectToMenu($menu, $id, $install = false)
    {
        $install_type = "";
        if ($install != false) {
            $install_type = "&installtype=installpreset";
        }
        $session = Factory::getSession();
        $session->set('activemenu', $menu);

        $this->setRedirect(Uri::base() . "index.php?option=com_tmarlevv2&view=template&id=" . $id . $install_type);
    }

    protected function enable_yrvote($data)
    {

        $yrvote = (int)$this->validate_field("enable_yrvote", $data);
        $yrminifier = (int)$this->validate_field("enable_yrminifier", $data);
        $disablejoomlavote = (int)$this->validate_field("disablejoomlavote", $data);

        // if (($yrvote == 1 || $disablejoomlavote == 1) || $yrminifier == 1) {

        // Access checks.
        $user = Factory::getUser();
        if (!$user->authorise('core.edit.state', 'com_templates')) {
            throw new Exception(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
        }
        // echo "disa ". $disablejoomlavote;exit();
        // if($disablejoomlavote == 1) {

        $db = Factory::getDbo();
        $db->setQuery(
            'UPDATE #__extensions' .
            ' SET enabled = 0' .
            ' WHERE element = "vote"');
        $db->execute();
        // }
        $db = Factory::getDbo();
        $db->setQuery(
            'UPDATE #__extensions' .
            ' SET enabled = ' . $yrvote .
            ' WHERE element = "yrvote"');
        $db->execute();

        $db->setQuery(
            'UPDATE #__extensions' .
            ' SET enabled = ' . $yrminifier .
            ' WHERE element = "yrminifier"');
        $db->execute();
        return true;

    }

    protected function validate_field($field, $data)
    {
        if (isset($data[$field]))
            return $data[$field];
        else
            return false;
    }

    protected function update_keys($load, $tid)
    {
        $keys = array();
        foreach ($load as $k => $value) {
            if ($k == "private_key" || $k == "product_key")
                $keys[$k] = trim($value);
            //unset($load[$k]);
        }

        $registry = new Registry;
        $registry->loadArray($keys);
        $keys = (string)$registry;

        $update = new \stdClass();
        $update->template = $this->template;
        $update->params = $keys;
        $checker = new saveLayout(0, false, $this->template);
        $get_exist = $checker->check_exist_template();

        if (!empty($get_exist) && $get_exist > 0) {
            $update->id = $get_exist;
            $result = Factory::getDbo()->updateObject('#__tmarlevv2_update', $update, 'template');
        } else {
            $result = Factory::getDbo()->insertObject('#__tmarlevv2_update', $update);
        }
        return $load;
    }

    protected function update_cookie_pageerror($load, $tid)
    {

        $registry = new Registry;
        $filter = new InputFilter();
        $defined = array(
            "cookie_deflang",
            "cookie_enable",
            "cookie_style",
            "errorpage_deflang",
            "offlinepage_deflang",
            "offline_counter",
            "offline_online",
            "enable_antispam",
            "contactprivacy_deflang"

        );
        $keys = array();
        foreach ($defined as $key => $val) {
            $keys[$val] = (isset($load[$val])) ? $load[$val] : "";
            unset($load[$val]);
        }
//        $keys["cookie_deflang"] = $load['cookie_deflang'];
//        $keys["cookie_enable"] = $load['cookie_enable'];
//        $keys["cookie_style"] = $load['cookie_style'];
//        $keys["errorpage_deflang"] = $load["errorpage_deflang"];
//        $keys["offlinepage_deflang"] = $load["offlinepage_deflang"];
//         $keys["offline_counter"] = $load["offline_counter"];
//        //$keys["offline_counter"]
//        unset($load['cookie_deflang']);
//        unset($load['cookie_style']);
//        unset($load['cookie_enable']);
//        unset($load['errorpage_deflang']);
        $finder = array(
            "cookie_title",
            "cookie_desc",
            "cookie_accept",
            "cookie_more",
            "cookie_link",
            "errortext",
            "errormodules",
            "offlinetext",
            "contactprivacy_checkbox",
            "contacttitle",
            "contactprivacy_article"


        );


        $langs = $this->getLangs();
        foreach ($langs as $lang) {
            foreach ($finder as $k => $value) {
                if (isset($load[$value . "_" . $lang->lang_code])) {
                    if (is_array($load[$value . "_" . $lang->lang_code])) {
                        $val = $load[$value . "_" . $lang->lang_code];
                        $registry->loadArray($val);
                        $keys[$value . "_" . $lang->lang_code] = $load[$key] = (string)$registry;
                    } else {
                        $keys[$value . "_" . $lang->lang_code] = $load[$value . "_" . $lang->lang_code];
                    }
                    unset($load[$value . "_" . $lang->lang_code]);
                }
            }
        }


        $registry->loadArray($keys);
        $update = new \stdClass();
        $update->params = (string)$registry;
        $update->template = $this->template;


        if ($tid > 0) {
            $update->id = $tid;
            $result = Factory::getDbo()->updateObject('#__tmarlevv2_static', $update, 'template');
        } else {

            $result = Factory::getDbo()->insertObject('#__tmarlevv2_static', $update);
        }
        return $load;
    }

    function getLangs()
    {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.lang_code, a.title');
        $query->from('#__languages AS a');
        $db->setQuery($query);
        $langs = $db->loadObjectList();
        return $langs;
    }

    protected function check_exist_template()
    {

        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id');
        $query->from('#__tmarlevv2_static');
        $query->where('template=' . $db->Quote($this->template));
        $db->setQuery($query);
        $return = $db->loadResult();
        return $return;
    }

    protected function check_exist_layout($id)
    {

        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id');
        $query->from('#__tmarlevv2_layout');
        $query->where('tid=' . $db->Quote($id));
        $db->setQuery($query);
        $return = $db->loadResult();
        return $return;
    }

    protected function clean_templatecache($template, $message = false)
    {
        $cashfolder = JPATH_SITE . '/cache/' . $template . "_template";
        $conf = Factory::getConfig();
        $options = array(
            'caching' => true,
            'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
        );

        $cache = Cache::getInstance('output', $options);
        if (is_dir($cashfolder)) {
            $cache->clean($template . '_template');
        }
        // if (is_dir(JPATH_SITE . '/cache/marlev_layout')) {
        $newcache = Cache::getInstance('output', array());
        $newcache->clean('marlev_layout');
        if ($message == true) {
            Factory::getApplication()->enqueueMessage(Text::_("COM_TMARLEV_CACHE_CLEANED"), 'message');
        }
        //  Factory::getApplication()->enqueueMessage(ucfirst($template) . " " . Text::_("TEMPLATE_CACHE_CLEANED"), 'message');
        //  }
    }

}
