<?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\Model;
require_once JPATH_ROOT . '/administrator/components/com_tmarlevv2/src/Helper/loader.php';
use Joomla\CMS\MVC\Model\ListModel;
use Joomla\CMS\Language\Text;
use \Joomla\Registry\Registry;
use Joomla\CMS\Filesystem\Path;
use Joomla\CMS\Factory;
use Marlev\Component\Tmarlevv2\Administrator\Helper\marlev_fonts;
use Marlev\Component\Tmarlevv2\Administrator\Controller\TemplateController;
//for_use

defined('_JEXEC') or die;

//use Joomla\Registry;
class TemplateModel extends ListModel{

    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   = Factory::getApplication()->getSession();

        $template = self::$template;
        $fr = $session->get('marlev_install_message');
        $messages = array();
        if(!empty($fr)) {
            $session->clear('marlev_install_message');
            $messages = (array)json_decode($fr);
        }
        $return = "";

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

        return $return;
    }
    function getFreshInstall_installPreset(){
        $app = Factory::getApplication();
        $input = $app->input;
        $id = $input->getInt("id");
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.template');
        $query->from('#__template_styles AS a');
        $query->where('a.id=' . $db->Quote($id));
        $db->setQuery($query);
        $template = $db->loadResult();
        $getpresets = JPATH_SITE . DS . "templates" . DS . $template . DS . "presets" . DS ."install_presets.php";
        if (is_file($getpresets)) {
          require_once $getpresets;
            $loadControll = new TemplateController();
          $pid = $presets["marlev_default"]['pid'];
          $loadControll->loadpresets_styles($pid,$id);
          $loadControll->loadpresets_layout($pid,$id);
        }
    }

    function getLoad_Template() {
        if (!Factory::getApplication()->getIdentity()->authorise('core.manage', 'com_templates')) {
            return Factory::getApplication()->enqueueMessage(Text::_('JERROR_ALERTNOAUTHOR'), 'error');
        }
        $app = Factory::getApplication();
        $input = $app->input;
        $tid = $input->getInt("id");
        if ($tid > 0) {
            $db = Factory::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) {


        $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 = Factory::getApplication()->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 Registry();
        $registry->loadString(self::$params->params);
        $params = $registry->toArray();

        // загрузка файла стилей шаблона
        $path = Path::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_ADMINISTRATOR . '/components/com_tmarlevv2' . "/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 = Factory::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 = Factory::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 getContactPrivacy() {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id,title,name');
        $query->from('#__fields');
        $query->where('type=' . $db->Quote('checkboxes'));
        $query->where('state=1');
        //$query->order($db->quoteName('ordering') . 'DESC');
        $db->setQuery($query);
        $modules = $db->loadObjectList();
        return $modules;
    }
    public function getContactPrivacyArticles() {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id,title');
        $query->from('#__content');
        //$query->where('type=' . $db->Quote('checkboxes'));
        $query->where('state=1');
        //$query->order($db->quoteName('ordering') . 'DESC');
        $db->setQuery($query);
        $modules = $db->loadObjectList();
        return $modules;
    }

    public function getUpdate_Template() {
        $template = self::$template;
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('version');
        $query->from('#__updates');
        $query->where('element=' . $db->Quote($template->template));
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result;
    }

    public function getLayout() {
        $template = self::$template;
        $db = Factory::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 Registry;
            $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 = Factory::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 Registry;
            $registry->loadString($return);
            $return = $registry->toArray();
        }

        return $return;
    }

    protected function getStatic() {
        $template = self::$template;
        $db = Factory::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 Registry;
            $registry->loadString($return);
            $return = $registry->toArray();
        }
        return $return;
    }

    protected function getData() {
        $tid = self::$template->id;
        if ($tid > 0) {
            $db = Factory::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 Registry;
                $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 Registry;
                $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 = 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 = new \stdClass();
        $return->langs = $langs;
        $registry = new Registry;
        $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 = Factory::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;
    }

}

?>
