require( '../includes/_header.php' );
require( '_helpers.php' );
analyzeChoices();
adminHeadline( 'Compute auxiliary data' );
showDescription();
showChoices();

if( $chosenDoIt ){
  noticeBox3( 0, "Note: At the end of this, when this page is completed, you should see a green success box at the bottom of the page. If not, something went wrong (like an out-of-memory error we recently had, which killed the script)." );

  // Adding best-3 mean computations, for 2014 mean/3 recognition.
  computeBest3();

  computeConciseRecords();
  computeRanks( 'best', 'Single' );
  computeRanks( 'average', 'Average' );
  computeCachedDatabase('../generated/cachedDatabase.php');
  deleteCaches();
  noticeBox3( 1, "Ok, finished.<br />" . wcaDate() );
}

require( '../includes/_footer.php' );

#----------------------------------------------------------------------
function showDescription () {
#----------------------------------------------------------------------

  echo "<p>This computes means for 3x3 bld, the auxiliary tables ConciseSingleResults, ConciseAverageResults, RanksSingle and RanksAverage, as well as the cachedDatabase.php script, and clears the caches.</p>\n";

  echo "<p>Do it after changes to the database data so that these things are up-to-date.</p><hr />\n";
}
    if (!$_SESSION["isAdmin"]) {
        $request["filters"]["userID"] = $_SESSION["userID"];
    }
    $result = selectRows($db, $request);
    $awarded = $result['items'];
    if (!count($awarded)) {
        return;
    }
    // we hope that there will be no collision in a serie of generated codes
    $query = "INSERT ignore INTO `contestant` (`ID`, `algoreaCode`) values ";
    $first = true;
    foreach ($awarded as $contestant) {
        if (!$first) {
            $query = $query . ', ';
        }
        $first = false;
        $query = $query . '(' . $contestant->ID . ', \'' . genAccessCode($db) . '\')';
    }
    $query = $query . ' on duplicate key update `algoreaCode` = values(`algoreaCode`)';
    $db->exec($query);
}
if (!isset($_SESSION["isAdmin"]) || !$_SESSION["isAdmin"]) {
    echo json_encode((object) array("success" => false, "message" => "Seul un admin peut calculer les classements"));
    exit;
}
$contestID = $_REQUEST["contestID"];
computeRanks($db, $contestID);
computeRanksSchool($db, $contestID);
generateAlgoreaCodes($db, $contestID);
unset($db);
echo json_encode(array("success" => true));