<?php
$sumfingIncl=true;
require '../fb/facebook.php';
require '../config.thing.php';
require '../mailer/phpmailer/class.phpmailer.php';

$app_namespace = '?sk=app_'.FB_APPID;
$app_url = MY_FB_PAGE_URL . $app_namespace;

if(!isset($_REQUEST['what']) && $_REQUEST['what'] != FB_APPID) die('no access');
//connect to database
echo dbConn();
	
	$query=mysql_query("SELECT * FROM admin");
	$result=mysql_fetch_assoc($query);
	$winnermail=htmlspecialchars_decode($result['emailmessage']);
	$amount=$result['amount'];
	$ends=$result['end'];
	$closed=$result['closed'];
	$prize=htmlspecialchars_decode($result['prize']);
	$winnerpick=$result['winnerpick'];
	$winnertimeline=htmlspecialchars_decode($result['winnertimeline']);
	$wonimg=$result['wonimg'];
	
	if($winnerpick=='random') {
		$winquery = "SELECT DISTINCT fb_id FROM tickets ORDER BY RAND() LIMIT ".$amount;
	} else {
		$winquery = "SELECT fb_id, COUNT(fb_id) AS TOTAL_Q
			 FROM tickets
			 GROUP BY fb_id
			 ORDER BY TOTAL_Q DESC LIMIT ".$amount;
	}
	
	
	
//close lottery
if((time() > strtotime($ends)) && ($closed == 0)) {
	$query=mysql_query("UPDATE admin SET closed=1");
	$closed=1;


//get total tickets
$query=mysql_query("SELECT * FROM tickets ORDER BY id DESC LIMIT 1");
	if($query) {
		$result=mysql_fetch_assoc($query);
		$ticketsTotal=$result['id'];
	}

//get winners
if($query=mysql_query($winquery)) {
	
	if(mysql_num_rows($query) != 0) {
	mysql_query("UPDATE admin SET gotwinner=1")  or die(mysql_error());
	}
		
	//select last id from winners
	if($last_id=mysql_query("SELECT MAX(id) as max_id FROM winners")) {
		$res=mysql_fetch_assoc($last_id);
		$new_id=$res['max_id']+1;
	} else die(mysql_error());
	
	while($result=mysql_fetch_assoc($query)) {
		$que=mysql_query("SELECT * FROM tickets WHERE fb_id=".$result['fb_id']." ORDER BY RAND() LIMIT 1");
		$r=mysql_fetch_assoc($que);
	
		
		//get user data
		if($uquery=mysql_query("SELECT * FROM user WHERE fb_id='".$r['fb_id']."'")) {
			$uresult=mysql_fetch_assoc($uquery);				
		
				
				//saving to the winners table
				mysql_query("INSERT INTO winners VALUES (
					'',
					".$new_id.",
					'".$uresult['fb_id']."',
					'".$uresult['name']."',
					'".$uresult['email']."',
					'".$r['id']."',
					".$ticketsTotal.",
					'".$r['code']."',
					'".strtotime($ends)."'
				)");
				
				//send email to the winner
				if(($winnermail!='') && ($uresult['banned'] == 'n')) {
					
					//email sending here -->
				
					include '../mailer/winner-email.php';
				
				}
				
				//post to timeline when only winners selected
				if(isset($winnertimeline) && ($uresult['banned'] == 'n')) {
									
					//post to user timeline
					$app_id = FB_APPID;
					$app_secret = FB_SECRET;
					
					$facebook = new Facebook(array(
					 'appId'  => $app_id,
					 'secret' => $app_secret,
					 'cookie' => true,
					 'fileUpload' => true
				   ));
					   
					$app_namespace = '?sk=app_'.FB_APPID;
					$app_url = MY_FB_PAGE_URL . $app_namespace;
									   
					$usertoken=$uresult['offline_access'];
					
					//posting image to winner album
					$file = '../img/post/'.$wonimg;
					$postmessage=str_replace("[PRIZE]",$prize,$winnertimeline);
					$postmessage=str_replace("[URL]",$app_url,$postmessage);
					
					$post_data = array(
					
						'message' => $postmessage,				
						'access_token'  => $usertoken,
						'source' => '@' . $file,
					
					);
										
					try {
											
						$publishPhoto = $facebook->api("/me/photos", 'post', $post_data);
										
					} catch (FacebookApiException $e) {
						error_log($e);
					}
					
				
					
				} 
								
			}
				
	}//while loop for winners
	
  } //select different unique tickets or random
include '../mailer/mail_to_admin.php';
} // if time

//displaying users on front page

$query=mysql_query("SELECT * FROM admin");
$result=mysql_fetch_assoc($query);
if($result['gotwinner']==0) die();

$query=mysql_query("SELECT * FROM winners WHERE id=(select max(id) from winners)");
	if($query) {
		if(($row=mysql_num_rows($query))!=0) {
		$winnersAre=($row > 1) ? WINNERS : WINNER;
		echo '<h2 style="margin:2px 6px; color:#555555">'.$winnersAre.'</h2>';
		while($result=mysql_fetch_assoc($query)) {
			
			$query2=mysql_query("SELECT banned FROM user WHERE fb_id='".$result['fb_id']."'");
			$result2=mysql_fetch_assoc($query2);
		
		$time= date('d-m-Y H:i', $result['date']);
		
			echo '<div class="new-winners small-round">';
			
			echo '<div class="img-round">
					<img src="https://graph.facebook.com/'.$result['fb_id'].'/picture?type=square" class="small-round">
				  </div>
				  <div id="winner-data">
						
						<strong>'.$result['name'].'</strong><br>';
						
						if($result2['banned'] == "y") {
							echo BANNED_USER.'<br>';
						} else {
							echo TICKET_WON.' '.$result['ticket_nr'].'<br>';
						}
						
						echo RAFFLE_TIME.' '.$time.'
						
				  </div>
				  <div id="prize-box">';
				  if($result2['banned'] == "y") {
				  	echo NO_PRIZE;
				  } else {
					echo THE_PRIZE.': '.$prize;
				  }
				  echo '</div>
				  
				  ';
			echo '<div style="clear:both;"></div>';
			echo '</div>';
			
			
		}
		echo '<div style="clear:both;"></div>';
	}
}


?>