<?php
if (!class_exists('vBShop_Item_Core'))
{
	die('No direct access allowed.');
}

class vBShop_Item_lotteryticket extends vBShop_Item_Core
{
	/**
	* The constructor
	*
	* @param	vBulletin	vBulletin registry
	* @param	array		Item info
	*/	
	public function __construct(&$registry, &$item)
	{
		parent::__construct($registry, $item);
		
		// Set purchase template
		$this->config['purchasetemplate'] = 'dbtech_vbshop_purchase_lottery';
	}

	/**
	* Render the item
	*/
	public function render()
	{
		global $vbphrase;

		// Lottery numbers
		$numbers = $selection = '';

		for ($s = 1; $s <= $this->config['code']['range']; $s++)
		{
			$selection .= "\r\n<option value='$s'>$s</option>";
		}

		for ($n = 1; $n <= $this->config['code']['numbers']; $n++)
		{
			$templater = vB_Template::create($this->config['purchasetemplate'] . '_number');
				$templater->register('number', $n);
				$templater->register('select', $selection);
			$numbers .= $templater->render();
		}

		// Next draw
		$nextdraw = vbdate($this->registry->options['dateformat'] . ', ' . $this->registry->options['timeformat'], $this->nextdraw());
		
		// Begin the purchase template
		$templater = vB_Template::create($this->config['purchasetemplate']);
			$templater->register('item', $this->config);
			$templater->register('price', vb_number_format(round($this->config['price'], 2)) . ' ' . $this->registry->options['dbtech_vbshop_pointsname']);
			$templater->register('pagetitle', construct_phrase($vbphrase['dbtech_vbshop_purchasing_x'], $this->config['title']));
			$templater->register('itemid', ($this->config['itemtypeid'] == 'gift' ? $this->config['giftid'] : $this->config['itemid']));
			$templater->register('type', $this->config['shoptype']);
			$templater->register('numbers', $numbers);
			$templater->register('nextdraw', $nextdraw);
		return $templater->render();
	}

	/**
	* Purchasing an item
	*
	* @param	array		User info
	* @param	array		Recipient user info
	*/	
	protected function pre_purchase(&$buyer, &$recipient)
	{
		global $vbphrase;

		$numbers = $_POST['code'];
		$used = array();
		$error = false;

		foreach ($numbers as $n => $num)
		{
			$n = intval($n);
			$num = intval($num);

			if ($num < 1)
			{
				$num = 1;
			}
			else if ($num > $this->config['code']['range'])
			{
				$num = $this->config['code']['range'];
			}

			if (in_array($num, $used) || $n < 1 || $n > $this->config['code']['numbers'])
			{
				$error = true;
			}

			$used[] = $num;
			$numbers[$n] = $num;
		}

		if ($error || count($numbers) != intval($this->config['code']['numbers']))
		{
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_lottery_error'])));
		}

		// insert into ticket table
		$this->registry->db->query_write("
			insert into " . TABLE_PREFIX . "dbtech_vbshop_ticket
			(userid, dateline, itemid, numbers)
			values
			(" . intval($recipient['userid']) . ", " . TIMENOW . ", " . $this->config['itemid'] . ", '" . $this->registry->db->escape_string(serialize($numbers)) . "')
		");
	}

	/**
	* Unix Timestamp of the next draw
	*/	
	public function nextdraw()
	{
		$rotation = array(
			'daily'		=> 86400,
			'weekly'	=> 604800,
			'monthly'	=> 2592000,
		);

		return $this->config['code']['start'] + $rotation[$this->config['code']['rotation']];
	}

	/**
	* Find active tickets for the draw
	*/
	public function fetchtickets()
	{
		$tickets = array();
		$fetch_tickets = $this->registry->db->query_read_slave("
			select ticket.*, user.username
			from " . TABLE_PREFIX . "dbtech_vbshop_ticket ticket
			left join " . TABLE_PREFIX . "user user on(user.userid = ticket.userid)
			where ticket.active = '1' and ticket.itemid = " . intval($this->config['itemid']) . 
		"");
		while ($ticket = $this->registry->db->fetch_array($fetch_tickets))
		{
			$tickets[] = $ticket;
		}

		return $tickets;
	}

	/**
	* Generate the draws numbers
	*/
	public function getnumbers()
	{
		$numbers = array();

		for ($n = 1; $n <= $this->config['code']['numbers']; $n++)
		{
			do
			{
				$num = rand(1, $this->config['code']['range']);
			}
			while (in_array($num, array_values($numbers)));

			$numbers[$n] = $num;
		}

		return $numbers;
	}

	/**
	* Finds the number of matches
	*/
	public function matches($numbers = array(), $ticketnumbers = array())
	{
		$matches = 0;

		foreach ($numbers as $number)
		{
			if (in_array($number, array_values($ticketnumbers)))
			{
				$matches++;
			}
		}

		return $matches;
	}

	/**
	* Builds the prize information
	*/
	public function prizes($prizeinfo = '')
	{
		$prizes = array();
		$prizeinfo = explode("\n", $prizeinfo);

		foreach ($prizeinfo as $prize)
		{
			$prize = trim($prize);

			if ($prize != '')
			{
				list($matches, $prize) = explode(':', $prize);

				$prizes[intval($matches)] = intval($prize);
			}
		}

		return $prizes;
	}

	/**
	* Finds prize, if any
	*/
	public function findprize($matches = 0, $prizes = array())
	{
		$prize = false;

		foreach ($prizes as $matchrequired => $prizeamount)
		{
			if ($matches >= $matchrequired && $prizeamount > intval($prize))
			{
				$prize = $prizeamount;
			}
		}

		return $prize;
	}

	/**
	* Calculates prize (raw or %)
	*/
	public function calcprize($prize, $tickets = array())
	{
		if ($this->config['code']['type'] == 'points')
		{
			return $prize;
		}

		$totalspent = count($tickets) * $this->config['price'];

		return ceil(($totalspent / 100) * $prize);
	}
	
	/**
	* Function to call before every action
	*/	
	public function action()
	{
		if (!parent::action())
		{
			// This type is inactive
			return false;
		}
		
		// We made it!
		return true;
	}

	/**
	* Prints out an AdminCP form
	*/	
	public function print_admin_form($code)
	{
		global $vbphrase;

		construct_hidden_code('item[code][start]', intval($code['start']) > 0 ? $code['start'] : TIMENOW);

		if (VBSHOP::$isPro)
		{
			$rotation = array(
				'daily'		=> $vbphrase['daily'],
				'weekly'	=> $vbphrase['weekly'],
				'monthly'	=> $vbphrase['monthly'],
			);

			$type = array(
				'points'	=> $this->registry->options['dbtech_vbshop_pointsname'],
				'percentage'	=> $vbphrase['dbtech_vbshop_ticket_percentage'],
			);

			print_select_row($vbphrase['dbtech_vbshop_lottery_frequency'], 'item[code][rotation]', $rotation, $code['rotation']);
			print_select_row($vbphrase['dbtech_vbshop_lottery_prizetype'], 'item[code][type]', $type, $code['type']);
			print_input_row($vbphrase['dbtech_vbshop_lottery_numbers'], 'item[code][numbers]', isset($code['numbers']) ? $code['numbers'] : 6);
			print_input_row($vbphrase['dbtech_vbshop_lottery_range'], 'item[code][range]', isset($code['range']) ? $code['range'] : '30');
		}
		else
		{
			construct_hidden_code('item[code][rotation]', 'weekly');
			construct_hidden_code('item[code][type]', 'points');
			construct_hidden_code('item[code][numbers]', '6');
			construct_hidden_code('item[code][range]', '25');

			print_description_row($vbphrase['dbtech_vbshop_lottery_liteinfo']);
		}

		print_textarea_row($vbphrase['dbtech_vbshop_lottery_prizes'], 'item[code][prize]', isset($code['prize']) ? $code['prize'] : "1:5\n2:10\n3:50\n4:200\n5:500\n6:2000", 15);
	}
}
?>