<?php
/*================================================================+\
|| # PHPRetro - An extendable virtual hotel site and management
|+==================================================================
|| # Copyright (C) 2009 Yifan Lu. All rights reserved.
|| # http://www.yifanlu.com
|| # Parts Copyright (C) 2009 Meth0d. All rights reserved.
|| # http://www.meth0d.org
|| # All images, scripts, and layouts
|| # Copyright (C) 2009 Sulake Ltd. All rights reserved.
|+==================================================================
|| # PHPRetro is provided "as is" and comes without
|| # warrenty of any kind. PHPRetro is free software!
|| # License: GNU Public License 3.0
|| # http://opensource.org/licenses/gpl-license.php
\+================================================================*/

$page['allow_guests'] = false;
require_once('./includes/core.php');
require_once('./includes/session.php');
$lang->addLocale("credits.club");

$page['id'] = "lottery";
$page['name'] = "Lottery";
$page['bodyid'] = "home";
$page['cat'] = "community";
require_once('./templates/community_header.php');

// Lottery stats mysql
$query = mysql_query("SELECT * FROM ".PREFIX."lottery_stats");
$row = mysql_fetch_object($query);

if($_GET['page']) {
	if(!is_numeric($_GET['page'])) {
	die("<meta http-equiv=\"REFRESH\" content=\"0;url=lottery\">"); // Prevents users from putting non-numeric strings in to GET Page.
	}
}

?>
<div id="container">
	<div id="content" style="position: relative" class="clearfix">
    <div id="column1" class="column">
				<div class="habblet-container ">		
						<div class="cbb clearfix green">
                          <h2 class="title"><span style="float: left;">How to play</span></h2>
                          <div id ="habboclub-products">
                              <div id="lottery-main-content">
                              	                               <table width="100%" border="0">
                                <tr>
                                  <td>
                                  <p>
<div class="habblet box-content">
                                   Welcome to our official lottery system. Here you can purchase four numbers located to the right to earn yourself a chance to win the amount of credits that is in the jackpot system.
                                   </p>
                                <p>
                                   You are not limited to the amount of tickets you can purchase, but each ticket will cost you <b>100 credits</b>. The more tickets you purchase, the more of a chance you have of winning the lottery. Our lottery will run once a week, and the winner will receive their credits on <b>Friday @ 9PM</b>.
                                </p>
                                <b>Warning: Refunds for your tickets are NOT available!</b>
                                </td>
                                  <td><img src="<?php echo PATH; ?>/lottery/dice.gif" /></td>
                                </tr>
                              </table>
							</div>
                          </div>
                      </div>
                  </div>
                  <script type="text/javascript">if (!$(document.body).hasClassName('process-template')) { Rounder.init(); }</script>
               
				<div class="habblet-container ">		
						<div class="cbb clearfix green ">
                            <h2 class="title"><span style="float: left;">Current tickets</h2></span>
                            <div id="habboclub-info" class="box-content">
                                <table width=\"100%\" border=\"0\">
                           <?php
	
	$tbl_name="cms_lottery";		//your table name
	$adjacents = 10;				// How many adjacent pages should be shown on each side?
	
	$query = "SELECT COUNT(*) as num FROM $tbl_name";
	$total_pages = mysql_fetch_array(mysql_query($query));
	$total_pages = $total_pages[num];
	
	
	$targetpage = "lottery"; 	
	$limit = 30; 								
	$page = $_GET['page'];
	
	if($page) 
		$start = ($page - 1) * $limit; 			
	else
		$start = 0;								
	
	
	$sql = "SELECT * FROM $tbl_name LIMIT $start, $limit";
	$result = mysql_query($sql);
	
	
	if ($page == 0) $page = 1;					//if no page var is given, default to 1.
	$prev = $page - 1;							//previous page is page - 1
	$next = $page + 1;							//next page is page + 1
	$lastpage = ceil($total_pages/$limit);		//lastpage is = total pages / items per page, rounded up.
	$lpm1 = $lastpage - 1;						//last page minus 1
	
	$pagination = "";
	if($lastpage > 1)
	{	
		$pagination.= "<center>";
		
		if ($page > 1) 
			$pagination.= "<a href=\"$targetpage?page=$prev\">&laquo; previous </a>";
		else
			$pagination.= "<span class=\"disabled\">&laquo previous </span>";	
		
		if ($lastpage < 7 + ($adjacents * 2))	
		{	
			for ($counter = 1; $counter <= $lastpage; $counter++)
			{
				if ($counter == $page)
					$pagination.= "<span class=\"current\">$counter </span>";
				else
					$pagination.= "<a href=\"$targetpage?page=$counter\">$counter </a>";					
			}
		}
		elseif($lastpage > 5 + ($adjacents * 2))
		{
			
			if($page < 1 + ($adjacents * 2))		
			{
				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\">$counter </span>";
					else
						$pagination.= "<a href=\"$targetpage?page=$counter\">$counter </a>";					
				}
				$pagination.= "...";
				$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1 </a>";
				$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage </a>";		
			}
			
			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
			{
				$pagination.= "<a href=\"$targetpage?page=1\">1 </a>";
				$pagination.= "<a href=\"$targetpage?page=2\">2 </a>";
				$pagination.= "...";
				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\">$counter </span>";
					else
						$pagination.= "<a href=\"$targetpage?page=$counter\">$counter </a>";					
				}
				$pagination.= "...";
				$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1 </a>";
				$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage </a>";		
			}
			
			else
			{
				$pagination.= "<a href=\"$targetpage?page=1\">1 </a>";
				$pagination.= "<a href=\"$targetpage?page=2\">2 </a>";
				$pagination.= "...";
				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\">$counter </span>";
					else
						$pagination.= "<a href=\"$targetpage?page=$counter\">$counter </a>";					
				}
			}
		}
		
		
		if ($page < $counter - 1) 
			$pagination.= "<a href=\"$targetpage?page=$next\"> next &raquo;</a>";
		else
			$pagination.= "<span class=\"disabled\"> next &raquo;</span>";
		$pagination.= "</center><br /><br />";		
	}
		
		while($row = mysql_fetch_object($result))
		{
			$name = $row->username;
                        $num = $row->num;
 			echo'<tr>
                        <td style="width:100%; height:10px; border-bottom:#666 1px solid;">
                        <table width="100%" border="0">
                        <tr>
                        <td align="left">Username: '.$name.'</td>
                        <td align="right">Numbers: '.$num.'</td>
                       </tr>
                       </table>								
                       </tr></td>';
		}
	?>

<?=$pagination?>
						</table>	
                            </div>
					</div>
				</div>
				<script type="text/javascript">if (!$(document.body).hasClassName('process-template')) { Rounder.init(); }</script>
</div>
<div id="column2" class="column"> 

 <div class="habblet-container ">		
						
			
</div><div class="habblet-container ">		
						<div class="cbb clearfix green ">
	
							<h2 class="title"><span style="float: left;">Choose your numbers</span>
							</h2>
					

            <center>
            <?php
            date_default_timezone_set('Europe/Dublin'); // Change this to your countrys timezone
		    if(date(l) == "Friday" && date(H) == "20" && date(i) > "55") { // Prevents users from purchasing tickets during automatic lottery draw at 9pm (5 minutes)
			echo'Automatic lottery draw in process, lottery will re-open again at 9pm!';
			} else {
			?>
			<br>Select your four numbers.<br /><br />
            <form method="post" action="">
    
                <select name="numset1">
                    <option value="*">*</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
               </select>
               
               <select name="numset2">
                    <option value="*">*</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
               </select>
               
               <select name="numset3">
                    <option value="*">*</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
               </select>
               
               <select name="numset4">
                    <option value="*">*</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
               </select>
    	<div class="settings-step">
			<div class="settings-step-content">
				<h3><label for="bean_captcha" class="registration-text"><?php echo $lang->loc['type.captcha']; ?></label></h3>
					<div id="captcha-code-error"></div>
						<script type="text/javascript">
							document.observe("dom:loaded", function() {
    							Event.observe($("captcha-reload"), "click", function(e) {Utils.reloadCaptcha()});});
						</script>
						<p id="captcha-container">
   							<img id="captcha" src="<?php echo PATH; ?>/captcha.jpg?t=<?php echo time(); ?>" alt="" width="200" height="50" />
						</p>
						<p>
							<input type="text" name="captcha" id="captcha-code" value="" class="registration-text required-captcha" />
                        </p>
						<div id="captcha-reload">
                        	<p>(Reload Captcha)<br>
    						<img src="<?php echo PATH; ?>/web-gallery/v2/images/shared_icons/reload_icon.gif" width="15" height="15" alt=""/>
        					<a id="captcha-reload-link" href="#"><?php echo $lang->loc['captcha.reload']; ?></a>
                            </p>
    					</div>
    			</div>
		</div>
			<input type="submit" value="Purchase" name="btn_purchase" />
    		</form>
    		<?php
			}
			if(isset($_POST['btn_purchase'])) {
				  // Define number selections to variables
				  // No sql injection prevention is needed, due to all input being veried for a number ONLY.
				  $num1 = trim($_POST['numset1']);	
				  $num2 = trim($_POST['numset2']);
				  $num3 = trim($_POST['numset3']);
				  $num4 = trim($_POST['numset4']);
				  
				  // querys for checking if user has correct coins
				  $checkcoins = mysql_query("SELECT * FROM users WHERE `id` = '$user->id'");
		    	  $row = mysql_fetch_object($checkcoins);
			      $coins = $row->credits;
				   
				  if($coins < 100) { // Does the user have enough credits? If he dont he must be poor :(
					  echo'Your do not have enough credits to perform this purchase.';
				  } else {
				   
				  if($num1 == "" || $num2 == "" || $num3 == "" || $num4 == "" || $num1 == "*" || $num2 == "*" || $num3 == "*" || $num4 == "*") {
					  echo'You have to choose four numbers.';
				  } else {
					  if(!is_numeric($num1) || !is_numeric($num2) || !is_numeric($num3) || !is_numeric($num4) || $num1 > 9 || $num2 > 9 || $num3 > 9 || $num4 > 9) {
						  echo'Invalid number!'; // If someone has tried to be brainy and change the source code to a letter or a number higher than 9.
					  } else {
						  if(($_SESSION['register-captcha-bubble'] == $_POST['captcha'] && !empty($_SESSION['register-captcha-bubble'])) || $settings->find("site_capcha") == "0"){
						  unset($_SESSION['register-captcha-bubble']);
						  $finalnum = $num1.$num2.$num3.$num4;
		   $db->query("INSERT INTO ".PREFIX."lottery (id,username,num) VALUES ('".$user->id."','".$user->name."','".$finalnum."')"); // Insert users lottery ticket in to the database
		   $db->query("UPDATE users set `credits` = credits-100 WHERE `id` = '$user->id'"); // Remove 100 credits from the user, poor thing.
		   $db->query("UPDATE ".PREFIX."lottery_stats set `current_balance` = current_balance+100"); // Add 100 credits to the prize balance, yay more moniez.
		   $db->query("INSERT INTO ".PREFIX."transactions (userid,amount,time,descr) VALUES ('".$user->id."','-100','".time()."','Lottery Ticket Purchase')"); // Adds a transaction
		   
			// MUS - THIS HAS NOT BEEN TESTED!
			$user->refresh();
			@SendMUSData('UPRC' . $user->id);	  

			echo'<br /><center>You have purchased the numbers <br />'.$num1.', '.$num2.', '.$num3.' and '.$num4.'. Good luck!</center>';
				  		  } else {
							  echo'The Captcha Code you entered was invalid!'; // People just cant read and type these days...
						  }
					   }
				    }
				 }
			  }
			  ?>
    		</center>
    	</div>
	</div>

				<script type="text/javascript">if (!$(document.body).hasClassName('process-template')) { Rounder.init(); }</script>
			     		 <div class="habblet-container ">		
						<div class="cbb clearfix green ">

						<h2 class="title"><span style="float: left;">Statistics</h2></span>
						<?php
						    // Statistics 
							$query = mysql_query("SELECT * FROM ".PREFIX."lottery_stats");
							$row = mysql_fetch_object($query);
							$current_balance = $row->current_balance;
							$last_balance = $row->last_week_balance;
							$last_winner = $row->last_winner;
							$rollover = $row->rollover;
						?>
						<div id="lottery-next-draw" class="box-content">
                        <p>
                        	<b>This weeks lottery</b><br />
                            Current balance: <?php echo $current_balance ?>
                        </p>
                        <p> 
                        	<?php 
							if($rollover == "true") {
								echo'There was not a winner from the previous week.';
							} else {
							?>
                        	<b>Last weeks lottery</b><br />
                        	<?php echo $last_winner ?> won  <?php echo $last_balance ?> credits!
                            <?php
							}
							?>
                        </p>
                        </div>
				</div>
				<script type="text/javascript">if (!$(document.body).hasClassName('process-template')) { Rounder.init(); }</script>
</div>

<?php require_once('templates/community_footer.php'); ?>