<?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;
jimport('joomla.application.component.modellist');
jimport('joomla.filesystem.file');
if (!defined('DS'))
    define('DS', DIRECTORY_SEPARATOR);

class Tmarlevv2ModelTemplate extends JModelList {

    private static $template;
    private static $params;
    private static $tparams;
    private static $type = false;
    private $layoutid = 0;

    function getMessage() {

        function foreach_input($array, $class, $type) {
            $return = '';
            foreach ($array as $key => $value) {
                $return .= '<div style="display:none" class="alert ' . $class . '"><button type="button"  class="close">×</button><h4>' . $type . '</h4><div>' . $value . '</div></div>';
            }
            return $return;
        }

        $session = JFactory::getSession();
        $template = self::$template;
        $fr = $session->get('marlev_install_message');
        $session->clear('marlev_install_message');
        $messages = (array) json_decode($fr);
        $return = "";

       if (isset($messages['alert-danger'])) {
            $return .= foreach_input($messages['alert-danger'], 'alert-danger', jText::_("COM_TMARLEV_MESSAGGIO_ERROR"));
        }
        if (isset($messages['alert-success'])) {
            $return .= foreach_input($messages['alert-success'], 'alert-success', jText::_("COM_TMARLEV_MESSAGGIO_OK"));
        }
         if (isset($messages['presets-installed'])) {
            $return .= foreach_input($messages['presets-installed'], 'alert-success install-layout', jText::_("COM_TMARLEV_MESSAGGIO_OK"));
        }
        if (isset($messages['clone-template']) || isset($messages['just-install'])) {
            $messages['alert-success install-layout'] = array(jText::_("COM_TMARLEV_INSTALATION_IN_PROGRESS"));
            $return .= foreach_input($messages['alert-success install-layout'], 'alert-success install-layout', jText::_("COM_TMARLEV_MESSAGGIO_OK"));
        }

        return $return;
    }

    function getLoad_Template() {
        if (!JFactory::getUser()->authorise('core.manage', 'com_templates')) {
            return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        }
        $input = JFactory::getApplication()->input;
        $tid = $input->getInt("id");
        $app = JFactory::getApplication();
        if ($tid > 0) {
            $db = JFactory::getDbo();
            $query = $db->getQuery(true);
            $query->select('a.template');
            $query->from('#__template_styles AS a');
            $query->where('a.id=' . $db->Quote($tid));
            $db->setQuery($query);
            $template = $db->loadResult();
            $template_patch = JPATH_SITE . DS . "templates" . DS . $template . DS . "admin" . DS;
            if (!is_file($template_patch . "tmarlev_version.php")) {
                $app->redirect("index.php?option=com_tmarlevv2");
                exit();
            }
            $return = new stdClass();
            $return->template = $template;
            $return->patch = $template_patch;
            $return->id = $tid;

            return self::$template = $return;
        } else {
            $app->redirect("index.php?option=com_tmarlevv2");
            exit();
        }
    }

    public function getForm($data = array(), $loadData = true) {

        jimport('joomla.form.form');
        $form = $this->loadForm('com_tmarlevv2.style', 'style', array('control' => 'params', 'load_data' => true));
        if (empty($form)) {
            return false;
        }
        $template = self::$template;

        //load lang file from template
        $lang = JFactory::getLanguage();
        $extension = 'tpl_' . $template->template;
        $base_dir = str_replace(DS . "admin", "", $template->patch);
        switch ($lang->get("tag")) {
            case "it-IT":$language_tag = 'it-IT';
                break;
            default :$language_tag = 'en-GB';
                break;
        }
        $reload = true;
        $lang->load($extension, $base_dir, $language_tag, $reload);


        //преобразование параметров из mysql в аррай
        $registry = new JRegistry;
        $registry->loadString(self::$params->params);
        $params = $registry->toArray();

        // загрузка файла стилей шаблона
        $path = JPath::clean($template->patch . '/styles.xml');
        $xml = simplexml_load_file($path);

        //добавление новый полей стиля
        foreach ($xml->fieldset->field as $k => $v) {
            $afields = array();

            foreach ($v->attributes() as $name => $value) {
                $afields[] = $name . '="' . $value . '" {||}';
                if ($value == "itroom" || $value == "websons") {
                    self::$type = $value;
                }
            }

            $option = "";
            if (isset($v->option)) {
                $aoption = array();
                foreach ($v->option as $name => $value) {
                    $aoption[] = '<option value="' . $value['value'] . '">' . $value . '</option>{||}';
                }
                $option = str_replace("{||}", "", implode("{||}", $aoption));
            } else if (isset($v->font)) {
                $option = $this->prepare_fonts();
            }

            $fields = str_replace("{||}", "", implode("{||}", $afields));
            $element = new SimpleXMLElement('<field ' . $fields . '>' . $option . '</field>');
            $form->setField($element);
        }
        // установка параметров из params

        foreach ($params as $pname => $pvalue) {
            if (!empty($pvalue)) {
                $form->setValue($pname, null, $pvalue);
            }
        }

        return $form;
    }

    protected function prepare_fonts() {
        require_once JPATH_COMPONENT_ADMINISTRATOR . "/functions/fonts.php";
        $getfonts = new marlev_fonts();
        $fonts = $getfonts->avvaiable_fonts();
        $aoption = array();
        foreach ($fonts as $name => $value) {
            $aoption[] = '<option value="' . $name . '">' . $name . '</option>{||}';
        }
        $option = str_replace("{||}", "", implode("{||}", $aoption));
        return $option;
    }

    protected function loadFormData() {
        if (empty($data)) {
            $data = $this->getData();
        }
        return $data;
    }

    public function getPresets() {
        $template = self::$template;
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.pid, a.title, a.created');
        $query->from('#__tmarlevv2_presets AS a');
        $query->where('a.template=' . $db->Quote($template->template));
        $query->order($db->quoteName('a.created') . 'DESC');
        $db->setQuery($query);
        $presets = $db->loadObjectList();
        return $presets;
    }

    public function getModules() {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id,title, position, language');
        $query->from('#__modules');
        $query->where('client_id=0');
        $query->where('published=1');
        $query->order($db->quoteName('ordering') . 'DESC');
        $db->setQuery($query);
        $modules = $db->loadObjectList();
        return $modules;
    }

    public function getLayout() {
        $template = self::$template;
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('layout,id');
        $query->from('#__tmarlevv2_layout');
        $query->where('tid=' . $db->Quote($template->id));
        $db->setQuery($query);
        $layout = $db->loadObjectList();

        $return = false;
        if (isset($layout[0]->layout)) {
            $registry = new JRegistry;
            $registry->loadString($layout[0]->layout);
            $return = $registry->toArray();
            $this->layoutid = $layout[0]->id;
        }

        return $return;
    }

    public function getLayoutid() {
        return $this->layoutid;
    }

    protected function getKeys() {
        $template = self::$template;
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('params');
        $query->from('#__tmarlevv2_update');
        $query->where('template=' . $db->Quote($template->template));
        $db->setQuery($query);
        $return = $db->loadResult();

        if (!empty($return)) {
            $registry = new JRegistry;
            $registry->loadString($return);
            $return = $registry->toArray();
        }

        return $return;
    }

    protected function getStatic() {
        $template = self::$template;
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('params');
        $query->from('#__tmarlevv2_static');
        $query->where('template=' . $db->Quote($template->template));
        $db->setQuery($query);
        $return = $db->loadResult();

        if (!empty($return)) {
            $registry = new JRegistry;
            $registry->loadString($return);
            $return = $registry->toArray();
        }
        return $return;
    }

    protected function getData() {
        $tid = self::$template->id;
        if ($tid > 0) {
            $db = JFactory::getDbo();
            $query = $db->getQuery(true);
            $query->select('a.id, a.template, a.params, a.title, a.home');
            $query->from('#__template_styles AS a');
            $query->where('a.id=' . $db->Quote($tid));
            $db->setQuery($query);
            $data = $db->loadObjectList();
            $return = new stdClass();
            if (isset($data[0])) {
                foreach ($data[0] as $v => $k) {
                    $return->$v = $k;
                }
            }



            $get_update_keys = $this->getKeys();
            $get_cookie = $this->getStatic();

            if (!empty($get_update_keys)) {
                $registry = new JRegistry;
                $registry->loadString($return->params);
                $tparams = $registry->toArray();

                $newparams = array_merge($tparams, $get_update_keys);
                $registry->loadArray($newparams);
                $return->params = (string) $registry;
            }
            if (!empty($get_cookie)) {
                $registry = new JRegistry;
                $registry->loadString($return->params);
                $tparams = $registry->toArray();

                $newparams = array_merge($tparams, $get_cookie);
                $registry->loadArray($newparams);
                $return->params = (string) $registry;
            }

            return self::$params = $return;
        }
    }

    public function getLang_params() {
        $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 = new stdClass();
        $return->langs = $langs;
        $registry = new JRegistry;
        $registry->loadString(self::$params->params);
        $params = $registry->toArray();
        if (isset($params['errorpage'])) {
            unset($params['errorpage']);
        }
         if (isset($params['offlinepage'])) {
            unset($params['offlinepage']);
        }
        $return->params = $params;

        return $return;
    }

    public function getPlugins() {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('name, enabled');
        $query->from('#__extensions');
        $a = "'yrvote','vote','yrminifier'";
        $query->where('element IN (' . $a . ')');
        $db->setQuery($query);
        $load = $db->loadObjectList();

        if (empty($load))
            return false;
        else {
            $result = array();
            foreach ($load as $key) {
                $name = strtolower($key->name);
                $result[$name] = $key;
            }

            return $result;
        }
    }

    public function getTtype() {
        return self::$type;
    }

    public function getTparams() {
        return self::$params->params;
    }

}

?>
