<?php
/**
* @package XenCentral Framework
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @version 1.4.1
* @revision 125
*/


class XenCentral_Framework_Install
{
    protected static $_frameworkVersion;

    public static function _assertVersionCheck($required)
    {
        self::$_frameworkVersion = self::_detectFrameworkVersion();
        if (version_compare(self::$_frameworkVersion, $required) < 0) {
            throw new XenForo_Exception ("XenCentral Framework version $required and greater is required for this addon to work", true);
        }
    }

    public static function _detectFrameworkVersion()
    {
        /** @var XenForo_Model_Addon $addonModel */
        static $addonModel;
        if (is_null($addonModel)) {
            $addonModel = XenForo_Model::create('XenForo_Model_AddOn');
        }
        $addon = $addonModel->getAddOnById('xcfw');
        return $addon['version_string'];
    }

    public static function installFramework()
    {
        if (class_exists('XenCentral_PaymentApi_Module')) {
            XenCentral_PaymentApi_Module::getInstance()->install();
        }

        $db = XenForo_Application::getDb();

        $db->query("
			REPLACE INTO xf_content_type
				(content_type, addon_id, fields)
			VALUES
				('redirect_helper', 'xcfw', '')
		");
        $db->query("
            REPLACE INTO `xf_content_type_field` (`content_type`, `field_name`, `field_value`)
            VALUES
            ('redirect_helper', 'alert_handler_class', 'XenCentral_Framework_AlertHandler_Redirect')
        ");

        $db->query("
			CREATE TABLE IF NOT EXISTS xcfw_redirect_alert (
					`redirect_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
					`user_id` INT( 11 ) UNSIGNED NOT NULL,
					`message` VARCHAR( 255 ) NOT NULL,
					`message_params` BLOB NULL DEFAULT NULL ,
					`link` VARCHAR( 255 ) NOT NULL,
					`link_type` VARCHAR( 255 ) NOT NULL,
					`link_params` BLOB NULL DEFAULT NULL,
					`dateline` INT (11) UNSIGNED NOT NULL
				) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        /* @var $cacheModel XenForo_Model_ContentType */
        $cacheModel = XenForo_Model::create('XenForo_Model_ContentType');
        $cacheModel->rebuildContentTypeCache();
    }

    public static function uninstallFramework()
    {
        if (class_exists('XenCentral_PaymentApi_Module')) {
            XenCentral_PaymentApi_Module::getInstance()->uninstall();
        }
    }

    public static function upgradeTable($tableName, $tableDefinition)
    {
        if (strpos($tableDefinition, $tableName) === false) {
            // shouldn't happen
            throw new XenForo_Exception("$tableName installation query is invalid.");
        }
        $db = XenForo_Application::getDb();
        // check if table exists
        $created = $db->fetchRow("SHOW TABLES LIKE '$tableName'");

        if (!$created) {
            // just create the table
            $db->query($tableDefinition);
            return true;
        }

        // rename old table
        try {
            $created = $db->fetchRow("SHOW TABLES LIKE '{$tableName}_backup'");
            if ($created) {
                // drop backup
                $db->query("DROP TABLE IF EXISTS {$tableName}_backup");
            }

            $db->query("RENAME TABLE  `$tableName` TO  `{$tableName}_backup` ;");
        } catch (Exception $ex) {
            // not have rename permission
            throw $ex;
        }

        // run table creation query
        try {
            $db->query($tableDefinition);
        } catch (Exception $ex) {
            // recover the table
            $db->query("RENAME TABLE  `{$tableName}_backup` TO  `{$tableName}` ;");
            throw $ex;
        }

        // check if table is successfully created
        $created = $db->fetchRow("SHOW TABLES LIKE '$tableName'");

        if (!$created) {
            $db->query("RENAME TABLE  `{$tableName}_backup` TO  `{$tableName}` ;");

            return false;
        }

        $newCol = $oldCol = array();

        // try to move data
        $colResource = $db->fetchAll("SHOW COLUMNS IN {$tableName}");
        foreach ($colResource AS $col) {
            $newCol[] = $col['Field'];
        }

        $colResource = $db->fetchAll("SHOW COLUMNS IN {$tableName}_backup");
        foreach ($colResource AS $col) {
            $oldCol[] = $col['Field'];
        }

        $commonCols = array_intersect($newCol, $oldCol);

        try {
            $db->query("
				INSERT IGNORE INTO {$tableName} (`" . implode('`,`', $commonCols) . "`)
				SELECT `" . implode('`,`', $commonCols) . "` FROM {$tableName}_backup
			");
            $db->query("DROP TABLE IF EXISTS {$tableName}_backup");
        } catch (Exception $ex) {
            // failed to move the data, restore old table
            $db->query("DROP TABLE IF EXISTS {$tableName}");
            $db->query("RENAME TABLE  `{$tableName}_backup` TO  `{$tableName}` ;");
            throw $ex;
        }

        return true;
    }

    /**
     * @return XenCentral_Framework_Interface_Database
     */
    protected static function _getDbInterface()
    {
        static $interface;
        if (is_null($interface)) {
            $interface = new XenCentral_Framework_Interface_Database();
        }
        return $interface;
    }
}