<?php

class Waindigo_InstallUpgrade_Install_Controller extends Waindigo_Install
{

    protected $_resourceManagerUrl = 'https://xenforo.com/community/resources/install-upgrade-by-waindigo.2035/';

    protected function _preInstall()
    {
        $this->_uninstallCopyrightNoticeAddOn();
        
        $this->_emptyLoginTableIfUpgradeFrom104();
        $this->_renameOldOptionsIfUpgradeFrom108();
        
        $this->_createUniqueIdentifier();
        
        $this->_randomizeCronEntry();
    }

    protected function _uninstallCopyrightNoticeAddOn()
    {
        $addOn = $this->getModelFromCache('XenForo_Model_AddOn')->getAddOnById('Waindigo_CopyrightNotice');
        
        if ($addOn) {
            if (XenForo_Application::$versionId >= 1020000 && $this->_xml) {
                $xenOptions = XenForo_Application::get('options');
                foreach ($this->_xml->optiongroups->option as $option) {
                    /* @var $option SimpleXMLElement */
                    switch ($option['option_id']) {
                        case 'waindigo_copyrightPosition_installUpgrade':
                            $option->default_value = $xenOptions->waindigo_move_copyright;
                            break;
                        case 'waindigo_installUpgrade_copyrightVisibility':
                            if ($xenOptions->waindigo_disable_copyright) {
                                $option->default_value = 'none';
                            } elseif ($xenOptions->waindigo_disable_css_copyright) {
                                $option->default_value = 'css';
                            }
                            break;
                    }
                }
            }
            $dw = XenForo_DataWriter::create('XenForo_DataWriter_AddOn');
            $dw->setExistingData($addOn);
            $dw->delete();
        }
    }

    protected function _emptyLoginTableIfUpgradeFrom104()
    {
        if ($this->_isTableExists('xf_install_upgrade_login')) {
            $describeTable = $this->_db->describeTable('xf_install_upgrade_login');
            $rows = array_keys($describeTable);
            $deleteAll = true;
            foreach ($rows as $row) {
                if ($row == 'unique_key') {
                    $deleteAll = false;
                }
            }
            if ($deleteAll) {
                $this->_db->delete('xf_install_upgrade_login');
            }
        }
    }

    protected function _renameOldOptionsIfUpgradeFrom108()
    {
        $options = array(
            'waindigo_copyrightVisibility_installUpgrade' => 'waindigo_installUpgrade_copyrightVisibility',
            'waindigo_copyrightPosition_installUpgrade' => 'waindigo_installUpgrade_copyrightPosition',
            'waindigo_showCopyrightRobots_installUpgrade' => 'waindigo_installUpgrade_showCopyrightRobots'
        );
        
        foreach ($options as $oldOption => $newOption) {
            $this->_db->update('xf_option', array(
                'option_id' => $newOption
            ), 'option_id = ' . $this->_db->quote($oldOption));
        }
    }

    protected function _createUniqueIdentifier()
    {
        $xenOptions = XenForo_Application::get('options');
        if (XenForo_Application::$versionId >= 1020000 && $this->_xml) {
            foreach ($this->_xml->optiongroups->option as $option) {
                /* @var $option SimpleXMLElement */
                switch ($option['option_id']) {
                    case 'waindigo_installUpgrade_uniqueIdentifier':
                        if ($xenOptions->waindigo_premium_uniqueIdentifier) {
                            $option->default_value = $xenOptions->waindigo_premium_uniqueIdentifier;
                        } else {
                            $option->default_value = XenForo_Application::generateRandomString(30);
                        }
                        break;
                }
            }
        }
    }

    protected function _randomizeCronEntry()
    {
        if (XenForo_Application::$versionId >= 1020000 && $this->_xml) {
            foreach ($this->_xml->cron->entry as $entry) {
                $entry[0] = json_encode(
                    array(
                        'day_type' => 'dom',
                        'dom' => array(
                            -1
                        ),
                        'hours' => array(
                            rand(0, 23)
                        ),
                        'minutes' => array(
                            rand(0, 59)
                        )
                    ));
            }
        }
    }

    protected function _getTables()
    {
        return array(
            'xf_install_upgrade_login' => array(
                'login_id' => 'int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
                'username' => 'varchar(255) NOT NULL',
                'password' => 'varchar(255) NOT NULL',
                'host' => 'varchar(255) NOT NULL',
                'path' => 'varchar(255) NOT NULL',
                'unique_key' => 'varchar(32) NOT NULL',
                'user_id' => 'int UNSIGNED NOT NULL DEFAULT 0'
            ),
            'xf_addon_files_waindigo' => array(
                'addon_id' => 'varbinary(25) NOT NULL',
                'filename_md5' => 'varchar(32) NOT NULL',
                'filename' => 'MEDIUMTEXT',
                'version_id' => 'int UNSIGNED NOT NULL DEFAULT 0',
                'version_string' => 'varchar(30) NOT NULL DEFAULT \'\''
            )
        );
    }

    protected function _getUniqueKeys()
    {
        return array(
            'xf_install_upgrade_login' => array(
                'unique_key' => array(
                    'unique_key'
                )
            )
        );
    }

    protected function _getPrimaryKeys()
    {
        return array(
            'xf_addon_files_waindigo' => array(
                'addon_id',
                'filename_md5'
            )
        );
    }

    protected function _getTableChanges()
    {
        return array(
            'xf_addon' => array(
                'install_upgrade_filename' => 'varchar(255) NOT NULL DEFAULT \'\'',
                'install_upgrade_updated' => 'tinyint NOT NULL DEFAULT \'0\''
            )
        );
    }

    protected function _postInstallAfterTransaction()
    {
        if (XenForo_Application::$versionId > 1020000) {
            XenForo_Application::defer('Waindigo_InstallUpgrade_Deferred_UpdateCheck', array(), 'WaindigoIuUpdateCheck');
        } else {
            /* @var $addOnModel XenForo_Model_AddOn */
            $addOnModel = $this->getModelFromCache('XenForo_Model_AddOn');
            
            $addOns = $addOnModel->getAllAddOns();
            
            /* @var $installUpgradeModel Waindigo_InstallUpgrade_Model_InstallUpgrade */
            $installUpgradeModel = $this->getModelFromCache('Waindigo_InstallUpgrade_Model_InstallUpgrade');
            
            $installUpgradeModel->checkForAddOnUpdates($addOns);
        }
    }

    protected function _postUninstall()
    {
        XenForo_Application::setSimpleCacheData('installUpgradeBroadcast', false);
    }
}