<?php
/**
 ********************************************
 * Masters of Endurance tracker / LFS-Tracker 
 ********************************************
 * 
 * Copyright © 2007 Wolfgang Tom (WolleT)
 * v1.0 originally written by Wolfgang Tom
 * 
 * Copyright © 2009-2011 Michael Booth (Boothy)
 * v2.0 tracker modified by Michael Booth
 * 
 * Thanks also to Casper Roescher (Kaspur).  
 * 
 * Latest tracker version available from the LFS forum thread - http://www.lfsforum.net/showthread.php?t=73414
 * Any code changes/improvements can be submitted for inclusion in the public tracker version. 
 * E-mail me at web@michaelbooth.me.uk or PM me via http://www.lfsforum.net/private.php?do=newpm&u=202039
 * 
 ********************************************
 * 
 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 * Version 2, December 2004

 * Copyright © 2004 Sam Hocevar <sam@hocevar.net>

 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.

 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

 * 0. You just DO WHAT THE FUCK YOU WANT TO. 
 * 
 ******************************************** 
 * See http://sam.zoy.org/wtfpl/ for more information
 **/
// REQUIRED FILES
require 'config.php';
require 'functions.php';
require 'variables.php';
require 'sql.php';
// CONNECT TO DB
$link = mysql_connect(SQL_HOST, SQL_USER, SQL_PASS);
if (!$link) {
    die('Could not connect: ' . mysql_error());
} else {
    mysql_select_db(SQL_DB);
    mysql_set_charset('utf8');
    $trackerMode = ucfirst(strtolower($trackerMode)); // get tracker mode in lowercase
    $trackerModeShort = strtolower(substr($trackerMode, 0, 4)); // qual or prac
    // NUMBER OF SERVERS
    $rid_string = 'AND ( ';
    for ($s = 1; $s < ($numServers + 1); ++$s) {
        $name = 'manualIdServer' . $s;
        if (${$name}) {
            $race_id = ${$name};
        } else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE . " WHERE server='$s' AND type='$trackerModeShort'") or
                die(mysql_error());
            $race_id = mysql_result($r_res, 0, 'id');
        }
        if ($s > 1) {
            $rid_string .= " OR race_id='" . $race_id . "' ";
        } elseif ($numServers == 1 && $serverCrash) {
            $rid_string = "AND ( race_id>='" . $race_id . "'";
        } elseif ($numServers == 1 && $allRaceids) {
            $rid_string = "AND ( race_id<='" . $race_id . "'";
        } else {
            $rid_string = "AND ( race_id='" . $race_id . "'";
        }

    }
    $rid_string .= " ) ";
}
// GET TIMESTAMP OF WHEN RACE WAS STARTED
$race_res = mysql_query("SELECT created_on FROM " . SQL_LAP . " WHERE type='" .
    strtoupper($trackerModeShort) . "_START' " . $rid_string .
    " ORDER BY race_id desc") or die(mysql_error());
if (mysql_num_rows($race_res) > 0)
    $race_start = mysql_result($race_res, 0);
// SET UP $XMLRACE ARRAY
$XMLRACE['race_start'] = $race_start;
$XMLRACE['num_sectors'] = $raceNumSectors;
$XMLRACE['raceTrackLengthKm'] = $raceTrackLengthKm;
if (!isset($qualMins)) {
    print 'No session time specified.';
    die;
}
$XMLRACE['timeMins'] = $qualMins;
$trackstatusfilename = "trackstatus.txt";
$fh = fopen($trackstatusfilename, "r") or print ('Could not open track status file!');
if (filesize($trackstatusfilename) == 0) {
    $trackstatus = "";
} else {
    $trackstatus = fread($fh, filesize($trackstatusfilename)) or print ('Could not read track status file!');
    fclose($fh);
}
$XMLRACE['session_status'] = $trackstatus;
$XMLRACE['fastest_lap'] = 99999999999;
$XMLRACE['numClasses'] = $raceClasses;
for ($o = 1; $o <= count($raceClassName); ++$o) {
    $p = $raceClassName[$o];
    $XMLRACE['classes'][$p]['name'] = $raceClassName[$o];
    $XMLRACE['classes'][$p]['position'] = 1;
    $XMLRACE['classes'][$p]['fastest_lap'] = 99999999999;
}
global $XMLRACE;
$XMLTEAM = array();
//GO THROUGH EACH TEAM FROM THE TEAMS.YAML ARRAY
$time2 = microtime(true);
foreach ($TEAMS as $key => $team) {
    $XMLTEAM[$key]['team_data'] = array();
    $XMLTEAM[$key]['team_data']['name'] = $TEAMS[$key]['team_name'];
    $XMLTEAM[$key]['team_data']['class'] = $TEAMS[$key]['class'];
    $XMLTEAM[$key]['team_data']['car'] = $TEAMS[$key]['car'];
    $XMLTEAM[$key]['team_data']['number'] = $TEAMS[$key]['number'];
    if ($showServer) {
        $XMLTEAM[$key]['team_data']['server'] = $TEAMS[$key]['server'];
    }
    $XMLTEAM[$key]['team_data']['grid'] = $TEAMS[$key]['grid'];
    $XMLTEAM[$key]['race_data']['penalty_laps'] = $TEAMS[$key]['penalty_laps'];
    $XMLTEAM[$key]['race_data']['penalty_time'] = $TEAMS[$key]['penalty_time'];
    $XMLTEAM[$key]['team_data']['team_status'] = $TEAMS[$key]['team_status'];
    $XMLTEAM[$key]['team_data']['team_status_num'] = 1;
    switch (strtoupper($XMLTEAM[$key]['team_data']['team_status'])) {
        case "NC":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 2;
            break;
        case "RET":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 3;
            break;
        case "DQ":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 4;
            break;
        case "DNS":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 5;
            break;
    }
    if ($raceClasses > 1) {
        $XMLTEAM[$key]['team_data']['class_position'] = 0;
    }
    $XMLTEAM[$key]['race_data']['fastest_lap'] = 99999999999;
    //$XMLTEAM[$key]['race_data']['fastest_lap_on'] = 0;
    $XMLTEAM[$key]['race_data']['flying_laps'] = 0;
    $i = 0;
    foreach ($TEAMS[$key]['driver_active'] as $k => $active) {
        if ($active) // ALWAYS TRUE!
            {
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_lfs'] = mb_strtolower($TEAMS[$key]['driver_lfs'][$k],
                'UTF-8');
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_full'] = $TEAMS[$key]['driver_real'][$k];
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_real'] = format_name($TEAMS[$key]['driver_real'][$k],
                " ");
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_country'] = $TEAMS[$key]['driver_country'][$k];
            $XMLTEAM[$key]['team_data']['drivers'][$i]['laps'] = "";
            $XMLTEAM[$key]['team_data']['drivers'][$i]['fastest_lap'] = 99999999999;
            ++$i;

        }
    }
    $XMLTEAM[$key]['team_data']['num_drivers'] = $i;
    //<!-- Group the drivers together and get all the LAPs they drove from the database -->
    if (strtoupper($XMLRACE['session_status']) !== "PRE-RACE") {
        $drivers = generateDriverString($team);
        // if $qualElimination then use only the highest race_id?
        if ($qualElimination) {
            $r_res = mysql_query("SELECT max(race_id) AS race_id FROM " . SQL_LAP .
                " WHERE type='LAP' AND (" . $drivers . ") " . $rid_string) or die(mysql_error());
            $maxraceid = mysql_result($r_res, 0, 'race_id');
            $XMLTEAM[$key]['race_data']['maxraceid'] = $maxraceid;
            $sql = "SELECT id, lfsworld, value, race_id, created_on, time FROM " . SQL_LAP .
                " WHERE type='LAP' AND race_id='$maxraceid' AND (" . $drivers . ") " . $rid_string .
                " ORDER BY race_id ASC, created_on ASC";
            $sql_res = mysql_query($sql);
            $sql_dummy = $sql_res;
        } else {
            $sql = "SELECT id, lfsworld, value, created_on, time FROM " . SQL_LAP .
                " WHERE type='LAP' AND (" . $drivers . ") " . $rid_string .
                " ORDER BY race_id ASC, created_on ASC";
            $sql_res = mysql_query($sql);
            $sql_dummy = $sql_res;
        }
        //<!-- Put the laps into an array -->
        $i = 0;
        while ($res = mysql_fetch_object($sql_res)) {
            //print $i;
            //$i+=$res->lap;
            if (!$trimFinished or ($res->value < 3600000) or ($res->time <= $XMLRACE['timeMins'] *
                60000)) {
                $XMLTEAM[$key]['raw_laps'][$i]['lap'] = $res->lap;
                $XMLTEAM[$key]['raw_laps'][$i]['laptime'] = $res->value;
                $XMLTEAM[$key]['raw_laps'][$i]['driverUserName'] = mb_strtolower($res->lfsworld,
                    'UTF-8');
                $XMLTEAM[$key]['raw_laps'][$i]['logged'] = $res->created_on;
                $XMLTEAM[$key]['raw_laps'][$i]['sessiontime'] = $res->time;
                $XMLTEAM[$key]['raw_laps'][$i]['mysqlid'] = $res->id;
                ++$i;
            }
        }
    }
    /*
    for ($j=0 ; $j<$XMLTEAM[$key]['raw_laps'][0]['lap'] ; $j++, $i++) {
    $XMLTEAM[$key]['raw_laps'][$i]['lap'] = $XMLTEAM[$key]['raw_laps'][0]['lap'];
    $XMLTEAM[$key]['raw_laps'][$i]['laptime'] = $XMLTEAM[$key]['raw_laps'][0]['laptime'];
    $XMLTEAM[$key]['raw_laps'][$i]['driverUserName'] = $XMLTEAM[$key]['raw_laps'][0]['driverUserName'];
    $XMLTEAM[$key]['raw_laps'][$i]['logged'] = $XMLTEAM[$key]['raw_laps'][0]['logged'];
    $XMLTEAM[$key]['raw_laps'][$i]['mysqlid'] = $XMLTEAM[$key]['raw_laps'][0]['mysqlid'];
    }
    */
    $XMLTEAM[$key]['race_data']['laps'] = count($XMLTEAM[$key]['raw_laps']);
    $p = 0;
    for ($k = 0; $k < $XMLTEAM[$key]['race_data']['laps']; $k++) {
        for ($l = 0; $l < $XMLTEAM[$key]['team_data']['num_drivers']; $l++) {
            if (mb_strtolower($XMLTEAM[$key]['raw_laps'][$k]['driverUserName'], 'UTF-8') ==
                $XMLTEAM[$key]['team_data']['drivers'][$l]['driver_lfs']) {
                $XMLTEAM[$key]['team_data']['drivers'][$l]['laps']++;
                if ($XMLTEAM[$key]['raw_laps'][$k]['laptime'] != 3600000) {
                    $XMLTEAM[$key]['team_data']['drivers'][$l]['fastest_lap'] = min($XMLTEAM[$key]['team_data']['drivers'][$l]['fastest_lap'],
                        $XMLTEAM[$key]['raw_laps'][$k]['laptime']);

                }
            }
        }
        if ($XMLTEAM[$key]['raw_laps'][$k]['laptime'] != 3600000) {
            if ($XMLTEAM[$key]['raw_laps'][$k]['laptime'] < $XMLTEAM[$key]['race_data']['fastest_lap']) {
                $XMLTEAM[$key]['race_data']['fastest_lap_on'] = $k + 2;
                $XMLTEAM[$key]['race_data']['fastest_driver'] = $XMLTEAM[$key]['raw_laps'][$k]['driverUserName'];
                $XMLTEAM[$key]['race_data']['fastest_lap'] = $XMLTEAM[$key]['raw_laps'][$k]['laptime'];
            }
            //$XMLTEAM[$key]['race_data']['fastest_lap'] = min($XMLTEAM[$key]['raw_laps'][$k]['laptime'],
            //  $XMLTEAM[$key]['race_data']['fastest_lap']);

            $XMLTEAM[$key]['race_data']['flying_laps'] += 1;

            if ($XMLTEAM[$key]['race_data']['penalty_laps'] < 0) {
                $XMLTEAM[$key]['sorted_laps'][$p] = $XMLTEAM[$key]['raw_laps'][$k]['laptime'];
                $p++;
            }

            /*if (($XMLTEAM[$key]['race_data']['fastest_lap'] == $XMLTEAM[$key]['raw_laps'][$k]['laptime'])) {
            $XMLTEAM[$key]['race_data']['fastest_lap_on'] = $k + 2;
            echo "$key, $k, ", $XMLTEAM[$key]['race_data']['fastest_lap'], $XMLTEAM[$key]['team_data']['name'],
            $XMLTEAM[$key]['raw_laps'][$k]['laptime'], " ", $XMLTEAM[$key]['race_data']['fastest_lap_on'],
            "\n";
            $XMLTEAM[$key]['race_data']['fastest_driver'] = $XMLTEAM[$key]['raw_laps'][$k]['driverUserName'];
            }*/

        }
    }


    if ($XMLTEAM[$key]['race_data']['penalty_laps'] < 0) {
        sort($XMLTEAM[$key]['sorted_laps']);
        $XMLTEAM[$key]['race_data']['fastest_lap'] = $XMLTEAM[$key]['sorted_laps'][abs($XMLTEAM[$key]['race_data']['penalty_laps'])];
        for ($k = 0; $k < count($XMLTEAM[$key]['raw_laps']); $k++) {
            if ($XMLTEAM[$key]['race_data']['fastest_lap'] == $XMLTEAM[$key]['raw_laps'][$k]['laptime'])
                $XMLTEAM[$key]['race_data']['fastest_lap_on'] = $k + 2;
        }
        if ($XMLTEAM[$key]['race_data']['fastest_lap'] == 0) {
            $XMLTEAM[$key]['race_data']['fastest_lap_on'] = 0;
            //$XMLTEAM[$key]['race_data']['laps'] = 1;
            $XMLTEAM[$key]['race_data']['fastest_lap'] = 99999999999;
        }
    }

    if ($XMLTEAM[$key]['raw_laps'][($XMLTEAM[$key]['race_data']['laps'] - 1)]['sessiontime'] >
        ($qualMins * 60 * 1000)) {
        $XMLTEAM[$key]['team_data']['finished'] = true;
    }


    $XMLTEAM[$key]['race_data']['fastest_lap'] = $XMLTEAM[$key]['race_data']['fastest_lap'] - ($XMLTEAM[$key]['race_data']['penalty_time'] *
        1000);

    // DETERMINE THE CURRENT POSITION OF THE CAR
    // DETERMINE THE DRIVER CURRENTLY IN THE CAR
    if ($XMLTEAM[$key]['team_data']['num_drivers'] > 1) {
        $sql_res2 = mysql_query("SELECT type, lfsworld FROM " . SQL_LAP .
            " WHERE (type='LAP' OR type='SP1' OR type='SP2' OR type='SP3') $timeLimit AND (" .
            $drivers . ") " . $rid_string . " ORDER BY race_id DESC, id DESC LIMIT 0, 1");
        $XMLTEAM[$key]['race_data']['current_driver'] = "";
        if ($XMLTEAM[$key]['race_data']['laps'] > 0) {
            if (mysql_result($sql_res2, 0, 'type') == "LAP")
                $XMLTEAM[$key]['race_data']['current_sector'] = 0;
            if (mysql_result($sql_res2, 0, 'type') == "SP1")
                $XMLTEAM[$key]['race_data']['current_sector'] = 1;
            if (mysql_result($sql_res2, 0, 'type') == "SP2")
                $XMLTEAM[$key]['race_data']['current_sector'] = 2;
            if (mysql_result($sql_res2, 0, 'type') == "SP3")
                $XMLTEAM[$key]['race_data']['current_sector'] = 3;
            $XMLTEAM[$key]['race_data']['current_driver'] = mb_strtolower(mysql_result($sql_res2,
                0, 'lfsworld'), 'UTF-8');
        } else {
            $XMLTEAM[$key]['race_data']['current_sector'] = 0;
        }
    } else {
        $XMLTEAM[$key]['race_data']['current_sector'] = 0;
        $XMLTEAM[$key]['race_data']['current_driver'] = $XMLTEAM[$key]['team_data']['drivers'][0]['driver_lfs'];
    }
}
// SORT STANDINGS
if ($qualElimination == true) {
    usort($XMLTEAM, "sort_standingsq2");
} else {
    usort($XMLTEAM, "sort_standingsq");
}
$amountTeams = count($XMLTEAM);
for ($i = 0; $i < $amountTeams; $i++) {
    $XMLTEAM[$i]['race_data']['position'] = ($i + 1);
    if ($XMLTEAM[$i]['race_data']['fastest_lap'] < $XMLRACE['fastest_lap']) {
        $XMLRACE['fastest_lap'] = $XMLTEAM[$i]['race_data']['fastest_lap'];
    }
    if ($XMLTEAM[$i]['race_data']['fastest_lap'] < $XMLRACE['classes'][($XMLTEAM[$i]['team_data']['class'])]['fastest_lap']) {
        $XMLRACE['classes'][($XMLTEAM[$i]['team_data']['class'])]['fastest_lap'] = $XMLTEAM[$i]['race_data']['fastest_lap'];
    }
    if ($i > 0) {
        if ($XMLTEAM[$i]['race_data']['laps'] > 0) {
            $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = $XMLTEAM[$i]['race_data']['fastest_lap'] -
                $XMLTEAM[$i - 1]['race_data']['fastest_lap'];
        } else
            $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = "";
    } else
        $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = "";


    if ($i > 0) {
        if ($XMLTEAM[$i]['race_data']['laps'] > 0) {
            if ($XMLRACE['numClasses'] > 1) {
                $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "+" . $XMLTEAM[$i]['race_data']['fastest_lap'] -
                    $XMLRACE['classes'][($XMLTEAM[$i]['team_data']['class'])]['fastest_lap'];
            } else {
                $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "+" . $XMLTEAM[$i]['race_data']['fastest_lap'] -
                    $XMLRACE['fastest_lap'];
            }

        } else
            $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "";
    } else
        $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = ""; // pole time


    if (strlen($XMLTEAM[$i]['race_data']['fastest_lap']) == 5) {
        $lapSeconds = substr($XMLTEAM[$i]['race_data']['fastest_lap'], 0, 2) . "." .
            substr($XMLTEAM[$i]['race_data']['fastest_lap'], -3);
    } else {
        $lapSeconds = substr($XMLTEAM[$i]['race_data']['fastest_lap'], 0, 3) . "." .
            substr($XMLTEAM[$i]['race_data']['fastest_lap'], -3);
    }
    $XMLTEAM[$i]['race_data']['kph'] = ($raceTrackLengthKm) / ($lapSeconds / 60 / 60);
    $XMLTEAM[$i]['race_data']['mph'] = $XMLTEAM[$i]['race_data']['kph'] *
        0.621371192;
    if ($XMLRACE['numClasses'] > 1) {
        $XMLTEAM[$i]['race_data']['percent'] = $XMLTEAM[$i]['race_data']['fastest_lap'] /
            $XMLRACE['classes'][($XMLTEAM[$i]['team_data']['class'])]['fastest_lap'] * 100;
    } else {
        $XMLTEAM[$i]['race_data']['percent'] = $XMLTEAM[$i]['race_data']['fastest_lap'] /
            $XMLRACE['fastest_lap'] * 100;
    }
    for ($l = 0; $l < $XMLTEAM[$i]['team_data']['num_drivers']; ++$l) {
        if ($XMLTEAM[$i]['race_data']['current_driver'] == $XMLTEAM[$i]['team_data']['drivers'][$l]['driver_lfs']) {
            $XMLTEAM[$i]['race_data']['current_driver_num'] = $l;
        }
    }

}
$totalloop += (microtime(true) - $time2);
if ($raceControl) {
    mysql_set_charset('latin1');
    $chat_search = mysql_query("SELECT lfsworld, type, value, created_on FROM " .
        SQL_LAP . " WHERE (type='MSG' OR type='BADJOIN' OR type='SHIFTS' OR type='" .
        strtoupper($trackerModeShort) . "_START' OR type='LEAVE')" . $rid_string .
        " ORDER BY race_id asc, id asc");
    while ($r = mysql_fetch_array($chat_search))
        $chat_array[] = $r;
    $XMLCHAT = array();
    $k = 0;
    // if (!empty($chat)) {
    if (($futureRaceStart - time() <= 0) or (strtoupper($XMLRACE['session_status'])
        !== "PRE-RACE")) {
        foreach ($chat_array as $chat) {
            $XMLCHAT[$k]['lfsworld'] = $chat['lfsworld'];
            $XMLCHAT[$k]['type'] = $chat['type'];
            $XMLCHAT[$k]['value'] = $chat['value'];
            $XMLCHAT[$k]['logged'] = $chat['created_on'];
            ++$k;
        }
    }
    /* MAIN STATS OUTPUT */
    //ob_clean();
    ob_start();
    include ('racecontrol.php');
    $statsphp = ob_get_contents();
    ob_clean();
    writeToFile('racecontrol.html', $statsphp);
    writeToFile('racecontrolq.html', $statsphp);
    unset($statsphp);
    ob_clean();
}
ob_start();
include ('qstats.php');
$statsphp = ob_get_contents();
ob_clean();
writeToFile('index.html', $statsphp);
writeToFile('qualifying.html', $statsphp);
unset($statsphp);
ob_clean();
/*
ob_start();
include ('qmobile.php');
$mobilephp = ob_get_contents();
ob_clean();
writeToFile('mobileq.html', $mobilephp);
unset($mobilephp);*/
foreach ($XMLTEAM as $i => $team) {
    ob_start();
    include ('qteamstats.php');
    $teamstats = ob_get_contents();
    ob_clean();
    writeToFile($trackerModeShort . '_' . $team['team_data']['number'] . '.html', $teamstats);
    //sleep(1);
}
reset($XMLTEAM);
if ($debugArrays) {
    print_r($XMLRACE);
    print_r($XMLTEAM);
}
?>