<?php
include 'displayerrors.php';

$servername = "127.0.0.1";
$username = "c3stats";
$password = "EsuxHeEKtqq3MrxfdP377DTS";
$dbname = "c3stats1";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


function SelectResult($sql, $conn) {
	$result = $conn->query($sql);
	return $result;
}

function secondsToTime($seconds) {
	if ($seconds == 0) {return 0;}
    $dtF = new \DateTime('@0');
    $dtT = new \DateTime("@$seconds");
    return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}

function table( $result ) {
    $result->fetch_array( MYSQLI_ASSOC );
    echo '<table class="display">';
    tableHead( $result );
    tableBody( $result );
    echo '</table>';
}

function tableHead( $result ) {
    echo '<thead>';
    foreach ( $result as $x ) {
    echo '<tr>';
    foreach ( $x as $k => $y ) {
        echo '<th>' . ucfirst( $k ) . '</th>';
    }
    echo '</tr>';
    break;
    }
    echo '</thead>';
}

function tableBody( $result ) {
    echo '<tbody>';
    foreach ( $result as $x ) {
    echo '<tr>';
    foreach ( $x as $y ) {
		$pos = strrpos($y, "STEAM");
		if ($pos === false) { 
			echo '<td>' . $y . '</td>';
		}
		else
		{
			echo '<td><a href="/?steamid='. $y . '">' . $y . '</a></td>';
		}
    }
    echo '</tr>';
    }
    echo '</tbody>';
}

?>
<html>
<head>
<link rel="stylesheet" href="jquery.dataTables.min.css" type="text/css" media="print, projection, screen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> 
<script>

$(document).ready(function() {
    $('.display').DataTable( {
		order: [[ 3, "desc" ]],
        scrollY:        '50vh',
        scrollCollapse: true,
        paging:         false
    } );
} );
    
</script>

<style>
/* unvisited link */
a:link {
    color: black;
}

/* visited link */
a:visited {
    color: black;
}

/* mouse over link */
a:hover {
    color: rgb(90, 90, 90);
}

/* selected link */
a:active {
    color: black;
}
</style>
</head>
<body>

<?php 
table(SelectResult("SELECT PlayerNames.Name, T1.SteamID, T1.PlayTime, COALESCE(T2.Kills,0) AS Kills, COALESCE(T3.Deaths,0) AS Deaths, ROUND(COALESCE(Kills/Deaths,0),1) AS KDR FROM (((Select SteamID,ROUND((Sum(PlayTime) / 60 / 60), 1) AS PlayTime FROM PlayTime GROUP BY SteamID) AS T1) LEFT JOIN ((Select KillerID,Count(*) AS Kills FROM KillStats GROUP BY KillerID) AS T2) ON T1.SteamID = T2.KillerID LEFT JOIN ((Select VictimID,Count(*) AS Deaths FROM KillStats GROUP BY VictimID) AS T3) ON T1.SteamID = T3.VictimID) INNER JOIN PlayerNames ON T1.SteamID = PlayerNames.SteamID ORDER BY Kills DESC", $conn));

 ?>

</body>
</html>

<?php $conn->close(); ?>
