<?php

/**
 * @package		SP Staging
 * @subpackage	Components
 * @copyright	KAINOTOMO PH LTD - All rights reserved.
 * @author		KAINOTOMO PH LTD
 * @link		https://www.kainotomo.com
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/

// no direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');

/**
 * Coordinate functions for Windows application install and update of extensions
 *
 * @author KAINOTOMO PH LTD <info@kainotomo.com>
 */
class SPStgSrvControllerInstaller extends JControllerLegacy {

        public $remote_log;

        public function __construct($config = array()) {
                parent::__construct($config);
                if (!isset($this->input)) {
                        $this->input = JFactory::getApplication()->input;
                }
        }

        public function install() {

                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');
                $model_actions->delete_log();

                $params = JComponentHelper::getParams('com_spstgsrv');
                $stage_id = $this->input->getString('stage_id');

                $post['sec'] = $this->input->get('sec');
                $post['downloadid'] = trim($this->getModel('downloadid'));
                $ip = $model->getIP();
                $post['ip'] = $ip;

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

                //Choose function type
                $data['package_name'] = $this->input->get('install_file');
                $pkg_arr = explode('.', $data['package_name']);
                $ext = strtolower($pkg_arr[count($pkg_arr) - 1]);

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

                        case 'php': //php
                                $message = $model->execute_php($data, true);
                                break;

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

                        default:
                                $message = $model->install($data, true);
                                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;
                }

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

        public function update() {
                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');
                $model_actions->delete_log();

                $input = $this->input;
                $stage_id = $input->getString('stage_id');

                $post['sec'] = $input->get('sec');
                $post['downloadid'] = trim($this->getModel('downloadid'));
                $ip = $model->getIP();
                $post['ip'] = $ip;
                $post['extension_id'] = $input->get('extension_id');

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

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

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

                        if ($file) {
                                JFactory::getApplication()->setUserState('com_joomlaupdate.file', $file);
                                $url = 'index.php?option=com_joomlaupdate&task=update.install&' . JFactory::getSession()->getFormToken() . '=1';
                                JLog::add(JText::sprintf('COM_JOOMLAUPDATE_UPDATE_LOG_FILE', $file), JLog::INFO, 'Update');
                        } else {
                                JFactory::getApplication()->setUserState('com_joomlaupdate.file', null);

                                $data['result'] = 0;
                                $data['message'] = JText::_('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'] = JText::_('COM_SPSTGSRV_UPDATE_SUCCESS');
                $this->save($stage_id, $data, false);
                return true;
        }

        /**
         * Get object of the defined model
         * @param type $name Name of the model
         * @param type $prefix Prefix of the Model
         * @param type $config Configuration array if any
         * @return type The actual object of the described model
         */
        public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true)) {
                return parent::getModel($name, $prefix, array('ignore_request' => false));
        }

        /**
         * Save the log, logout from the administrator and redirect
         * 
         * @param type $stage_id The stage id as defined in manager database
         * @param type $data An array of data with the result of the operation
         * @param type $log Save the log if true
         */
        protected function save($stage_id, $data, $log = false) {

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

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

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

                $model_actions = $this->getModel('actions');
                $model_actions->save($data);

                if ($data['result'] == '1') {
                        $app->redirect(Juri::root());
                } else {
                        if (isset($data['message'])) {
                                echo $data['message'];
                        } else {
                                echo JText::_('JERROR_AN_ERROR_HAS_OCCURRED');
                        }
                }
        }

}
