<?php

$dbhost = "localhost"; /* DATABASE HOST */
$dbuser = "root"; /* DATABASE USERNAME */
$dbpass = "falcons7"; /* DATABASE PASSWORD  */
$dbid = "holodb"; /* DATABASE NAME  */
mysql_connect($dbhost, $dbuser, $dbpass) or  die();
mysql_select_db($dbid);

$generate_winning_ticket = mt_rand(1,9).mt_rand(1,9).mt_rand(1,9).mt_rand(1,9); // Generates random set of numbers E.G "1234" and loads them into a var

// Selects a random winner out of the winners what have gotten the correct number.
// This basically, if there is more than 1 winner, it will choose a random person.
$findwinner = mysql_query("SELECT * FROM cms_lottery WHERE num = '$generate_winning_ticket' order by rand() limit 1"); 
$row = mysql_fetch_object($findwinner);	
$winners = $row->id;
$winner_username = $row->username;

// Finds lottery stats 
$stats = mysql_query("SELECT * FROM cms_lottery_stats");
$getstats = mysql_fetch_object($stats);
$winningbalance = $getstats->current_balance;

if(mysql_num_rows($findwinner) > 0) { // Is the chosen number even there? 
	
	// Weve found a winner
	mysql_query("UPDATE cms_lottery_stats Set `rollover` = 'false'"); // Update latest winner...
	mysql_query("UPDATE users Set `credits` = credits+".$winningbalance." WHERE `id` = '$winners'"); // Awards the user with the Lotto balance
	mysql_query("UPDATE cms_lottery_stats Set `last_winner` = '".$winner_username."'"); // Update latest winner...
	mysql_query("UPDATE cms_lottery_stats Set `last_week_balance` = '".$winningbalance."'"); // Update Last week credit balance
	mysql_query("UPDATE cms_lottery_stats Set `current_balance` = '0'"); // Set the new balance to 0 credits
	mysql_query("truncate table cms_lottery"); // Delete all lottery current lottery tickets
	
} else { // Chosen number wasnt there, lets roll over the balance and add the current balance on to the new one!

	mysql_query("UPDATE cms_lottery_stats Set `rollover` = 'true'"); // Tell the lotery page rollover is true
	mysql_query("UPDATE cms_lottery_stats Set `last_winner` = 'null'"); // Set last winner to nothing
	mysql_query("truncate table cms_lottery"); // Delete all lottery current lottery tickets
}
?>