<?php

class AVForums_Competitions_Install
{
	public static function installer($previous)
	{
		if (XenForo_Application::$versionId < 1020070)
		{
			throw new XenForo_Exception('This add-on requires XenForo 1.2.0 or higher.', true);
		}

		$db = XenForo_Application::get('db');

		if (!$previous)
		{
			foreach (self::getTables() AS $tableSql)
			{
				try
				{
					$db->query($tableSql);
				}
				catch (Zend_Db_Exception $e) {}
			}

			foreach (self::getData() AS $tableSql)
			{
				try
				{
					$db->query($tableSql);
				}
				catch (Zend_Db_Exception $e) {}
			}

			foreach (self::getAlters() AS $tableSql)
			{
				try
				{
					$db->query($tableSql);
				}
				catch (Zend_Db_Exception $e) {}
			}

			if (!XenForo_Application::getSimpleCacheData('competitionTerms'))
			{
				XenForo_Application::setSimpleCacheData(
					'competitionTerms',
					'[LIST][*]Employees, principals, and immediate family of this site are ineligible to enter.[/LIST]'
				);
			}
		}
		else
		{
			if ($previous['version_id'] < 1000670)
			{
				try
				{
					$db->query('ALTER TABLE xf_user CHANGE COLUMN competition_entries competition_entries BLOB NULL');
				}
				catch (Zend_Db_Exception $e) {}
			}
			
			if ($previous['version_id'] < 1001000)
			{
				try
				{
					$db->query("ALTER TABLE xf_avforums_competitions_entry ADD COLUMN `answer_state_original` enum('correct','incorrect') NOT NULL DEFAULT 'incorrect'  AFTER `answer_state`");
				}
				catch (Zend_Db_Exception $e) {}

				try
				{
				    $db->query("UPDATE xf_avforums_competitions_entry SET `answer_state_original` = `answer_state`");
				}
				catch (Zend_Db_Exception $e) {}

				try
				{
				    $db->query("
            			INSERT IGNORE INTO xf_content_type_field
            				(content_type, field_name, field_value)
            			VALUES
            				('avforums_competition', 'sitemap_handler_class', 'AVForums_Competitions_SitemapHandler_Competition')
				      ");
				}
				catch (Zend_Db_Exception $e) {}
				
				//$this->getModelFromCache('XenForo_Model_ContentType')->rebuildContentTypeCache();
			}
		}
	}

	public static function uninstaller()
	{
		$db = XenForo_Application::get('db');

		self::removeAllImages($db);

		foreach (self::getTables() AS $tableName => $tableSql)
		{
			try
			{
				$db->query("DROP TABLE IF EXISTS `$tableName`");
			}
			catch (Zend_Db_Exception $e) {}
		}

		try
		{
			$db->query("ALTER TABLE xf_user DROP competition_entries");
		}
		catch (Zend_Db_Exception $e) {}

		XenForo_Application::setSimpleCacheData(
			'competitionTerms', false
		);

		XenForo_Application::setSimpleCacheData(
			'competitionCount', false
		);

		XenForo_Application::setSimpleCacheData(
			'competitionsCache', false
		);

		XenForo_Application::setSimpleCacheData(
			'competitionsCacheFull', false
		);


		XenForo_Db::beginTransaction($db);

		$contentTypeTables = array(
			'xf_content_type',
			'xf_content_type_field',
			'xf_user_alert'
		);
		foreach ($contentTypeTables AS $table)
		{
			$db->delete($table, 'content_type = (' . $db->quote('avforums_competition') . ')');
		}

		$db->delete('xf_permission_entry', "permission_group_id = 'competitions'");

		XenForo_Db::commit($db);
	}

	public static function removeAllImages($db)
	{
		/** @var $competitionModel AVForums_Competitions_Model_Competition */
		$competitionModel = XenForo_Model::create('AVForums_Competitions_Model_Competition');

		$competitions = $competitionModel->getCompetitions();

		foreach ($competitions AS $competition)
		{
			$attachmentIds = array(
				'thumb' => $competition['thumb_attachment_id'],
				'image1' => $competition['image1_attachment_id'],
				'image2' => $competition['image2_attachment_id'],
				'image3' => $competition['image3_attachment_id'],
				'image4' => $competition['image4_attachment_id']
			);
			$attachments = $competitionModel->getAttachmentsByAttachmentIds($attachmentIds);

			foreach ($attachmentIds AS $type => $attachmentId)
			{
				if (!empty($attachments[$attachmentId]))
				{
					$attachmentIds[$attachmentId] = array(
						'type' => $type,
						'attachment_id' => $attachmentId
					);
				}
			}

			foreach ($attachments AS $attachment)
			{
				$db->update('xf_attachment', array(
					'unassociated' => 1
				), 'attachment_id = ' . $db->quote($attachment['attachment_id']));

				@unlink ($competitionModel->getCompetitionImagePath($attachment, null, $attachmentIds[$attachment['attachment_id']]['type']));
			}
		}
	}

	public static function getTables()
	{
		$tables = array();

		$tables['xf_avforums_competitions'] = "
			CREATE TABLE IF NOT EXISTS `xf_avforums_competitions` (
			  `competition_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
			  `competition_title` varchar(255) NOT NULL DEFAULT '',
			  `user_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `username` varchar(50) NOT NULL DEFAULT '',
			  `competition_date` int(10) unsigned NOT NULL DEFAULT '0',
			  `competition_state` enum('closed','open','completed') NOT NULL DEFAULT 'open',
			  `competition_published` tinyint(3) unsigned NOT NULL DEFAULT '0',
			  `competition_type` enum('competition','prize_draw') NOT NULL DEFAULT 'competition',
			  `force_thumbnail` tinyint(3) unsigned NOT NULL DEFAULT '0',
			  `competition_prize` varchar(255) NOT NULL DEFAULT '',
			  `prize_value` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',
			  `competition_text` text NOT NULL,
			  `competition_start` int(10) unsigned NOT NULL DEFAULT '0',
			  `competition_end` int(10) unsigned NOT NULL DEFAULT '0',
			  `external_link` varchar(500) NOT NULL DEFAULT '',
			  `competition_question` text NOT NULL,
			  `question_hint` text NOT NULL,
			  `competition_answers` blob NOT NULL,
			  `restrictions` text NOT NULL,
			  `view_user_groups` blob NOT NULL,
			  `enter_user_groups` blob NOT NULL,
			  `territories` blob NOT NULL,
			  `number_of_winners` int(10) unsigned NOT NULL DEFAULT '0',
			  `number_of_runners_up` int(10) unsigned NOT NULL DEFAULT '0',
			  `submit_text` text NOT NULL,
			  `sponsor` varchar(100) NOT NULL DEFAULT '',
			  `minimum_age` int(10) unsigned NOT NULL DEFAULT '0',
			  `marketing_message` text NOT NULL,
			  `competition_opt_out` tinyint(3) unsigned NOT NULL DEFAULT '0',
			  `competition_images_left` tinyint(3) unsigned NOT NULL DEFAULT '0',
			  `competition_hide_form` tinyint(3) unsigned NOT NULL DEFAULT '0',
			  `competition_node_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `competition_thread_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `competition_thread_user_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `competition_thread_username` varchar(50) NOT NULL DEFAULT '',
			  `competition_view_count` int(10) unsigned NOT NULL DEFAULT '0',
			  `competition_entry_count` int(10) NOT NULL DEFAULT '0',
			  `competition_correct_count` int(10) NOT NULL DEFAULT '0',
			  `competition_optin_count` int(10) NOT NULL DEFAULT '0',
			  `thumb_attachment_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `thumb_crop_area` blob NOT NULL,
			  `thumb_caption` text NOT NULL,
			  `thumb_url` varchar(500) NOT NULL DEFAULT '',
			  `thumb_alt` varchar(500) NOT NULL DEFAULT '',
			  `image1_attachment_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `image1_crop_area` blob NOT NULL,
			  `image1_caption` text NOT NULL,
			  `image1_url` varchar(500) NOT NULL DEFAULT '',
			  `image1_alt` varchar(500) NOT NULL DEFAULT '',
			  `image2_attachment_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `image2_crop_area` blob NOT NULL,
			  `image2_caption` text NOT NULL,
			  `image2_url` varchar(500) NOT NULL DEFAULT '',
			  `image2_alt` varchar(500) NOT NULL DEFAULT '',
			  `image3_attachment_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `image3_crop_area` blob NOT NULL,
			  `image3_caption` text NOT NULL,
			  `image3_url` varchar(500) NOT NULL DEFAULT '',
			  `image3_alt` varchar(500) NOT NULL DEFAULT '',
			  `image4_attachment_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `image4_crop_area` blob NOT NULL,
			  `image4_caption` text NOT NULL,
			  `image4_url` varchar(500) NOT NULL DEFAULT '',
			  `image4_alt` varchar(500) NOT NULL DEFAULT '',
			  `competition_winners` blob NOT NULL,
			  PRIMARY KEY (`competition_id`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		$tables['xf_avforums_competitions_entry'] = "
			CREATE TABLE IF NOT EXISTS `xf_avforums_competitions_entry` (
			  `entry_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
			  `competition_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `user_id` int(10) unsigned NOT NULL DEFAULT '0',
			  `username` varchar(50) NOT NULL DEFAULT '',
			  `entry_state` enum('loser','winner','runner_up') NOT NULL DEFAULT 'loser',
			  `answer_state` enum('correct','incorrect') NOT NULL DEFAULT 'incorrect',
			  `answer_state_original` enum('correct','incorrect') NOT NULL DEFAULT 'incorrect',
			  `given_answer` varchar(500) NOT NULL DEFAULT '0',
			  `opt_in` tinyint(3) unsigned NOT NULL DEFAULT '0',
			  `entry_date` int(10) unsigned NOT NULL DEFAULT '0',
			  PRIMARY KEY (`entry_id`),
			  UNIQUE KEY `competition_id_user_id` (`competition_id`,`user_id`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		return $tables;
	}

	public static function getData()
	{
		$data = array();

		$data['xf_content_type'] = "
			INSERT IGNORE INTO xf_content_type
				(content_type, addon_id, fields)
			VALUES
				('avforums_competition', 'AVForums_Competitions', '')
		";

		$data['xf_content_type_field'] = "
			INSERT IGNORE INTO xf_content_type_field
				(content_type, field_name, field_value)
			VALUES
				('avforums_competition', 'attachment_handler_class', 'AVForums_Competitions_AttachmentHandler_Competition'),
				('avforums_competition', 'alert_handler_class', 'AVForums_Competitions_AlertHandler_Competition'),
				('avforums_competition', 'sitemap_handler_class', 'AVForums_Competitions_SitemapHandler_Competition')
		";

		return $data;
	}

	public static function getAlters()
	{
		$alters = array();

		$alters['xf_user_competition_entries'] = "
			ALTER TABLE `xf_user` ADD COLUMN `competition_entries` BLOB NOT NULL  AFTER `is_staff`
		";

		return $alters;
	}
}