<?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
 */
defined('_JEXEC') or die;
if (!defined('DS'))
    define('DS', DIRECTORY_SEPARATOR);
jimport('joomla.application.component.controlleradmin');
jimport('joomla.filter.filterinput');
include JPATH_COMPONENT . '/controllers/layout.php';

class Tmarlevv2ControllerTemplate extends JControllerAdmin {

    public $template;

    protected function get_form() {
        if (!JSession::checkToken('get')) {
            JFactory::getApplication()->redirect(JURI::base() . 'index.php', JText::_('JINVALID_TOKEN'));
            return false;
        }

        if (!JFactory::getUser()->authorise('core.manage', 'com_templates')) {
            JFactory::getApplication()->redirect(JURI::base() . 'index.php', JText::_('JERROR_ALERTNOAUTHOR'));

            return false;
        }
        $input = JFactory::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();
        $filter = new JFilterInput();
        $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() {
        $result = $this->get_form();

        $this->save_apply($result);
        $this->setRedirect(JURI::base() . "index.php?option=com_templates");
    }

    public function cancel() {
        $this->setRedirect(JURI::base() . "index.php?option=com_templates");
    }

    protected function save_apply($output) {

//     
        $filter = new JFilterInput();
        $data = $output['params']; //$this->input->post->get('params', array(), 'array');
        // 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"])) {
            JFactory::getApplication()->enqueueMessage('Titolo &egrave; richiesto', 'warning');
            $this->redirectToMenu("tm-base", $id);
            return false;
        }
        $allowhtml = JFilterInput::getInstance(null, null, 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 JRegistry;
                    // $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 class for css
        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 (array_key_exists($k, $load)) {
            $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;
        }
        //fine esclusione
        $tid = $this->check_exist_template();
        $load = $this->update_keys($load, $tid);

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

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

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

        if ($result) {
            $this->setHome($id, $home);

            $make_layout = new saveLayout($id, $layout, $this->template);

            $make_layout->setLayout($additional_css, $load['font']);




            $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) {
                JFactory::getApplication()->enqueueMessage(jText::_("COM_TMARLEV_INSTALATION_IN_PROGRESS_DONE"), 'message');
            } else {
                JFactory::getApplication()->enqueueMessage('Modifiche Salvate', 'message');
            }
        } else {
            JFactory::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 {
            JFactory::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 {
            JFactory::getApplication()->enqueueMessage('File non esiste ' . $custom_js, 'notice');
        }
    }

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

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

            $db = JFactory::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"])) {
                JArrayHelper::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($id = 0, $home) {
        $user = JFactory::getUser();
        $db = JFactory::getDbo();

        // Access checks.
        if (!$user->authorise('core.edit.state', 'com_templates')) {
            throw new Exception(JText::_('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() {
//        if (!JSession::checkToken('get')) {
//            JFactory::getApplication()->enqueueMessage(JText::_('JINVALID_TOKEN'), 'error');
//            $this->setRedirect(JURI::base() . "index.php");
//        }
//        if (!JFactory::getUser()->authorise('core.manage', 'com_templates')) {
//            JFactory::getApplication()->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'), 'error');
//            $this->setRedirect(JURI::base() . "index.php");
//        }
//        $form = $this->input->post->get('postdata', array(), 'array');
//        parse_str($form[0], $array);
//
//
//        JArrayHelper::toInteger($array['delete_preset']);
//
//        $id = (int) $array["ajax_return"];
//        $presets = $array['delete_preset'];
//        $n = count($presets);
        $array = $this->get_form();
        $id = $array["ajax_return"];
        JArrayHelper::toInteger($array['delete_preset']);
        $presets = $array['delete_preset'];
       
        $n = count($presets);
        
        if ($n > 1) {
            JFactory::getApplication()->enqueueMessage(JText::_("COM_TMARLEV_SELECT_ONLY_ONE_PRESET"), 'error');
            $this->redirectToMenu("tm-presets", $id);
            return;
        }

        JArrayHelper::toInteger($presets);
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.params');
        $query->from('#__tmarlevv2_presets AS a');
        $query->where('a.pid=' . $db->Quote($presets[0]));
        $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 = JFactory::getDbo()->updateObject('#__template_styles', $object, 'id');

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.params');
        $query->from('#__tmarlevv2_layoutpresets AS a');
        $query->where('a.pid=' . $db->Quote($presets[0]));
        $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 = JFactory::getDbo()->updateObject('#__tmarlevv2_layout', $object1, 'id');
        } else {
            $object1->tid = $id;
            $result1 = JFactory::getDbo()->insertObject('#__tmarlevv2_layout', $object1);
        }




        if ($result && $result1) {
            JFactory::getApplication()->enqueueMessage('<span class="reload-page">' . jText::_("COM_TMARLEV_PRESET_UPLOADED") . '</span></br>' . jText::_("COM_TMARLEV_PRESET_UPLOADED_2"), 'message');
            $this->redirectToMenu("tm-presets", $id);
        } else {
            JFactory::getApplication()->enqueueMessage(jText::_("COM_TMARLEV_PRESET_UPLOAD_ERROR"), 'error');
            $this->redirectToMenu("tm-presets", $id);
        }
    }

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

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

    function cancellpresets() {

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

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

        function remove_preset_fromdb($preset, $table) {
            $return = true;
            $db = JFactory::getDbo();
            $query = 'DELETE FROM #__tmarlevv2_' . $table
                    . ' WHERE pid IN ( ' . $db->escape($preset) . '  )';
            $db->setQuery($query);
            if (!$db->query()) {
                $return = false;
            }
            return $return;
        }

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

    function savepresets() {
        $output = $this->get_form();
        $filter = new JFilterInput();
        $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|)";
        unset($output);
        if (empty($preset_title)) {
            JFactory::getApplication()->enqueueMessage(jText::_("COM_TMARLEV_TITLE_PRESETS_REQUIRED"), 'warning');
        } 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 JRegistry;
            $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 = JFactory::getDbo()->insertObject('#__tmarlevv2_presets', $sql);
            $backup_layout = new saveLayout($pid, $layout_load);
            $run_backup_layout = $backup_layout->backupLayout();
            if ($result && $run_backup_layout) {
                JFactory::getApplication()->enqueueMessage(jText::_("COM_TMARLEV_PRESET_SAVED_OK"), 'message');
            } else {
                JFactory::getApplication()->enqueueMessage(jText::_("COM_TMARLEV_PRESET_SAVED_FAIL"), 'warning');
            }
        }
        $this->redirectToMenu("tm-presets", $id);
    }

    protected function redirectToMenu($menu, $id) {
        $session = JFactory::getSession();
        $session->set('activemenu', $menu);
        $this->setRedirect(JURI::base() . "index.php?option=com_tmarlevv2&view=template&id=" . $id);
    }

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

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

            // Access checks.
            $user = JFactory::getUser();
            if (!$user->authorise('core.edit.state', 'com_templates')) {
                throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
            }
            $db = JFactory::getDbo();
            if ($yrvote == 1 || $yrminifier == 1) {
                $enable_arr = array();

                if ($yrminifier == 1)
                    $enable_arr[] = $db->quote("yrminifier");
                if ($yrvote == 1)
                    $enable_arr[] = $db->quote("yrvote");
                $enable = implode(",", $enable_arr);

                $db->setQuery(
                        'UPDATE #__extensions' .
                        ' SET enabled = ' . $db->Quote(1) .
                        ' WHERE element IN (' . $enable . ')');
            }
            else {
                $db->setQuery(
                        'UPDATE #__extensions' .
                        ' SET enabled = ' . $db->Quote(0) .
                        ' WHERE element = "vote"');
            }
            $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 JRegistry;
        $registry->loadArray($keys);
        $keys = (string) $registry;

        $update = new stdClass();
        $update->template = $this->template;
        $update->params = $keys;

        if ($tid > 0) {
            $update->id = $tid;
            $result = JFactory::getDbo()->updateObject('#__tmarlevv2_update', $update, 'template');
        } else {
            $result = JFactory::getDbo()->insertObject('#__tmarlevv2_update', $update);
        }
        return $load;
    }

    protected function update_cookie_pageerror($load, $tid) {

        $registry = new JRegistry;
        $filter = new JFilterInput();
        $defined = array(
            "cookie_deflang",
            "cookie_enable",
            "cookie_style",
            "errorpage_deflang",
            "offlinepage_deflang",
            "offline_counter",
            "offline_online"
        );
        $keys = array();
        foreach ($defined as $key => $val) {
            $keys[$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",
        );


        $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 = JFactory::getDbo()->updateObject('#__tmarlevv2_static', $update, 'template');
        } else {

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

    function getLangs() {
        $db = JFactory::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 = JFactory::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 = JFactory::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) {
        $cashfolder = JPATH_SITE . '/cache/' . $template . "_template";
        $conf = JFactory::getConfig();
        $options = array(
            'caching' => true,
            'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
        );

        $cache = JCache::getInstance('output', $options);
        if (is_dir($cashfolder)) {
            $cache->clean($template . '_template');
        }
        // if (is_dir(JPATH_SITE . '/cache/marlev_layout')) {
        $cache->clean('marlev_layout');
        //  JFactory::getApplication()->enqueueMessage(ucfirst($template) . " " . JText::_("TEMPLATE_CACHE_CLEANED"), 'message');
        //  }
    }

}
