<?php

namespace Aps\App\Joomla;

define('APS_BOOTSTRAP', getenv('WEB___DIR') . '/installation/application/bootstrap.php');

require_once __DIR__ . '/bootstrap.php';

/**
 * Simulate native controllers - process native Joomla models
 */
class Installer
{

    protected function getOptions()
    {
        $options = array(
            'db_type' => apsGetDatabaseType(),
            'db_host' => apsGetDatabaseHost(),
            'db_user' => getenv('DB_main_LOGIN'),
            'db_pass' => getenv('DB_main_PASSWORD'),
            'db_name' => getenv('DB_main_NAME'),
            'db_prefix' => getenv('DB_main_PREFIX') ?: 'jos_',
            'db_created' => true,
            'db_select' => true,
            'db_old' => 'backup', // not "remove"
            'language' => getenv('SETTINGS_locale'),
            'sample_file' => getenv('SETTINGS_install_sample_data') ? 'sample_data.sql' : null,
        );
        return $options;
    }

    /*
        ---
        http://joomla.loc/installation/index.php?tmpl=body&view=summary
        http://joomla.loc/installation/index.php
        post:
            //format: json
            //jform[sample_file]=sample_data.sql
            //jform[summary_email]=1
            //jform[summary_email_passwords]=0
            //task=summary
            //7979d4e42223879dca92294998a6af36=1
        http://joomla.loc/installation/index.php?tmpl=body&view=install
        http://joomla.loc/installation/index.php?task=InstallDatabase_backup
        http://joomla.loc/installation/index.php?task=InstallDatabase
        http://joomla.loc/installation/index.php?task=InstallSample
        http://joomla.loc/installation/index.php?task=InstallConfig
        http://joomla.loc/installation/index.php?task=InstallEmail
        http://joomla.loc/installation/index.php?tmpl=body&view=complete
        http://joomla.loc/installation/index.php?tmpl=body&view=languages
        post:
            //	format: json
            //cid[]=51
            //task=InstallLanguages
            //02f3403b7d4527b8ea04eec7005b04cc=1
        http://joomla.loc/installation/index.php?tmpl=body&view=defaultlanguage
        post:
            //	format: json
            //jform[activateMultilanguage]=0
            //jform[installLocalisedContent]=1
            //jform[activatePluginLanguageCode]=0
            //administratorlang=en-GB
            //frontendlang=en-GB
            //task=setdefaultlanguage
            //7b4dda7958f4a0471c70071c08d50312=1
        http://joomla.loc/installation/index.php?tmpl=body&view=remove
        http://joomla.loc/installation/index.php?task=removefolder
    */
    public function execute()
    {
        // $model = new \InstallationModelSetup;
        // $options = $model->getOptions();
        $options = $this->getOptions();

        // \InstallationModelDatabase::createTables use short file paths to *.sql
        chdir(JPATH_INSTALLATION);

        //workaround for
        //PHP Fatal error: Call to a member function get() on a non-object in .../libraries/joomla/session/handler/joomla.php on line 71
        \JFactory::$session = new \JSessionAps;

        // \InstallationControllerInstallDatabase_backup::execute
        // \InstallationControllerInstallDatabase::execute
        // \InstallationControllerInstallSample::execute
        $this->processDatabase($options);

        // \InstallationControllerInstallConfig::execute
        $this->createConfigAndSuperuser($options);

        // \InstallationControllerInstallEmail::execute
        // skip

        // \InstallationControllerInstallLanguages::execute
        // \InstallationControllerSetdefaultlanguage::execute
        $this->processLanguages($options);

        // \InstallationControllerRemovefolder::execute
        $this->removeInstallationFolder();
    }

    protected function processDatabase($options)
    {
        $db = new \InstallationModelDatabase;

        // \InstallationControllerInstallDatabase_backup::execute
        if (!$db->handleOldDatabase($options)) {
            throw new \Exception();
        }

        // \InstallationControllerInstallDatabase::execute
        if (!$db->createTables($options)) {
            throw new \Exception();
        }

        // \InstallationControllerInstallSample::execute
        if (!$db->installSampleData($options)) {
            throw new \Exception();
        }
    }

    protected function createConfigAndSuperuser($options)
    {
        $options['site_offline'] = false;
        $options['site_name'] = getenv('SETTINGS_title');
        $options['helpurl'] = null;
        $options['site_metadesc'] = $options['site_name'];
        $options['admin_email'] = getenv('SETTINGS_admin_email');
        // super admin
        $options['admin_password'] = getenv('SETTINGS_admin_password');
        $options['admin_user'] = trim(getenv('SETTINGS_admin_name'));

        // \InstallationControllerInstallConfig::execute
        $configuration = new \InstallationModelConfiguration;
        if (!$configuration->setup($options)) {
            throw new \Exception();
        }
    }

    protected function processLanguages($options)
    {
        // \InstallationControllerInstallLanguages::execute
        // install archives from APS only
        $zipFile = JPATH_ROOT . '/tmp/distributives/' . $options['language'] . '_joomla_lang_full.zip';
        if (file_exists($zipFile)) {
            $package = \JInstallerHelper::unpack($zipFile);

            $installer = new \JInstaller;
            if (!$installer->install($package['dir'])) {
                throw new \Exception();
            }
            \JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);
        }

        // \InstallationControllerSetdefaultlanguage::execute
        $model = new \InstallationModelLanguages;
        $model->setDefault($options['language'], 'administrator');
        $model->setDefault($options['language'], 'site');
    }

    protected function removeInstallationFolder()
    {
        // \InstallationControllerRemovefolder::execute
        // Fatal error:
        // https://issues.joomla.org/tracker/joomla-cms/4703
        // https://github.com/joomla/joomla-cms/issues/4703

        \JFolder::delete(JPATH_INSTALLATION);
        \JFile::delete(JPATH_ROOT . '/joomla.xml');

        // Rename the robots.txt.dist file if robots.txt doesn't exist
        file_exists(JPATH_ROOT . '/robots.txt') || copy(JPATH_ROOT . '/robots.txt.dist', JPATH_ROOT . '/robots.txt');

        // copy: htaccess.txt -> .htaccess
        file_exists(JPATH_ROOT . '/.htaccess') || copy(JPATH_ROOT . '/htaccess.txt', JPATH_ROOT . '/.htaccess');

        // IIS url rewrite rules
        file_exists(JPATH_ROOT . '/web.config') || copy(JPATH_ROOT . '/web.config.txt', JPATH_ROOT . '/web.config');
    }
}