<?php
    session_start();
    date_default_timezone_set('America/New_York');
?>
<!DOCTYPE html>
<html>

<head>
    <script src="js/jquery-2.1.1.min.js"></script>
    <script src="js/header.js"></script>
	<style>
	body {
    	padding-bottom: 70px;
	}
	table.sortable th:not(.sorttable_sorted):not(.sorttable_sorted_reverse):not(.sorttable_nosort):after {
    	content: " \25B4\25BE";
	}
    .button {
        background-color: #29b6f6;
        border: none;
        color: white;
        padding: 5px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 12px;
        border-radius: 12px;
        cursor: pointer;
        -webkit-transition-duration: 0.4s; /* Safari */
        transition-duration: 0.4s;
    }
    .disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    .button:hover {
        background-color: #219ad1;
    }
	</style>

</head>

<body>
<!-- Navigation -->
<nav class="light-blue lighten-1" role="navigation">
    <div class="nav-wrapper container">
        <ul id="nav-mobile" class="left">
            <li><a href="index.php"><i class="material-icons left" style="font-size: 20px">home</i>Home</a></li>
            <li><a href="dataset.php"><i class="material-icons left" style="font-size: 20px">insert_chart</i>Dataset</a></li>
            <li class="active"><a href="leaderboard.php"><i class="material-icons left" style="font-size: 20px">list</i>Leaderboard</a></li>
            <li><a href="about.php"><i class="material-icons left" style="font-size: 20px">info_outline</i>Team</a></li>
            <li><a class="dropdown-trigger" data-target="workshop"><i class="material-icons left" style="font-size: 20px">book</i>Workshop<i class="material-icons right">arrow_drop_down</i></a></li>
        </ul>
        <ul id="workshop" class="dropdown-content">
          <li><a href="https://cydar.ist.psu.edu/conference/BEEU2020/index.html">BEEU2020</a></li>
        </ul>
        <ul id="nav-mobile" class="right">
            <?php require_once('navigation.php'); ?>
        </ul>

    </div>
</nav>

<div class="section no-pad-bot" id="index-banner">
    <div class="container">
        <img src="img/bold.png" width="20%" style="padding-top: 20px;"><br /><br />

        <h5><b>Leaderboard</b></h5><br />

        <?php
            $connection = mysqli_connect($db_host, $db_username, $db_password);
            if (!$connection) die ("Could not connect to the database: <br />". mysqli_error());$db_select=mysqli_select_db($connection, $db_database);
            $db_select=mysqli_select_db($connection, $db_database);
            if (!$db_select) die ("Could not select the database: <br />". mysqli_error());

            if (isset($_SESSION['uid'])) {
                $sql = "SELECT team_name, affiliation FROM user_metadata WHERE usr_id = '".$_SESSION['uid']."';";
                $result = mysqli_query($connection, $sql);
                $row = mysqli_fetch_array($result);
                $teamname = $row["team_name"];
                $institution = $row["affiliation"];
                $sql = "SELECT team_name, institution, date FROM team_result WHERE team_name = '".$teamname."' AND institution = '".$institution."' AND date = CURDATE();";
                $result = mysqli_query($connection, $sql);
                if (mysqli_num_rows($result) == 0) {
                    $sql = "SELECT team_name, institution, MAX(date) AS 'Max Date' FROM team_result WHERE team_name = '".$teamname."' AND institution = '".$institution."';";
                    $result = mysqli_query($connection, $sql);
                    $row = mysqli_fetch_array($result);
                    $datetime = $row["Max Date"];

                    echo "<form action=\"\" method=\"post\" enctype=\"multipart/form-data\">";
                    echo "<input type=\"file\" name=\"fileToUpload\" id=\"fileToUpload\">";
                    echo "<p></p>";
                    echo "<input type='submit' class = 'button hover' name='submit' value='Submit Result'></form>";
                } else {
                    echo "<button class='button disabled' disabled>Today's result submitted</button>";
                }
            } else {
                echo "<button class='button disabled' disabled>Log in to submit result</button>";
            }
        ?>

        <h5><b></b></h5><br />
        <table id = 'leaderboard' class = "sortable" width = 100%>
            <thead>
                <tr>
                    <th class = "sorttable_nosort" width = 25%>Team Name</th>
                    <th class = "sorttable_nosort" width = 30%>Institution</th>
                    <th class = "sorttable_numeric" width = 12%>AP</th>
                    <th class = "sorttable_numeric" width = 12%>ROCAUC</th>
                    <th class = "sorttable_numeric" width = 12%>\(R^2\)</th>
                    <th class = "sorttable_numeric" width = 15%>ERS</th>
                </tr>
            </thead>
            <?php
            if (isset($_SESSION['uid']) && isset($_POST['submit'])) {
                $error = NULL;
                $date = date("Ymd");
                $target_dir = $_SERVER['DOCUMENT_ROOT'].'/emotionchallenge/results/';
                $tmp_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
                $target_file = $target_dir ."uid". $_SESSION['uid'] . "_" . $date . "." .$result_ext;
                $uploadOk = 1;
                $FileType = strtolower(pathinfo($tmp_file,PATHINFO_EXTENSION));
                // Check if file already exists
                if (file_exists($target_file)) {
                    $error = "Only 1 submission allowed per day.";
                    $uploadOk = 0;
                }
                // Check file size
                if ($_FILES['fileToUpload']["size"] > 10000000) {
                    $error = "Your file is too large.";
                    $uploadOk = 0;
                }
                // Allow certain file formats
                if($FileType != $result_ext) {
                    $error = "Only '".$result_ext."' files are allowed.";
                    $uploadOk = 0;
                }
                // Upload result
                $uploadOk = 1;
                if ($uploadOk == 1) {
                    if (move_uploaded_file($_FILES['fileToUpload']["tmp_name"], $target_file)) {
                        // paths needs to be changed to fit in server directory hierarchy
                        $saved_file = "results/"."uid". $_SESSION['uid'] . "_" . $date . "." .$result_ext;
                        // paths needs to change to fit in server directory hierarchy
                        exec("cd python/;".$python." -W ignore evaluate.py --pred ../".$saved_file." 2>&1", $output);
                        //var_dump($output);
                        $returnval = round(floatval($output[0]), 4);
                        if ($returnval == 0){
                            $ap = round(floatval($output[1]), 4);
                            $auc = round(floatval($output[2]), 4);
                            $r2 = round(floatval($output[3]), 4);

                            /* Test whether user's data can be selected and inserted */
                            $query = "INSERT INTO team_result (`id`, `team_name`, `date`, `institution`, `ap`, `auc`, `r_squared`) VALUES (".$_SESSION['uid'].",'".$teamname."',  CURDATE(), '".$institution ."', ".$ap.", ".$auc.", ".$r2.");";
                            $result = mysqli_query($connection, $query);
                            echo "Result upload successful. Your result is: AP = ".$ap.", AUC = ".$auc.", R^2 = ".$r2;
                            //echo "<meta http-equiv='refresh' content='0'>";
                        }
                        else{
                            $error = "Upload file is not valid! Valid submission should be a 5714 x 29 numerical csv file.";
                        }
                    } else {
                        $error = "Unknown problem when uploading your file, please contact administrator for help.";
                    }
                }
                if ($error) echo "<p style='color:red'><b>Error:</b> $error</p>";
            }

            $sql = "SELECT team_name, institution, ap, auc, r_squared, score FROM leaderboard ORDER BY score DESC;";
            $result = mysqli_query($connection, $sql);
            if( mysqli_num_rows($result) ) {
                while ($row = mysqli_fetch_array($result)) {
                    echo "<tr><td>".$row["team_name"]."</td><td>".$row["institution"]."</td><td>".$row["ap"]."</td><td>".$row["auc"]."</td><td>".$row["r_squared"]."</td><td>".$row["score"]."</td></tr>";
                }
            }
            ?>
        </table>
    </div>
</div>
</body>
<script src="js/footer.js"></script>
</html>
