<?php
// Add the bank field
if (self::$db_alter->fetch_table_info('dbtech_vbshop_category'))
{
	self::$db_alter->add_field(array(
		'name'       => 'bitfield',
		'type'       => 'int',
		'length'	 => '10',
		'attributes' => 'unsigned',
		'null'       => false,	// True = NULL, false = NOT NULL
		'default'    => '1'
	));
	self::$db_alter->drop_field('shoptypes');
	self::$db->hide_errors();
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_category ADD active ENUM('0', '1') NOT NULL DEFAULT '1'");
	self::$db->show_errors();
	self::report('Altered Table', 'dbtech_vbshop_category');
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_item'))
{
	self::$db_alter->add_field(array(
		'name'       => 'icon',
		'type'       => 'MEDIUMTEXT',
		'null'       => true,	// True = NULL, false = NOT NULL
		'default'    => NULL
	));
	self::$db_alter->add_field(array(
		'name'       => 'currencyid',
		'type'       => 'int',
		'length'	 => '10',
		'attributes' => 'unsigned',
		'null'       => false,	// True = NULL, false = NOT NULL
		'default'    => '0'
	));
	self::$db_alter->add_field(array(
		'name'       => 'shop',
		'type'       => 'int',
		'length'	 => '10',
		'attributes' => 'unsigned',
		'null'       => false,	// True = NULL, false = NOT NULL
		'default'    => '1'
	));
	self::$db_alter->add_field(array(
		'name'       => 'duration',
		'type'       => 'int',
		'length'	 => '10',
		'attributes' => 'unsigned',
		'null'       => false,	// True = NULL, false = NOT NULL
		'default'    => '0'
	));
	self::$db_alter->add_field(array(
		'name'       => 'ownerid',
		'type'       => 'int',
		'length'	 => '10',
		'attributes' => 'unsigned',
		'null'       => false,	// True = NULL, false = NOT NULL
		'default'    => '0'
	));
	self::$db->hide_errors();
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_item CHANGE itemtype itemtypeid VARCHAR( 50 ) NOT NULL");
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_item ADD uniqueitem ENUM('0', '1') NOT NULL DEFAULT '1'");
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_item ADD onlygiftable ENUM('0', '1') NOT NULL DEFAULT '0'");
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_item ADD moderation ENUM('0', '1') NOT NULL DEFAULT '0'");
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_item ADD reconfigure ENUM('0', '1') NOT NULL DEFAULT '1'");
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_item ADD regift ENUM('0', '1') NOT NULL DEFAULT '1'");
	self::$db->show_errors();
	self::report('Altered Table', 'dbtech_vbshop_item');
}

// Add the bank field
if (self::$db_alter->fetch_table_info('dbtech_vbshop_purchase'))
{
	self::$db_alter->add_field(array(
		'name'       => 'shopid',
		'type'       => 'int',
		'length'	 => '10',
		'attributes' => 'unsigned',
		'null'       => false,	// True = NULL, false = NOT NULL
		'default'    => '1'
	));
	self::$db_alter->add_field(array(
		'name'       => 'configuration',
		'type'       => 'mediumtext',
		'null'       => true,	// True = NULL, false = NOT NULL
		'default'    => NULL
	));
	self::$db_alter->add_field(array(
		'name'       => 'message',
		'type'       => 'mediumtext',
		'null'       => true,	// True = NULL, false = NOT NULL
		'default'    => NULL
	));
	self::$db->hide_errors();
	self::$db->query_write("UPDATE " . TABLE_PREFIX . "user SET dbtech_vbshop_purchase = NULL");
	self::$db->query_write("ALTER TABLE " . TABLE_PREFIX . "dbtech_vbshop_purchase ADD active ENUM('0', '1') NOT NULL DEFAULT '1'");
	self::$db->show_errors();
	self::report('Altered Table', 'dbtech_vbshop_purchase');	
}

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_bank`
	(
		`userid` INT( 10 ) UNSIGNED NOT NULL,
		`currencyid` INT( 10 ) UNSIGNED NOT NULL,
		`points` DOUBLE UNSIGNED NOT NULL DEFAULT '0',
		PRIMARY KEY (`userid`,`currencyid`)
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_bank');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_currency`
	(
		`currencyid` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT,
		`title` VARCHAR( 50 ) NOT NULL DEFAULT '',
		`description` MEDIUMTEXT NULL DEFAULT NULL,
		`active` ENUM( '0','1' ) DEFAULT '1',
		`displayorder` INT( 10 ) UNSIGNED NOT NULL DEFAULT '10',
		`pointstable` VARCHAR( 50 ) NOT NULL DEFAULT '',
		`pointscolumn` VARCHAR( 50 ) NOT NULL DEFAULT '',
		`canbank` ENUM( '0','1' ) DEFAULT '1',
		`cansteal` ENUM( '0','1' ) DEFAULT '1',
		`stealprotect` DOUBLE NOT NULL DEFAULT '-1',
		`interest` DOUBLE NOT NULL DEFAULT '0',
		`rounding` INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
		`privacy` INT( 10 ) UNSIGNED NOT NULL DEFAULT '2',
		`customshops` ENUM( '0','1' ) DEFAULT '1',
		`perreply` INT( 10 ) UNSIGNED NOT NULL DEFAULT '1',
		`perthread` INT( 10 ) UNSIGNED NOT NULL DEFAULT '1',
		`postbit` INT( 10 ) UNSIGNED NOT NULL DEFAULT '2',
		`bitfield` INT( 10 ) UNSIGNED NOT NULL DEFAULT '1',
		PRIMARY KEY ( `currencyid` )
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_currency');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_itemtype`
	(
		`itemtypeid` VARCHAR( 50 )  NOT NULL,
		`title` VARCHAR( 50 ) NOT NULL DEFAULT '',
		`description` MEDIUMTEXT NULL DEFAULT NULL,
		`active` ENUM( '0','1' ) DEFAULT '1',
		`filename` MEDIUMTEXT NULL DEFAULT NULL,
		PRIMARY KEY ( `itemtypeid` )
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_itemtype');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_lottery`
	(
		`lotteryid` int(10) unsigned NOT NULL AUTO_INCREMENT,
		`title` varchar(50) NOT NULL,
		`description` mediumtext,
		`active` enum('0','1') NOT NULL,
		`permissions` mediumtext,
		`ticketprice` double unsigned NOT NULL DEFAULT '0',
		`currencyid` int(10) unsigned NOT NULL DEFAULT '0',
		`numbers` mediumtext,
		`prizes` mediumtext,
		`drawinterval` int(10) unsigned NOT NULL,
		`nextdraw` int(10) unsigned NOT NULL DEFAULT '0',
		`prevdraw` int(10) unsigned NOT NULL DEFAULT '0',
		`bitfield` int(10) unsigned NOT NULL DEFAULT '1',
		PRIMARY KEY (`lotteryid`)
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_lottery');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_lotteryprize`
	(
		`lotteryprizeid` int(10) unsigned NOT NULL AUTO_INCREMENT,
		`title` varchar(50) NOT NULL,
		`description` mediumtext,
		`active` enum('0','1') NOT NULL DEFAULT '1',
		`numbers` mediumtext,
		`bitfield` int(10) unsigned NOT NULL DEFAULT '0',
		PRIMARY KEY (`lotteryprizeid`)
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_lotteryprize');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_shop`
	(
		`shopid` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT,
		`title` VARCHAR( 50 ) NOT NULL,
		`description` MEDIUMTEXT,
		`active` ENUM( '0','1' ) NOT NULL DEFAULT '1',
		`displayorder` INT( 10 ) UNSIGNED NOT NULL DEFAULT '10',
		`logo` MEDIUMTEXT,
		`ownerid` INT( 10 ) UNSIGNED NOT NULL NULL DEFAULT '0',
		`permissions` MEDIUMTEXT,
		`sales` INT( 10 ) UNSIGNED NOT NULL NULL DEFAULT '0',
		`salesamounts` MEDIUMTEXT,
		`latestcustomer` INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
		`latestsale` INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
		`bitfield` INT( 10 ) UNSIGNED NOT NULL DEFAULT '1',
		PRIMARY KEY ( `shopid` )
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_shop');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_shopinventory`
	(
		`shopid` int(10) unsigned NOT NULL,
		`itemid` int(10) unsigned NOT NULL,
		`currencyid` int(10) unsigned NOT NULL DEFAULT '0',
		`price` double unsigned NOT NULL,
		`buybackprice` double unsigned NOT NULL,
		`buybacktime` int(10) unsigned NOT NULL DEFAULT '0',
		`buybackreplenish` enum('0','1') NOT NULL DEFAULT '1',
		`notifications` mediumtext,
		`notifications_config` mediumtext,
		`stock` int(10) NOT NULL DEFAULT '0',
		`maxstock` int(10) NOT NULL DEFAULT '0',
		`refilltime` int(10) unsigned NOT NULL DEFAULT '0',
		`lastrefill` int(10) unsigned NOT NULL DEFAULT '0',
		PRIMARY KEY (`shopid`,`itemid`)
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_shopinventory');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_shoppingcart`
	(
		`userid` int(10) unsigned NOT NULL,
		`items` mediumtext,
		PRIMARY KEY (`userid`)
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_shoppingcart');

// Add itemtype table
self::$db->query_write("
	CREATE TABLE IF NOT EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_transactionlog`
	(
		`transactionlogid` int(10) unsigned NOT NULL AUTO_INCREMENT,
		`userid` int(10) unsigned NOT NULL DEFAULT '0',
		`recipient` int(10) unsigned NOT NULL DEFAULT '0',
		`dateline` int(10) unsigned NOT NULL DEFAULT '0',
		`ipaddress` char(15) NOT NULL,
		`action` varchar(50) NOT NULL,
		`info` mediumtext,
		PRIMARY KEY (`transactionlogid`)
	) ENGINE=MyISAM
");
self::report('Created Table', 'dbtech_vbshop_transactionlog');


// Populate tables
if (self::$db_alter->fetch_table_info('dbtech_vbshop_bank'))
{
	self::$db->query_write("
		REPLACE INTO " . TABLE_PREFIX . "dbtech_vbshop_bank
			(userid, currencyid, points)
		SELECT 
			userid,
			'1',
			dbtech_vbshop_bank
		FROM " . TABLE_PREFIX . "user AS user
		ORDER BY userid
	");
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_category'))
{
	$lastbitfield = 0;
	$categorys = self::$db->query_read_slave("SELECT categoryid FROM `" . TABLE_PREFIX . "dbtech_vbshop_category`");
	while ($category = self::$db->fetch_array($categorys))
	{
		$bitfield = $lastbitfield = ($lastbitfield == 0 ? 1 : ($lastbitfield * 2));
		self::$db->query_write("UPDATE `" . TABLE_PREFIX . "dbtech_vbshop_category` SET `bitfield` = $bitfield WHERE `categoryid` = $category[categoryid]");
	}
	self::$db->free_result($categorys);
	unset($category);	
	self::report('Populated Table', 'dbtech_vbshop_category');
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_currency'))
{
	self::$db->query_write("
		REPLACE INTO `" . TABLE_PREFIX . "dbtech_vbshop_currency`
			(`currencyid`, `title`, `description`, `active`, `pointstable`, `pointscolumn`, `rounding`, `perreply`, `perthread`, `postbit`)
		VALUES (
			1,
			" . self::$db->sql_prepare((self::$vbulletin->options['dbtech_vbshop_pointsname'] 		? self::$vbulletin->options['dbtech_vbshop_pointsname'] 				: 'Points')) . ",
			'The default vBShop currency.',
			" . self::$db->sql_prepare((self::$vbulletin->options['dbtech_vbshop_enablepoints'] 	? "'" . self::$vbulletin->options['dbtech_vbshop_enablepoints'] . "'" 	: '1')) . ",
			" . self::$db->sql_prepare((self::$vbulletin->options['dbtech_vbshop_pointstable'] 		? self::$vbulletin->options['dbtech_vbshop_pointstable'] 				: 'user')) . ",
			" .self::$db->sql_prepare((self::$vbulletin->options['dbtech_vbshop_pointsfield'] 		? self::$vbulletin->options['dbtech_vbshop_pointsfield'] 				: 'dbtech_vbshop_points')) . ",
			'0',
			" . self::$db->sql_prepare((self::$vbulletin->options['dbtech_vbshop_pointsperreply'] 	? self::$vbulletin->options['dbtech_vbshop_pointsperreply']  			: 1)) . ",
			" . self::$db->sql_prepare((self::$vbulletin->options['dbtech_vbshop_pointsperthread'] 	? self::$vbulletin->options['dbtech_vbshop_pointsperthread'] 			: 5)) . ",
			" . self::$db->sql_prepare((self::$vbulletin->options['dbtech_vbshop_postbit'] 			? self::$vbulletin->options['dbtech_vbshop_postbit'] 		 			: 2)) . "
		)
	");
	self::report('Populated Table', 'dbtech_vbshop_currency');
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_donationlog'))
{
	$logs = self::$db->query_read_slave("SELECT * FROM `" . TABLE_PREFIX . "dbtech_vbshop_donationlog`");
	while ($log = self::$db->fetch_array($logs))
	{
		self::$db->query_write("
			INSERT INTO `" . TABLE_PREFIX . "dbtech_vbshop_transactionlog`
				(userid, recipient, action, info)
			VALUES (
				'$log[userid]',
				'$log[recipient]',
				'donate',
				'" . serialize(array('currencyid' => 1, 'points' => $log['points'])) . "'
			)
		");
	}
	self::$db->query_write("TRUNCATE TABLE `" . TABLE_PREFIX . "dbtech_vbshop_donationlog`");
	self::report('Populated Table', 'dbtech_vbshop_transactionlog');
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_item'))
{
	// Init this
	$gifts = array();
	
	self::$db->query_write("
		UPDATE `" . TABLE_PREFIX . "dbtech_vbshop_item`
		SET icon = shopicon, shop = 1
	");
		
	$gifts_q = self::$db->query_read_slave("SELECT * FROM " . TABLE_PREFIX . "dbtech_vbshop_gift");
	while ($gift = self::$db->fetch_array($gifts_q))
	{
		$itemid = self::$db->query_write("
			INSERT INTO `" . TABLE_PREFIX . "dbtech_vbshop_item`
				(`categoryid`, `title`, `description`, `icon`, `shopicon`, `displayorder`, `price`, `permissions`, `code`, `itemtypeid`, `purchases`, `giftable`, `giftpm`, `shop`)
			VALUES (
				" . self::$db->sql_prepare($gift['categoryid']) . ",
				" . self::$db->sql_prepare($gift['title']) . ",
				" . self::$db->sql_prepare($gift['description']) . ",
				" . self::$db->sql_prepare($gift['icon']) . ",
				" . self::$db->sql_prepare($gift['shopicon']) . ",
				" . self::$db->sql_prepare($gift['displayorder']) . ",
				" . self::$db->sql_prepare($gift['price']) . ",
				" . self::$db->sql_prepare($gift['permissions']) . ",
				'a:0:{}',
				'custom',
				" . self::$db->sql_prepare($gift['purchases']) . ",
				1,
				1,
				1
			)
		");
		
		$gifts["$gift[giftid]"] = $itemid;
	}
	self::$db->free_result($gifts_q);
	unset($gift);
	
	$items = self::$db->query_read_slave("SELECT itemid FROM `" . TABLE_PREFIX . "dbtech_vbshop_item`");
	while ($item = self::$db->fetch_array($items))
	{
		self::$db->query_write("
			REPLACE INTO `" . TABLE_PREFIX . "dbtech_vbshop_shopinventory`
				(shopid, itemid, currencyid, price)
			VALUES (
				1,
				$item[itemid],
				1,
				'$item[price]'
			)
		");
	}
	self::$db->free_result($items);
	unset($item);
	self::report('Populated Table', 'dbtech_vbshop_item');
	
	self::$db->query_write("DELETE FROM `" . TABLE_PREFIX . "dbtech_vbshop_purchase` WHERE featureid IN(SELECT itemid FROM `" . TABLE_PREFIX . "dbtech_vbshop_item` WHERE itemtypeid = 'lotteryticket')");
	self::report('Cleaned Table', 'dbtech_vbshop_purchase');	
	
	self::$db->query_write("DELETE FROM `" . TABLE_PREFIX . "dbtech_vbshop_item` WHERE itemtypeid = 'lotteryticket'");
	self::$db_alter->drop_field('price');
	self::report('Cleaned Table', 'dbtech_vbshop_item');	
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_itemtype'))
{
	$lite = array(
		'custom' 			=> array(
			'title' 		=> 'Custom Item',
			'description' 	=> 'An item that can be customised to fit many needs.',
		),
		'immunity' 			=> array(
			'title' 		=> 'Immunity',
			'description' 	=> 'Immunity from various actions affecting user accounts.',
		),
		'intpermission' 	=> array(
			'title' 		=> 'Usergroup Permissions (Values)',
			'description' 	=> 'Value Flags',
		),
		'permission' 		=> array(
			'title' 		=> 'Usergroup Permissions (Yes / No)',
			'description' 	=> 'Yes / No Permission Flags',
		),
		'usernamechange' 	=>  array(
			'title' 		=> 'Username Change',
			'description' 	=> 'Change user names.',
		),
		'usernamestyle' 	=> array(
			'title' 		=> 'User Name Style Change',
			'description' 	=> 'Change the style of user names.',
		),
		'usertitlechange' 	=> array(
			'title' 		=> 'User Title Change',
			'description' 	=> 'Change user titles.',
		),
		'usertitlestyle' 	=> array(
			'title' 		=> 'User Title Style Change',
			'description' 	=> 'Change the style of user titles.',
		),
	);
	foreach ($lite as $filename => $info)
	{
		self::$db->query_write("
			REPLACE INTO `" . TABLE_PREFIX . "dbtech_vbshop_itemtype`
				(`itemtypeid`, `title`, `description`, `filename`)
			VALUES (
				" . self::$db->sql_prepare($filename) . ",
				" . self::$db->sql_prepare($info['title']) . ",
				" . self::$db->sql_prepare($info['description']) . ",
				'/dbtech/vbshop/items/" . $filename . ".php'
			)
		");
	}
	
	$pro = array(
		'forumpermission' 	=> array(
			'title' 		=> 'Forum Access',
			'description' 	=> 'Purchase access to certain forums.',
		),
		'stealchance' 		=> array(
			'title'			=> 'Steal Chance',
			'description' 	=> 'Add to a user\'s steal chance.',
		),
		'stealmore' 		=> array(
			'title'			=> 'Steal More',
			'description' 	=> 'Add to a user\'s steal amount.',
		),
		'usergroupchange' 	=> array(
			'title' 		=> 'Usergroup Change',
			'description' 	=> 'Change usergroups.',
		)
	);
	foreach ($pro as $filename => $info)
	{
		self::$db->query_write("
			REPLACE INTO `" . TABLE_PREFIX . "dbtech_vbshop_itemtype`
				(`itemtypeid`, `title`, `description`, `filename`)
			VALUES (
				" . self::$db->sql_prepare($filename) . ",
				" . self::$db->sql_prepare($info['title']) . ",
				" . self::$db->sql_prepare($info['description']) . ",
				'/dbtech/vbshop_pro/items/" . $filename . ".php'
			)
		");
	}
	self::report('Populated Table', 'dbtech_vbshop_itemtype');
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_purchase'))
{
	foreach ($gifts as $giftid => $itemid)
	{
		self::$db->query_write("UPDATE `" . TABLE_PREFIX . "dbtech_vbshop_purchase` SET `feature` = 'item', featureid = $itemid WHERE `featureid` = $giftid");
	}
	self::report('Populated Table', 'dbtech_vbshop_purchase');
}

if (self::$db_alter->fetch_table_info('dbtech_vbshop_shop'))
{
	self::$db->query_write("
		REPLACE INTO `" . TABLE_PREFIX . "dbtech_vbshop_shop`
			(`shopid`, `title`, `description`)
		VALUES (
			1,
			'Shop',
			'A shop that holds a number of purchasable items.'
		)
	");
	self::report('Populated Table', 'dbtech_vbshop_shop');
}

// Drop
$tables = array(
	'donationlog',
	'gift',
	'ticket',
);
foreach ($tables as $table)
{
	self::$db->query_write("DROP TABLE IF EXISTS `" . TABLE_PREFIX . "dbtech_vbshop_{$table}`");
	self::report('Deleted Table', 'dbtech_vbshop_' . $table);
}

define('CP_REDIRECT', 'vbshop.php?do=finalise&version=200');
define('DISABLE_PRODUCT_REDIRECT', true);