<?php

/*
 * Copyright (C) 2018 KAINOTOMO PH LTD <info@kainotomo.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Joomla\Component\SpStgSrv\Administrator\Controller;

defined('_JEXEC') or die;

use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\Utilities\ArrayHelper;

/**
 * Description of InstallerInstallController
 *
 * @author KAINOTOMO PH LTD <info@kainotomo.com>
 */
class InstallerInstallController extends BaseController{
        
        public $remote_log;
        
        public function __construct($config = array(), MVCFactoryInterface $factory = null, $app = null, $input = null) {
                parent::__construct($config, $factory, $app, $input);
                if (!isset($this->input)) {
                        $this->input = Factory::getApplication()->input;
                }
        }
        
        public function install() {

                error_reporting(0);

                $model_actions = new \Joomla\Component\SpStgSrv\Site\Model\ActionsModel;
                $model = new \Joomla\Component\SpStgSrv\Administrator\Model\InstallerModel();
                $model_actions->delete_log();

                $params = ComponentHelper::getParams('com_spstgsrv');
                $stage_id = $this->input->getString('stage_id');
                $remote_log = $model_actions->getRemoteLog($stage_id);
                if (is_array($remote_log)) {
                        $this->save($stage_id, $remote_log, true);
                        return false;
                }
                $this->remote_log = $remote_log;
                $post['sec'] = trim($remote_log->sec);

                $data = $model->getItem($post);
                if (!$data['result']) {
                        $this->save($stage_id, $data, true);
                        return false;
                }

                //Choose function type
                $data['package_path'] = $params->get('package_path') . 'components/com_spstgmng/packages/';
                $data['package_name'] = $remote_log->post->package_name;
                $pkg_arr = explode('.', $data['package_name']);
                $ext = strtolower($pkg_arr[count($pkg_arr) - 1]);

                switch ($ext) {
                        case 'stg': //php
                                $message = $model->execute_php($data);
                                break;

                        case 'sql':
                                $message = $model->execute_sql($data);
                                break;

                        default:
                                $message = $model->install($data);
                                break;
                }

                $data['package_name'] = $model->package_name;
                $data['version'] = $model->version;

                if ($message != 'success') {
                        $data['result'] = 0;
                        $data['message'] = $message;
                        $this->save($stage_id, $data, true);
                        return false;
                }

                $packages = $model->getPackages();
                if (!is_array($packages)) {
                        $data['result'] = 0;
                        $data['message'] = $packages;
                        $this->save($stage_id, $data, true);
                        return false;
                }
                $data['packages'] = $packages;

                $data['result'] = 1;
                $data['message'] = Text::_('COM_SPSTGSRV_INSTALL_SUCCESS');
                $this->save($stage_id, $data, true);
                return true;
        }

        public function update() {

                error_reporting(0);

                $model_actions = new \Joomla\Component\SpStgSrv\Site\Model\ActionsModel;
                $model = new \Joomla\Component\SpStgSrv\Administrator\Model\InstallerModel();
                $model_actions->delete_log();

                $stage_id = $this->input->getString('stage_id');
                $remote_log = $model_actions->getRemoteLog($stage_id);
                if (is_array($remote_log)) {
                        $this->save($stage_id, $remote_log, true);
                        return false;
                }
                $this->remote_log = $remote_log;
                $post['sec'] = trim($remote_log->sec);

                $data = $model->getItem($post);
                if (!$data['result']) {
                        $this->save($stage_id, $data, true);
                        return false;
                }

                foreach ($remote_log->post as $value) {
                        $data['extension_id'] = trim($value->extension_id);
                        $data['package_name'] = $value->package_name;
                        $data['version'] = $value->version;

                        if ($data['extension_id'] == '700') { //redirect to com_joomlaupdate if core Joomla update
                                $model_actions = $this->getModel('actions');
                                $model_actions->save_stage_id($stage_id, $data);

                                $file = $model->downloadJoomlaNew();
                                $message = null;
                                $messageType = null;

                                if ($file) {
                                        Factory::getApplication()->setUserState('com_joomlaupdate.file', $file);
                                        $url = 'index.php?option=com_joomlaupdate&task=update.install&' . Factory::getSession()->getFormToken() . '=1';
                                        JLog::add(Text::sprintf('COM_JOOMLAUPDATE_UPDATE_LOG_FILE', $file), JLog::INFO, 'Update');
                                } else {
                                        Factory::getApplication()->setUserState('com_joomlaupdate.file', null);
                                        
                                        $data['result'] = 0;
                                        $data['message'] = Text::_('COM_JOOMLAUPDATE_VIEW_UPDATE_DOWNLOADFAILED');
                                        $this->save($stage_id, $data, true);
                                        return false;
                                }

                                $this->setRedirect($url, $message, $messageType);

                                return;
                        }

                        $message = $model->update($data);
                        if ($message != 'success') {
                                $data['result'] = 0;
                                $data['message'] = $message;
                                $this->save($stage_id, $data, true);
                                return false;
                        }

                        $model->save($data);
                }

                $packages = $model->getPackages();
                if (!is_array($packages)) {
                        $data['result'] = 0;
                        $data['message'] = $packages;
                        $this->save($stage_id, $data, true);
                        return false;
                }
                $data['packages'] = $packages;

                $updates = $model->find();
                if (!is_array($updates)) {
                        $data['result'] = 0;
                        $data['message'] = $updates;
                        $this->save($stage_id, $data, true);
                        return false;
                }
                $data['updates'] = $updates;

                $data['result'] = 1;
                $data['message'] = Text::_('COM_SPSTGSRV_UPDATE_SUCCESS');
                $this->save($stage_id, $data, false);
                return true;
        }

        public function update_old() {

                error_reporting(0);

                JLoader::import('actions', JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_spstgsrv' . DIRECTORY_SEPARATOR . 'models');
                $model_actions = CYENDFactory::getModel('actions', 'SPStgSrvModel');
                $model = $this->getModel('installer');

                $params = JComponentHelper::getParams('com_spstgsrv');
                $data['package_path'] = $params->get('package_path') . 'components/com_spstgmng/packages/';
                $this->remote_log = $remote_log;
                $remote_log = $model_actions->getRemoteLog($stage_id);
                $data['extension_id'] = $remote_log->post->extension_id;

                $ip = $model->getIP();
                $message = $model->update($data);
                $data['package_name'] = $model->package_name;
                $data['version'] = $model->version;
                if ($message != 'success') {
                        $data['result'] = 0;
                        $data['message'] = $message;
                        $data['ip'] = $ip;
                        $this->save($stage_id, $data);
                        return false;
                }

                $data['ip'] = $ip;
                $data['result'] = 1;
                $data['message'] = Text::_('COM_SPSTGSRV_UPDATE_SUCCESS');
                $this->save($stage_id, $data);
                return true;
        }

        protected function save($stage_id, $data, $log = false) {

                $app = Factory::getApplication();
                $app->logout();

                if ($log) {
                        $model = $this->getModel('installer');
                        $model->save($data);
                }

                $parent_task = $this->input->get('parent_task');

                $model_actions = new \Joomla\Component\SpStgSrv\Site\Model\ActionsModel;
                $model_actions->save($data);

                $this->setRedirect($model_actions->url_manager . 'administrator/index.php?option=com_spstgmng&task=' . $parent_task . '&tmpl=component&stage_id=' . $stage_id);
        }
}
