<?php
/*======================================================================*\
|| #################################################################### ||
|| # EoT-Clan BF3 Leaderboard                                         # ||
|| # ---------------------------------------------------------------- # ||
|| # Dieses Copyright darf nicht entfernt werden                      # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # -----------------BF3 Leaderboard is a free Software--------------# ||
|| #                     http://eot-clan.net                          # ||
|| #################################################################### ||
\*======================================================================*/
	require_once ('../inc/config.php');
	require_once ('../language/'.$row['language'].'.php');
  require_once ('../inc/BattlelogApi/battlelog.api.php');
  
  $_GET = security::escape($_GET);
  $_POST = security::escape($_POST);

   if ($row['battlereports'] != 1){
   	?>
	            <html>
		           <head>
			          <title><?php echo LANG_BATTLEREPORT_TITLE2; ?></title>
		            	<link rel="stylesheet" type="text/css" href="../css/style.php" media="screen,projection" /> 
		           </head>
		            <table class="defaultUpdate" style="margin-left: -450px;margin-top: -100px;position: absolute;left: 50%;top: 50%; cellspacing="0" cellpadding="0">
			           <tr>
				          <td class="head" colspan="5"><?php echo LANG_BATTLEREPORT_TITLE2; ?></td>
			         </tr>
			           <tr>
				          <td class="result">
					      <span>
					       <br /><br /><b><?php echo LANG_BATTLEREPORT_ERROR_0; ?></b><br /><br />
					     </span>
				        </td>
			         </tr>
		          </table>
	           </html>
	        <?php
	        exit;
	 }
   	
            $battlelog = new BattlelogApiCurl;
            $time = time();
            $meta = "";
            $forwarding = "";

            $query = mysql_query("SELECT soldiername,pid FROM ".DBPrefix."generalStats WHERE lastPlayingTime+7200 > {$time} ");
			      $entrys = mysql_num_rows($query);
			        
			          $sSql = "SELECT soldiername FROM ".DBPrefix."generalStats";
                $result = mysql_query($sSql) or $sError = 'Error in Query: ' . mysql_error() . ' in SQL: ' . print_r($sSql, true);
		            $aPlayer = array();
		          while ($data = mysql_fetch_assoc($result)) {
		           	 $aPlayer[] = $data['soldiername'];
	 	          }
  
             if(isset($_GET['update']) && !empty($_GET['update']) && $_GET['update'] != '' && in_array($_GET['update'],$aPlayer)) {
	             $soldier = $_GET['update'];
	             $sWhere = "soldiername='".$soldier."' AND lastBattlereport+300 < $time";
	             $meta = '<meta http-equiv="refresh" content="4;url=../battlereport.php?name='.rawurlencode($soldier).'">';
	             $forwarding = LANG_BATTLEREPORT_UPDATE_FORWARDING;     
			      }elseif ($entrys == 0){
			      	?>
	            <html>
		           <head>
			          <title><?php echo LANG_BATTLEREPORT_TITLE2; ?></title>
		            	<link rel="stylesheet" type="text/css" href="../css/style.php" media="screen,projection" /> 
		           </head>
		            <table class="defaultUpdate" style="margin-left: -450px;margin-top: -100px;position: absolute;left: 50%;top: 50%; cellspacing="0" cellpadding="0">
			           <tr>
				          <td class="head" colspan="5"><?php echo LANG_BATTLEREPORT_TITLE2; ?></td>
			         </tr>
			           <tr>
				          <td class="result">
					      <span>
					       <br /><br /><b><?php echo LANG_BATTLEREPORT_UPDATE_ERROR; ?></b><br /><br />
					     </span>
				        </td>
			         </tr>
		          </table>
	           </html>
	        <?php
	        exit;
			      }else{
			      	$sWhere = "lastPlayingTime+7200 > {$time}";
			      }
			      

           $Sql = "SELECT soldiername,pid,battlelogID,Pplatform,persona FROM ".DBPrefix."generalStats WHERE {$sWhere} ORDER BY lastBattlereport ASC LIMIT 1";
           $Result   = mysql_query($Sql);
           $nums = mysql_num_rows($Result);
         if ($nums == 0){
         	?>
	            <html>
		           <head>
			          <title><?php echo LANG_BATTLEREPORT_TITLE2; ?></title>
			            <meta http-equiv="refresh" content="4;url=../battlereport.php?name=<?php echo rawurlencode($soldier); ?>">
		            	<link rel="stylesheet" type="text/css" href="../css/style.php" media="screen,projection" /> 
		           </head>
		            <table class="defaultUpdate" style="margin-left: -450px;margin-top: -100px;position: absolute;left: 50%;top: 50%; cellspacing="0" cellpadding="0">
			           <tr>
				          <td class="head" colspan="5"><?php echo LANG_BATTLEREPORT_TITLE2; ?></td>
			         </tr>
			           <tr>
				          <td class="result">
					      <span>
					       <br /><br /><b><?php echo LANG_BATTLEREPORT_UPDATE_TIMELIMIT; ?></b><br /><br /><?php echo $forwarding; ?>
					     </span>
				        </td>
			         </tr>
		          </table>
	           </html>
	        <?php
	        exit;
         }           
           $aData = mysql_fetch_assoc($Result); 
           $BattleReports = $battlelog->BattleReport($aData['soldiername']);
        
        if ($row['platform'] != 'pc'){
      		$BattleReports = $battlelog->BattleReport($aData['persona']);
      	}
      	
        $aReports = array();
        if (!isset($BattleReports['status'])){
            $sSql = "SELECT ReportID FROM ".DBPrefix."battlereports WHERE stats_pid={$aData['pid']} ORDER BY CreatetAt DESC LIMIT 30";
            $pidResult   = mysql_query($sSql) or $bError .= "\nError in Query: " . mysql_error() . ' in SQL: ' . print_r($sSql, true);
            $aBattlereports  = array();
           while($aReportID = mysql_fetch_assoc($pidResult)){  
            $aBattlereports[] = $aReportID['ReportID'];
           }
      	  if (is_array($BattleReports))foreach($BattleReports as $ID => $reports){ 
      	 	     $count = count($reports);
      	    for($i=0; $i < $count; $i++){
      	   	  if (!in_array($reports[$i]['reportId'],$aBattlereports)){
      	   	  	$serverName = addslashes($reports[$i]['serverName']);
      	   	 	  mysql_query("INSERT INTO ".DBPrefix."battlereports
      	   	 	              (stats_pid,ServerName,ReportID,ServerMap,CreatetAt,gameMode,winStatus) 
    		                  VALUES 
    		                    ({$aData['pid']},'{$serverName}',{$reports[$i]['reportId']},'{$reports[$i]['mapName']}',{$reports[$i]['createdAt']},{$reports[$i]['gameMode']},{$reports[$i]['winStatus']})");
    		        $aReports[] = $reports[$i]['reportId'];   		        
              }
      	    }
      	  }
        }
                $ID = $aData['pid'];
    		        $bID = $aData['battlelogID'];
    		        $uPlatform = $aData['Pplatform'];
    		        
    		     
    		        
    		     $soldier = $battlelog->SoldierInfo($aData['soldiername']);
    		        if ($row['platform'] != 'pc'){
      		         $soldier = $battlelog->SoldierInfo($aData['persona']);
      	        }
             $vet = "";
             if(is_array($soldier['0']['veteranStatus']['games'])){
                $vet = implode(',',$soldier['0']['veteranStatus']['games']);
             }
    		        
         mysql_query("UPDATE ".DBPrefix."generalStats SET lastBattlereport='{$time}',veteran='{$vet}' WHERE pid='{$ID}'");
      
      
      
          $IDcount = count($aReports);
          $ireports=0;
      if ($IDcount > 0){
        include_once('battlereportDetails.php');
       }
       
       
       if ($row['max_Reports'] > 0){
    	    $query = mysql_query("SELECT ReportID FROM ".DBPrefix."battlereports WHERE stats_pid={$ID}");
			    $Reports = mysql_num_rows($query);
			    
		         if ($Reports > $row['max_Reports']){
		         	$LIMIT = $Reports-$row['max_Reports'];
		           	$q = mysql_query("SELECT ReportID FROM ".DBPrefix."battlereports
		           	              WHERE stats_pid={$ID} 
		           	               ORDER BY CreatetAt ASC LIMIT {$LIMIT}") or die (mysql_error());    
		             	while ($a = mysql_fetch_assoc($q)) {
		           	       $delID[] = $a['ReportID'];
	 	              }  
	 	               
	 	              foreach ($delID as $id){
	 	              	mysql_query("DELETE a.*,b.* FROM ".DBPrefix."battlereports a
	 	              	            Left JOIN 
                                  ".DBPrefix."battlereportsDetails b ON a.ReportID = b.ReportID
		           	              WHERE a.ReportID={$id}") or die (mysql_error()); 
	 	              } 	               
		           	               
		         }
       }
       


       
    $text = LANG_BATTLEREPORT_UPDATE2;
if ($ireports == 0){
	   $text = LANG_BATTLEREPORT_UPDATE3;
	 }
      
 ?>
	<html>
		<head>
			<title><?php echo LANG_BATTLEREPORT_TITLE2; ?></title>
			<?php echo $meta; ?>
			<link rel="stylesheet" type="text/css" href="../css/style.php" media="screen,projection" /> 
		</head>
		<table class="defaultUpdate" style="margin-left: -450px;margin-top: -100px;position: absolute;left: 50%;top: 50%; cellspacing="0" cellpadding="0">
			<tr>
				<td class="head" colspan="5"><?php echo LANG_BATTLEREPORT_TITLE2; ?></td>
			</tr>
			<tr>
				<td class="result">
					<span>
					<br /><br /><b><?php echo LANG_BATTLEREPORT_UPDATE.$aData['soldiername'].LANG_BATTLEREPORT_UPDATE1.$ireports.$text; ?></b><br /><br /><?php echo $forwarding; ?>
					</span>
				</td>
			</tr>
		</table>
	</html>