<?php
/**
 *
 * @extension       TMarlev
 * @author          Lev Milicenco<support@marlev.it>
 * @link            http://www.marlev.it
 * @copyright       Copyright 2021 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);
use Joomla\CMS\Factory;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Filesystem\Folder;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Installer\Installer;
//for_use
class com_inmarlevInstallerScript
{

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

        $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_BASE . DS . 'administrator' . DS . 'components' . DS . 'com_tmarlevv2' . DS . 'tmarlevv2.xml')) {

                        $get_this_xml = simplexml_load_file($pkg_path . "tmarlevv2" . DS . 'tmarlevv2.xml');
                        $xml = simplexml_load_file(JPATH_BASE . DS . 'administrator' . DS . 'components' . DS . 'com_tmarlevv2' . DS . 'tmarlevv2.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 (!Folder::exists($folder_name)) {
                        if (Folder::create($folder_name, 0755)) {
                            $jfile = new File;
                            $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>';
                            // Factory::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 (file_exists($img_sourse)) {
                        if (!Folder::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>';
                            // Factory::getApplication()->enqueueMessage($message, 'message');
                            $create_message["alert-danger"][] = $message;
                        }
                    }
                    //delete unused folder
                    $delete_unused_folders = array(
                       // JPATH_SITE . DS . 'templates' . DS . $fname . DS . "html" . DS . 'com_content',
                        JPATH_SITE . DS . 'templates' . DS . $fname . DS . "html" . DS . 'mod_search',
                        JPATH_SITE . DS . 'templates' . DS . $fname . DS . "css" . DS . 'bootstrap',
                    );
                    foreach ($delete_unused_folders as $key=>$html_com_content ) {
                        if (file_exists($html_com_content) && is_dir($html_com_content)) {
                            Folder::delete($html_com_content);
                        }
                    }
                    $this->delete_old_files($fname);
                    //Update server
                    $this->update_updateserver($fname);

                }
            }
        }

        $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) {
                Factory::getApplication()->enqueueMessage($value, 'error');
            }
        } else {
            $tid = com_inmarlevInstallerScript::run_dbquery($template_query);
            $session = Factory::getApplication()->getSession();
            //$session = Factory::getSession();
            $tojson = json_encode($create_message);
            $session->set('marlev_install_message', $tojson);

            $install_presents = $this->presets_function($template_query);//If return true is upgraded from old tmarlev
            if ($install_presents) {
                $install_update = "upgraded";
            }
            if ($install_update == "update") {
                $message_confirm = $templatename . " " . $messageinstall;
                Factory::getApplication()->enqueueMessage($message_confirm, 'message');
            }
            $parent->getParent()->setRedirectURL('index.php?option=com_tmarlevv2&view=template&id=' . $tid . '&installtype=' . $install_update);
        }
        return false;
    }
    private function update_updateserver($template)
    {
        if(file_exists(JPATH_SITE . '/templates/'.$template.'/templateDetails.xml')) {
            $xml = simplexml_load_file(JPATH_SITE . '/templates/'.$template.'/templateDetails.xml');
            $link = $xml->{'updateservers'}->{'server'};
            $name = $link->attributes()->name[0];
            $db = Factory::getDbo();
            $query = $db->getQuery(true);
            $query = 'UPDATE #__update_sites' . ' SET location = ' . $db->quote($link) . ' WHERE name =' . $db->quote($name);
            $db->setQuery($query);
            $result = $db->execute();
        }
    }

    protected function presets_function($template)
    {
        $upgrade_from_old_tmarlev = false;
        $patch = JPATH_SITE . DS . 'templates' . DS . $template . DS . "presets/";
        $presets_file = $patch . "install_presets.php";
        $layout = true;
        if (!file_exists($presets_file)) {
            $layout = false;
            $presets_file = JPATH_SITE . DS . 'templates' . DS . $template . DS . "admin" . DS . "install_presets.php";
            $upgrade_from_old_tmarlev = $this->upgrade_from_old_tmarlev($template);
        }
        if (file_exists($presets_file)) {
            require_once $presets_file;
            $exists = $this->load_exist_presets($template);
            if(isset($exists[0])){
                foreach($exists as $all_presets){
                    $existed = trim($all_presets->title);
                    if(isset($presets[$existed]) ){
                        $this->remove_preset_fromdb($all_presets->pid, "presets");
                        $this->remove_preset_fromdb($all_presets->pid, "layoutpresets");
                    }
                }
            }
            if (!empty($presets)) {
                $this->install_presets($presets, $template, $layout);
                if ($layout == true) {
                    $this->install_layouts($presets, $patch);
                }
            }
        }
        return $upgrade_from_old_tmarlev;
    }
    protected function remove_preset_fromdb($preset, $table)
    {
        $return = true;
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->delete($db->quoteName('#__tmarlevv2_' . $table));
        $query->where('pid IN (' . $preset . ')');
        //$query->where($conditions);
        $db->setQuery($query);
        $result = $db->execute();
        if (!$result) {
            $return = false;
        }
        return $return;
    }

    protected function install_layouts($presets, $patch)
    {
        $db = Factory::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, $template, $layout)
    {
        $dt = date('Y-m-d H:i:s');
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $columns = array('pid', 'title', 'template', 'params', "created");
        $query->insert($db->quoteName('#__tmarlevv2_presets'))->columns($db->quoteName($columns));
        if ($layout == true) {
            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));
            }
        } else {
            foreach ($presets as $key => $value) {
                $values = array($db->quote(rand(10000000, 999999999)), $db->quote($key), $db->quote($template), $db->quote($value), $db->quote($dt));
                $query->values(implode(',', $values));
            }
        }
        $db->setQuery($query);
        $db->execute();
    }

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

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

    protected function run_dbquery($searchtemplatename)
    {
        $db = Factory::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 = Factory::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();
    }
    protected function delete_old_files($template){
        unlink(JPATH_SITE . DS . 'templates' . DS . $template . DS . "css/bootstrap.min.css");
    }

    protected function upgrade_from_old_tmarlev($template)
    {
        if (ComponentHelper::getComponent('com_tmarlev', true)->enabled) {
            $updates = self::copy_updates_from_tmarlev($template);
            $presets = self::copy_presets_from_tmarlev($template);
            $deleter = self::delete_unused_files($template);
            if ($updates || $presets) {
                return true;
            }
        }
        return false;
    }

    protected function delete_unused_files($template)
    {
        foreach (array("default_plugins.php", "default_home.php") as $key => $value) {
            if (file_exists(JPATH_SITE . DS . 'templates' . DS . $template . DS . "admin" . DS . $value)) {
                unlink(JPATH_SITE . DS . 'templates' . DS . $template . DS . "admin" . DS . $value);
            }

        }
    }

    protected function copy_presets_from_tmarlev($template)
    {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('title,params,created');
        $query->from('#__tmarlev_presets');
        $query->where('template=' . $db->Quote($template));
        $db->setQuery($query);
        $presets = $db->loadObjectList();
        if (isset($presets[0])) {
            $db = Factory::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(rand(10000000, 999999999)) . ',' . $db->quote($key->title) . ',' . $db->quote($template) . ',' . $db->quote($key->params) . ',' . $db->quote($key->created));
            }
            $db->setQuery($query);
            $db->execute();

            $db = Factory::getDbo();
            $query = $db->getQuery(true);
            $query->delete($db->quoteName('#__tmarlev_presets'));
            $query->where('template=' . $db->Quote($template));
            $db->setQuery($query);
            $result = $db->execute();
            return true;
        }
        return false;

    }

    protected function copy_updates_from_tmarlev($template)
    {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('params');
        $query->from('#__tmarlev_update');
        $query->where('template=' . $db->Quote($template));
        $db->setQuery($query);
        $params = $db->loadResult();
        if (!empty($params)) {
            $db = Factory::getDbo();
            $query = $db->getQuery(true);
            $columns = array('template', 'params');
            $query->insert($db->quoteName('#__tmarlevv2_update'))->columns($db->quoteName($columns));
            $query->values($db->quote($template) . ',' . $db->quote($params));
            $db->setQuery($query);
            $db->execute();

            $db = Factory::getDbo();
            $query = $db->getQuery(true);
            $query->delete($db->quoteName('#__tmarlev_update'));
            $query->where('template=' . $db->Quote($template));
            $db->setQuery($query);
            $result = $db->execute();
            return true;
        }
        return false;
    }
}
