<?php

/**
 *
 * @extension       TMarlev
 * @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('Restricted access');
if (!defined('DS'))
    define('DS', DIRECTORY_SEPARATOR);
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
jimport('joomla.installer.helper');

class com_inmarlevInstallerScript {

    function postflight($type, $parent) {
        $installer = new JInstaller();

        $installer->_overwrite = true;
        $pkg_path = dirname(__FILE__) . DS . 'extensions' . DS;
        $files = preg_grep('/^([^.])/', scandir($pkg_path));
        $plugins = array("yrvote", "yrminifier", "marlevupdate", "extendibletm");
        $create_message = array();
        foreach ($files as $f => $fname) {

            if (is_dir($pkg_path . $fname)) {

                if ($fname == "tmarlevv2") {
                    //$installedxml = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_tmarlev' . DS . 'tmarlev.xml';
                    if (file_exists(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_tmarlevv2' . DS . 'tmarlevv2.xml')) {
                       
                        $get_this_xml = simplexml_load_file($pkg_path ."tmarlev".DS.'tmarlev.xml');
                        $xml = simplexml_load_file(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_tmarlev' . DS . 'tmarlev.xml');
                        
                        if (version_compare($get_this_xml->version, $xml->version) >= 0) {
                            if (!$installer->install($pkg_path . $fname)) {
                                $message = "ERROR: Could not install correcty Marlev Framework. Please contact Marlev Support.";
                                $create_message["alert-danger"][] = $message;
                            }
                        }
                        //  JInstallerHelper::cleanupInstall($pkg_path . $fname);
                    } else {
                        if (!$installer->install($pkg_path . $fname)) {
                            $message = "ERROR: Could not install correcty Marlev Framework. Please contact Marlev Support.";
                            $create_message["alert-danger"][] = $message;
                        }
                    }
                } elseif (in_array($fname, $plugins)) {

                    if (!$installer->install($pkg_path . $fname)) {
                        $message = "ERROR: Could not install correcty " . ucfirst($fname) . " Plugin. Please contact Marlev Support.";
                        $create_message["alert-danger"][] = $message;
                    }
                } else {
                    $template_query = $fname;
                    $templatename = ucfirst($fname) . " " . "Template";
                    $install_update = "done";
                    if (file_exists(JPATH_SITE . DS . 'templates' . DS . $fname . DS . 'templateDetails.xml')) {
                        $messageinstall = "successfully updated";
                        $install_update = "update";
                    } else {
                        $messageinstall = "successfully installed";
                        $install_update = "install";
                    }

                    if (!$installer->install($pkg_path . $fname)) {
                        $message = "ERROR: Could not install correcty " . $templatename . ". Please contact Marlev Support.";
                        $create_message["alert-danger"][] = $message;
                    } else {
                        $message = $templatename . " " . $messageinstall;
                        if ($install_update === "install") {
                            $create_message["just-install"][] = "messaggio in model";
                        } else {
                            $create_message["alert-success"][] = $message;
                        }
                    }
                    $folder_name = JPATH_SITE . DS . 'templates' . DS . $fname . DS . "custom";
                    if (!JFolder::exists($folder_name)) {
                        if (JFolder::create($folder_name, 0755)) {
                            $jfile = new JFile;

                            $file_content = "/* This file is for your custom css styles " . PHP_EOL . " Questo file e' per i tuoi stili css personali.  */";
                            $jfile->append($folder_name . DS . '/css.css', $file_content);
                            $file_content = "/* This file is for your custom javascript " . PHP_EOL . " Questo file e' per il tuo javascript personale.  */";
                            $jfile->append($folder_name . DS . '/js.js', $file_content);
                            $jfile->append($folder_name . DS . '/index.html', "");
                        } else {
                            $message .= '<div><b><span style="color:#CC0033">Folder</span> ' . $folder_name
                                    . ' <span style="color:#CC0033">creation failed!</span></b> Please create it manually with files js.js and css.cs</div>';
                            // JFactory::getApplication()->enqueueMessage($message, 'message');
                            $create_message["alert-danger"][] = $message;
                        }
                    }
                    //copy image folder to media
                    $img_sourse = JPATH_SITE . DS . 'templates' . DS . $fname . DS . "images" . DS . 'template';
                    $img_dest = JPATH_SITE . DS . 'images' . DS . $fname . "_template";
                    if (!JFolder::copy($img_sourse, $img_dest, '', true, false)) {
                        $message .= '<div><b><span style="color:#CC0033">Folder</span> ' . $folder_name
                                . ' <span style="color:#CC0033">Copy image folder failed</span></b> Please copy manually. Images in the folder ' . $img_sourse . '  must be copied in this folder ' . $img_dest . ' /div>';
                        // JFactory::getApplication()->enqueueMessage($message, 'message');
                        $create_message["alert-danger"][] = $message;
                    }
                }
            }
        }

        $enable = array("marlevupdate", "extendibletm");
        $get_plugins = $this->enable_extensions($enable);
        // JInstallerHelper::cleanupInstall($pkg_path);
        if (isset($create_message["alert-danger"])) {
            foreach ($create_message["alert-danger"] as $key => $value) {
                JFactory::getApplication()->enqueueMessage($value, 'error');
            }
        } else {
            $tid = com_inmarlevInstallerScript::run_dbquery($template_query);
            $session = JFactory::getSession();
            $tojson = json_encode($create_message);
            $session->set('marlev_install_message', $tojson);
            if ($install_update == "update") {
                $message_confirm = $templatename . " " . $messageinstall;
                JFactory::getApplication()->enqueueMessage($message_confirm, 'message');
            }
            $install_presents = $this->presets_function($template_query);
            $parent->getParent()->setRedirectURL('index.php?option=com_tmarlevv2&view=template&id=' . $tid . '&installtype=' . $install_update);
        }
        return false;
    }

    protected function presets_function($template) {
        $patch = JPATH_SITE . DS . 'templates' . DS . $template . DS . "presets/";
        $presets_file = $patch. "install_presets.php";
        if (file_exists($presets_file)) {
            require_once $presets_file;
            $exists = $this->load_exist_presets($template);
            $install = array();
            if (isset($exists[0])) {
                foreach ($exists as $key) {
                    $existed = trim($key->title);
                    unset($presets[$existed]);
                }
            }
            if (!empty($presets)) {
                $this->install_presets($presets);
                $this->install_layouts($presets, $patch);
            }
        }
    }

    protected function install_layouts($presets, $patch) {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $columns = array('pid', 'params');
        $query->insert($db->quoteName('#__tmarlevv2_layoutpresets'))->columns($db->quoteName($columns));
        foreach ($presets as $key => $value) {
            $values = file_get_contents($patch . $key . "_layout.csv");
            $query->values($values);
        }
        $db->setQuery($query);
        $db->execute();
    }

    protected function install_presets($presets) {
        $dt = date('Y-m-d H:i:s');
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $columns = array('pid','title', 'template', 'params', "created");
        $query->insert($db->quoteName('#__tmarlevv2_presets'))->columns($db->quoteName($columns));
        foreach ($presets as $key) {
            $query->values($db->quote($key["pid"]).','. $db->quote($key["title"]).','. $db->quote($key["template"]).','. $db->quote($key["params"]).','. $db->quote($dt));
        }
        $db->setQuery($query);
        $db->execute();
    }

    protected function load_exist_presets($template) {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('title');
        $query->from('#__tmarlevv2_presets');
        $query->where('template =' . $db->Quote($template));

        $db->setQuery($query);
        $titles = $db->loadObjectList();
        return $titles;
    }

    protected function run_dbquery($searchtemplatename) {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('a.id');
        $query->from('#__template_styles AS a');
        $query->where('template =' . $db->Quote($searchtemplatename));

        $db->setQuery($query);
        $tid = $db->loadResult();


        $query = $db->getQuery(true);
        $query->delete($db->quoteName('#__menu'));
        $query->where('title IN ("COM_TMARLEVV2","INMARLEV")');
        //$query->where('title=' . $db->Quote('INMARLEV'));
        $db->setQuery($query);
        $result = $db->execute();
        return $tid;
    }

    protected function enable_extensions($extension) {

        $db = JFactory::getDbo();
        $prepare = array();
        foreach ($extension as $key => $ext) {
            if (!empty($ext))
                $prepare[] = $db->quote($ext);
        }
        $elements = implode(",", $prepare);
        $query = $db->getQuery(true);
        $query = 'UPDATE #__extensions' . ' SET enabled = 1 WHERE element IN ( ' . $elements . '  )';
        $db->setQuery($query);
        $result = $db->execute();
    }

}
