<?php
/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/

class XenCentral_AdServer_Install
{
	public static function installCode()
	{
        if(!class_exists('XenCentral_Framework_Install')) {
            throw new XenForo_Exception("Please install the latest version of XenCentral Framework available in Downloads section before installing this addon.", true);
        }

        XenCentral_Framework_Install::_assertVersionCheck('1.4.0');

        $db = XenForo_Application::getDb();

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_zone` (
				`zoneId`	int(11) unsigned NOT NULL AUTO_INCREMENT,
				`title` varchar(255) NOT NULL DEFAULT '',
				`locations` MEDIUMTEXT NOT NULL,
				`width` int(11) unsigned NOT NULL DEFAULT 0,
				`height` int(11) unsigned NOT NULL DEFAULT 0,
				`force_dimensions` tinyint(1) unsigned NOT NULL DEFAULT 0,
				`rotate` tinyint(1) unsigned NOT NULL DEFAULT 0,
				`rotate_zone` tinyint(1) unsigned NOT NULL DEFAULT 0,
				`auto_rotate` mediumint(5) unsigned NOT NULL DEFAULT 0,
				`display_order` int(11) unsigned NOT NULL DEFAULT 10,
				`active` tinyint(1) unsigned NOT NULL DEFAULT 1,
				PRIMARY KEY (`zoneId`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_banner` (
				`bannerId`	int(11) unsigned NOT NULL AUTO_INCREMENT,
				`zoneId`	int(11) unsigned NOT NULL,
				`title` varchar(255) NOT NULL,
				`url` TEXT NOT NULL,
				`image` TEXT NOT NULL,
				`code` MEDIUMTEXT NOT NULL,
				`display_order` int(11) NOT NULL DEFAULT 10,
				`is_placeholder` tinyint(1) NOT NULL DEFAULT 0,
				`mobile_view_code` MEDIUMTEXT NOT NULL,
				`tablet_view_code` MEDIUMTEXT NOT NULL,
				`active` tinyint(1) NOT NULL DEFAULT 1,
				PRIMARY KEY (`bannerId`),
				KEY zoneId (`zoneId`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_transaction_log` (
				`log_id`	int(11) unsigned NOT NULL AUTO_INCREMENT,
				`content_type` varchar(255) NOT NULL,
				`content_id`	int(11) unsigned NOT NULL,
				`user_id`	int(11) unsigned NOT NULL,
				`dateline`	int(11) unsigned NOT NULL,
				`payment_info_id`	int(11) unsigned NOT NULL,
				`transaction_id` varchar(255) NOT NULL,
				PRIMARY KEY (`log_id`),
				KEY content_type (`content_type`),
				KEY user_id (`user_id`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_credit_transaction_log` (
				`log_id`	int(11) unsigned NOT NULL AUTO_INCREMENT,
				`user_id`	int(11) unsigned NOT NULL,
				`dateline`	int(11) unsigned NOT NULL,
				`payment_info_id`	int(11) unsigned NOT NULL,
				`transaction_id` varchar(255) NOT NULL,
				PRIMARY KEY (`log_id`),
				KEY user_id (`user_id`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_impressions_zone` (
				`zoneId`	int(11) unsigned NOT NULL,
				`dateline`	int(11) unsigned NOT NULL,
				`count`	    int(11) unsigned NOT NULL,
				PRIMARY KEY (`zoneId`, `dateline`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_impressions_banner` (
				`bannerId`	int(11) unsigned NOT NULL,
				`dateline`	int(11) unsigned NOT NULL,
				`count`	    int(11) unsigned NOT NULL,
				PRIMARY KEY (`bannerId`, `dateline`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_user_data` (
				`user_id`	int(11) unsigned NOT NULL,
				`ad_credit` numeric(15,3) DEFAULT 0,
				PRIMARY KEY (`user_id`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        try {
            $db->query($q = "
                CREATE TABLE IF NOT EXISTS `xcas_impressions_temp` (
                    `itemId`	int(11) unsigned NOT NULL,
                    `itemType`	varchar(255) NOT NULL,
                    `dateline`	int(11) unsigned NOT NULL
                ) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
            ");
        } catch (Exception $ex) {
            try {
                $db->query('ALTER TABLE xcas_impressions_temp DISCARD TABLESPACE');
            } catch(Exception $ex) {

            }

            try {
                $db->query('ALTER TABLE xcas_impressions_temp IMPORT TABLESPACE');
            } catch(Exception $ex) {

            }

            try {
                $db->query("DROP TABLE xcas_impressions_temp");
            } catch (Exception $ex2) {

            }

            $db->query($q = "
                CREATE TABLE `xcas_impressions_temp` (
                    `itemId`	int(11) unsigned NOT NULL,
                    `itemType`	varchar(255) NOT NULL,
                    `dateline`	int(11) unsigned NOT NULL
                ) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
            ");
        }

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_clicks_zone` (
				`logId`	    int(11) unsigned NOT NULL AUTO_INCREMENT,
				`zoneId`	int(11) unsigned NOT NULL,
				`dateline`	int(11) unsigned NOT NULL,
				`referrer`  varchar(255) NOT NULL,
				`ip_address`  int(11) unsigned NOT NULL,
				`is_user`  tinyint(1) unsigned NOT NULL DEFAULT 0,
				PRIMARY KEY (`logId`),
				KEY zoneId (zoneId),
				KEY referrer (referrer),
				KEY ip_address (ip_address),
				KEY is_user (is_user)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_clicks_banner` (
				`logId`	    int(11) unsigned NOT NULL AUTO_INCREMENT,
				`bannerId`	int(11) unsigned NOT NULL,
				`dateline`	int(11) unsigned NOT NULL,
				`referrer`  varchar(255) NOT NULL,
				`ip_address`  int(11) unsigned NOT NULL,
				`is_user`  tinyint(1) unsigned NOT NULL DEFAULT 0,
				PRIMARY KEY (`logId`),
				KEY bannerId (bannerId),
				KEY referrer (referrer),
				KEY ip_address (ip_address),
				KEY is_user (is_user)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_click_credit_log` (
				`logId`	    int(11) unsigned NOT NULL AUTO_INCREMENT,
				`bannerId`	int(11) unsigned NOT NULL,
				`ownerId`	int(11) unsigned NOT NULL,
				`bannerClickId`	int(11) unsigned NOT NULL,
				`zoneClickId`	int(11) unsigned NOT NULL,
				`price`	numeric(15,3) unsigned NOT NULL,
				PRIMARY KEY (`logId`),
				KEY bannerId (bannerId)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        $db->query($q = "
			CREATE TABLE IF NOT EXISTS `xcas_stats_summary` (
				`content_type`  CHAR(8) NOT NULL,
				`content_id`  int(11) unsigned NOT NULL,
				`impressions`	int(11) unsigned NOT NULL DEFAULT 0,
				`clicks`	int(11) unsigned NOT NULL DEFAULT 0,
				`running_time`  varchar(255) NOT NULL DEFAULT 0,
				PRIMARY KEY (`content_type`, `content_id`)
			) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
		");

        // add some fields to zones table
        $table=$db->describeTable('xcas_zone');
        if (!isset($table['packages'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD packages TEXT NULL DEFAULT NULL
            ");
        }

        if (!isset($table['user_criteria'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD  `user_criteria` mediumblob NOT NULL,
                ADD  `page_criteria` mediumblob NOT NULL
            ");
        }

        if (!isset($table['user_criteria_not'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD  `user_criteria_not` mediumblob NOT NULL,
                ADD  `page_criteria_not` mediumblob NOT NULL
            ");
        }

        if (!isset($table['user_zone'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD user_zone TINYINT(1) UNSIGNED NOT NULL DEFAULT 0
            ");
        }

        if (!isset($table['randomize_banners'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD randomize_banners TINYINT(1) UNSIGNED NOT NULL DEFAULT 0
            ");
        }



        if (!isset($table['last_update'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD last_update INT(11) UNSIGNED NOT NULL DEFAULT 0
            ");
        }



        if (!isset($table['slot_count'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD slot_count INT(11) UNSIGNED NOT NULL DEFAULT 0
            ");
        }

        if (!isset($table['use_placeholder'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD use_placeholder TINYINT(1) UNSIGNED NOT NULL DEFAULT 0
            ");
        }

        if (!isset($table['owners'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD owners varchar(255) NOT NULL DEFAULT ''
            ");
        }

        if (!isset($table['creator_user_id'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD creator_user_id INT(11) UNSIGNED NOT NULL DEFAULT 0
            ");
        }

        if (!isset($table['price_per_click'])) {
            $db->query("
                ALTER TABLE xcas_zone
                ADD price_per_click numeric(15,3) DEFAULT 0
            ");
        }

        // add active to/from code
        $table=$db->describeTable('xcas_banner');
        if (!isset($table['user_id'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD user_id varchar(255) NOT NULL DEFAULT ''
            ");
        } else {
            if ($table['user_id']['DATA_TYPE'] != "varchar") {
                $db->query("ALTER TABLE  `xcas_banner` CHANGE  `user_id`  `user_id` varchar( 255)");
            }
        }

        if (!isset($table['status'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD status ENUM('active', 'inactive', 'moderated', 'paused') NOT NULL DEFAULT 'active'
            ");
        } else {
            if($table['status']['DATA_TYPE']!="enum('active','inactive','moderated','paused')") {
                $db->query("
                    ALTER TABLE xcas_banner
                    CHANGE status status ENUM('active', 'inactive', 'moderated', 'paused') NOT NULL DEFAULT 'active'
                ");
            }
            // active - will be served
            // inactive - will be available for activation, also the status once active is expired
            // moderated - will not be available for activation
            // paused - status after user campaign zone is inactivated and changes back to active once credit is filled-up
        }

        if (!isset($table['text'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD text VARCHAR(255) NOT NULL DEFAULT ''
            ");
        }

        if(!isset($table['active_from'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD active_from INT(11) UNSIGNED NOT NULL DEFAULT 0,
                ADD active_to INT(11) UNSIGNED NOT NULL DEFAULT 0
            ");
        }

        if (!isset($table['impressions_left'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD impressions_left INT(11) NOT NULL DEFAULT -1
            ");
        }

        if (!isset($table['safe_mode'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD safe_mode TINYINT(1) UNSIGNED NOT NULL DEFAULT 0
            ");
        }

        if(!isset($table['mobile_view_code'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD `mobile_view_code` MEDIUMTEXT NOT NULL
            ");
        }
        if(!isset($table['tablet_view_code'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD `tablet_view_code` MEDIUMTEXT NOT NULL
            ");
        }

        if(!isset($table['notifications_sent'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD `notifications_sent` TINYINT(5) UNSIGNED NOT NULL DEFAULT 0
            ");
        }

        if(!isset($table['tags'])) {
            $db->query("
                ALTER TABLE xcas_banner
                ADD `tags` mediumblob NULL DEFAULT NULL
            ");
        }



        $table=$db->describeTable('xcas_clicks_banner');
        
        if ($table['ip_address']['DATA_TYPE'] != "varbinary(16)") {
            $db->query("
                ALTER TABLE xcas_clicks_banner
                CHANGE ip_address ip_address varbinary(16) NOT NULL
            ");
        }

        $table=$db->describeTable('xcas_clicks_zone');

        if ($table['ip_address']['DATA_TYPE'] != "varbinary(16)") {
            $db->query("
                ALTER TABLE xcas_clicks_zone
                CHANGE ip_address ip_address varbinary(16) NOT NULL
            ");
        }

        $table = $db->describeTable('xcas_user_data');
        if (!isset($table['excluded_campaign_domains'])) {
            $db->query("
                ALTER TABLE xcas_user_data
                ADD `excluded_campaign_domains` mediumblob NULL DEFAULT NULL
            ");
        }

        $db->query("
			REPLACE INTO xf_content_type
				(content_type, addon_id, fields)
			VALUES
				('banner', 'xcas', '')
		");
        $db->query("
            REPLACE INTO `xf_content_type_field` (`content_type`, `field_name`, `field_value`)
            VALUES
            ('banner', 'alert_handler_class', 'XenCentral_AdServer_AlertHandler_Banner')
        ");

        $db->query("
            REPLACE INTO `xf_content_type_field` (`content_type`, `field_name`, `field_value`)
            VALUES
            ('banner', 'tag_handler_class', 'XenCentral_AdServer_TagHandler_Banner')
        ");
        $db->query("
            REPLACE INTO `xf_content_type_field` (`content_type`, `field_name`, `field_value`)
            VALUES
            ('banner', 'attachment_handler_class', 'XenCentral_AdServer_AttachmentHandler_Banner')
        ");

        $table=$db->describeTable('xcas_credit_transaction_log');

        if(!isset($table['admin_user_id'])) {
            $db->query('
                ALTER TABLE xcas_credit_transaction_log
                ADD admin_user_id INT (11) UNSIGNED NOT NULL DEFAULT 0,
                ADD manual_transaction_data MEDIUMBLOB NULL DEFAULT NULL
            ');
        }


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

        XenForo_Application::setSimpleCacheData('xcas_zone_cache', false);
        XenForo_Application::setSimpleCacheData('xcas_banner_cache', false);


        // clean cache, just in case
        // XenForo_Model::create('XenCentral_Framework_Model_Cache')->clean();

		return true;
	}

	public static function uninstallCode()
	{
		$db = XenForo_Application::getDb();

        /*$db->query("
            DROP TABLE IF EXISTS `xcas_zone`
        ");*/

		return true;
	}
}