<?php
error_reporting(E_ALL);

//echo time();

//include 'header.php';

$startTime = array_sum(explode(chr(32), microtime()));
require_once 'functions.php';
require_once 'variables.php';
require_once 'sql.php';


mysql_connect(SQL_HOST, SQL_USER, SQL_PASS);
mysql_select_db(SQL_DB);


/*
$loadavg = file("/proc/loadavg");
$loadavg = explode(" ",$loadavg[0]);
$loadavg = $loadavg[0];
*/
$loadavg = 0;
if ($loadavg > 8) {
    echo "Sorry! Server load critical.";
    exit();
    writeToFile('index.html', "Sorry! Server load critical.");
    exit();
} else {


    if ($numServers == 2) {
        $rid_string = " AND (";

        if ($useManualIdServer1)
            $race_id = $manualIdServer1;
        else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE .
                " where server='1'");
            $race_id = mysql_result($r_res, 0, 'id');

        }

        $rid_string .= " race_id='" . $race_id . "' ";

        if ($useManualIdServer2)
            $race_id = $manualIdServer2;
        else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE .
                " where server='2'");
            $race_id = mysql_result($r_res, 0, 'id');
        }

        $rid_string .= " OR race_id='" . $race_id . "' ";
        $rid_string .= " ) ";
    } elseif ($numServers == 3) {

        $rid_string = " AND (";

        if ($useManualIdServer1)
            $race_id = $manualIdServer1;
        else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE .
                " where server='1'");
            $race_id = mysql_result($r_res, 0, 'id');

        }

        $rid_string .= " race_id='" . $race_id . "' ";

        if ($useManualIdServer2)
            $race_id = $manualIdServer2;
        else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE .
                " where server='2'");
            $race_id = mysql_result($r_res, 0, 'id');
        }

        $rid_string .= " OR race_id='" . $race_id . "' ";
        if ($useManualIdServer3)
            $race_id = $manualIdServer3;
        else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE .
                " where server='3'");
            $race_id = mysql_result($r_res, 0, 'id');
        }

        $rid_string .= " OR race_id='" . $race_id . "' ";
        $rid_string .= " ) ";


        if ($useManualIdServer1) {
            $rid_string = " AND (";
            $race_id = $manualIdServer1;
            $rid_string .= " race_id>='" . $race_id . "' ";
            $rid_string .= " ) ";
        }


    } elseif ($numServers == 1) {

        if ($useManualIdServer1) {
            $race_id = $manualIdServer1;
        } else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE .
                " where server='1'") or die(mysql_error());
            $race_id = mysql_result($r_res, 0, 'id');

        }
        if ($server_crash) {
            $rid_string = "AND ( race_id>='" . $race_id . "')";
        } else {
            $rid_string = "AND ( race_id='" . $race_id . "')";
        }

    } else {
        print "Incompatible number of servers specified.";
        die;
    }

    // GET TIMESTAMP OF WHEN RACE WAS STARTED
    $race_res = mysql_query("SELECT * FROM " . SQL_LAP . " WHERE type='RACE_START' " .
        $rid_string . " ORDER BY race_id asc") or die(mysql_error());
    if (mysql_num_rows($race_res) > 0)
        $race_start = mysql_result($race_res, 0, 'created_on');

    $XMLRACE = $RACE;
    $XMLRACE['race_start'] = $race_start;
    global $XMLRACE;

    $XMLTEAM = array();
    //<!-- Count the number of driverswaps, pitstops, dt and s&g a team has done -->
    $server_language = "ENGLISH";
    if ($server_language == "ENGLISH") {
        $pitstop_search = mysql_query("SELECT * FROM " . SQL_LAP .
            " WHERE type='MSG' AND value LIKE '% pit stop'" . $rid_string .
            " ORDER BY race_id asc");
        $dt_search = mysql_query("SELECT * FROM " . SQL_LAP .
            " WHERE type='MSG' AND value LIKE '% : DRIVE-THROUGH PENALTY'" . $rid_string .
            " ORDER BY race_id asc");
        $finished = mysql_query("SELECT * FROM " . SQL_LAP .
            " WHERE type='MSG' AND value LIKE '%^L finished %' OR value LIKE '%^L won the race'" .
            $rid_string . " ORDER BY race_id asc");
    }

    if ($server_language == "GERMAN") {
        $pitstop_search = mysql_query("SELECT * FROM " . SQL_LAP .
            " WHERE type='MSG' AND value LIKE '%Boxenstopp'" . $rid_string .
            " ORDER BY race_id asc");
        $dt_search = mysql_query("SELECT * FROM " . SQL_LAP .
            " WHERE type='MSG' AND value LIKE '%Durchfahrtsstrafe'" . $rid_string .
            " ORDER BY race_id asc");
    }

    $finishedDrivers = array();
    while ($r = mysql_fetch_array($finished)) {
        $finishedDrivers[] = $r;
    }


    $pitinout_search = mysql_query("SELECT * FROM " . SQL_LAP .
        " WHERE (type='PITIN' OR type='PITOUT') AND (lfsworld != '') " . $rid_string .
        " ORDER BY race_id asc, id asc");

    while ($r = mysql_fetch_array($pitstop_search))
        $pitstop_array[] = $r;

    while ($r = mysql_fetch_array($dt_search))
        $dt_array[] = $r;

    while ($r = mysql_fetch_array($pitinout_search))
        $pitinout_array[] = $r;

    foreach ($TEAMS as $key => $team) {
        $XMLTEAM[$key]['team_data'] = array();
        $XMLTEAM[$key]['team_data']['name'] = $TEAMS[$key]['team_name'];
        $XMLTEAM[$key]['team_data']['name_presuffix'] = $TEAMS[$key]['name_presuffix'];
        $XMLTEAM[$key]['team_data']['car'] = $TEAMS[$key]['car'];
        $XMLTEAM[$key]['team_data']['number'] = $TEAMS[$key]['number'];
        $XMLTEAM[$key]['team_data']['display'] = $TEAMS[$key]['display'];
        if ($showPresuffix)
            $XMLTEAM[$key]['team_data']['name'] = $TEAMS[$key]['name_presuffix'] . ' - ' . $TEAMS[$key]['team_name'];


        $i = 0;
        foreach ($TEAMS[$key]['driver_active'] as $k => $active) {
            if ($active) {
                $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_lfs'] = strtolower($TEAMS[$key]['driver_lfs'][$k]);
                $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_real'] = format_name($TEAMS[$key]['driver_real'][$k]);
                $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_country'] = strtolower($TEAMS[$key]['driver_country'][$k]);

                // check if team has finished
                foreach ($finishedDrivers as $msg) {

                    $hayStack = strtolower($msg['value']);
                    $needle = strtolower($TEAMS[$key]['driver_real'][$k]);
                    $teamFinished = (strpos($hayStack, $needle) === false) ? false : true;

                    if ($teamFinished) {
                        $output = "Driver " . $TEAMS[$key]['driver_real'][$k] .
                            " finished the race for team " . $XMLTEAM[$key]['team_data']['name'];
                        $team['finished_on'] = $msg['created_on'];
                    }
                }


                $i++;
            }
        }

        $XMLTEAM[$key]['team_data']['num_drivers'] = $i;

        //<!-- Group the drivers together and get all the LAPs they drove from the database -->

        $timeLimit = null;
        // cut off finished teams
        if (isset($team['finished_on']) && $team['finished_on'] != "") {
            $finishTime = $team['finished_on'];
            $timeLimit = " AND `created_on` <= '" . $finishTime . "' ";
        }


        $drivers = generateDriverString($team);
        $sql = "SELECT * FROM " . SQL_LAP . " WHERE type='LAP' $timeLimit AND (" . $drivers .
            ") " . $rid_string . " $timeoffset 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;
            $XMLTEAM[$key]['raw_laps'][$i]['lap'] = $res->lap;
            $XMLTEAM[$key]['raw_laps'][$i]['laptime'] = $res->value;
            $XMLTEAM[$key]['raw_laps'][$i]['driverUserName'] = $res->lfsworld;
            $XMLTEAM[$key]['raw_laps'][$i]['logged'] = $res->created_on;
            $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]['filter_laps'] = filterLaps($XMLTEAM[$key]['raw_laps']);

        $XMLTEAM[$key]['race_data']['laps'] = countLaps($XMLTEAM[$key]['filter_laps']);
        $XMLTEAM[$key]['race_data']['total_time'] = totalTime($XMLTEAM[$key]['filter_laps'],
            $race_start);


        // COUNT NUMBER OF PITSTOPS
        $pitted = 0;
        foreach ($pitstop_array as $pitstop_value) {
            if (inTeam($pitstop_value['value'], $team['number'])) {
                $XMLTEAM[$key]['race_data']['last_pit'] = $pitstop_value['created_on'];
                $pitted++;
            }
        }
        $XMLTEAM[$key]['race_data']['num_pits'] = $pitted;

        // SAVE RECORD OF PITIN AND PITOUT MESSAGES

        $l = 0;
        if (count($pitinout_array) > 0) {
            foreach ($pitinout_array as $pitio_value) {
                for ($k = 0; $k < count($XMLTEAM[$key]['team_data']['drivers']); $k++) {
                    //print $pitio_value['lfsworld'] . " > " . $XMLTEAM[$key]['team_data']['drivers'][$k]['driver_lfs']. "<br/>";
                    if (strtolower($pitio_value['lfsworld']) == strtolower($XMLTEAM[$key]['team_data']['drivers'][$k]['driver_lfs'])) {
                        $XMLTEAM[$key]['race_data']['pitstops'][$l]['type'] = $pitio_value['type'];
                        $XMLTEAM[$key]['race_data']['pitstops'][$l]['time'] = $pitio_value['created_on'];
                        $XMLTEAM[$key]['race_data']['pitstops'][$l]['lap'] = $pitio_value['lap'];
                        $XMLTEAM[$key]['race_data']['pitstops'][$l]['mysqlid'] = $pitio_value['id'];
                        $l++;
                    }
                }
            }
        }

        // COUNT NUMBER OF DRIVE THROUGHS
        $dt = 0;
        if (count($dt_array) > 0) {
            foreach ($dt_array as $dt_value) {
                if (inTeam($dt_value['value'], $team['number']))
                    $dt++;
            }
            $XMLTEAM[$key]['race_data']['num_dt'] = $dt;
        } else
            $XMLTEAM[$key]['race_data']['num_dt'] = 0;

        // COUNT NUMBER OF DRIVERSWAPS
        $swap = 0;
        for ($i = 1; $i < count($XMLTEAM[$key]['raw_laps']); $i++) {
            if ($XMLTEAM[$key]['filter_laps'][$i]['driverUserName'] != $XMLTEAM[$key]['filter_laps'][$i -
                1]['driverUserName'])
                $swap++;
        }
        $XMLTEAM[$key]['race_data']['num_swap'] = $swap;


        // DETERMIN THE CURRENT POSITION OF THE CAR
        // DETERMIN THE DRIVER CURRENTLY IN THE CAR


        $sql_res2 = mysql_query("SELECT * 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'] = strtolower(mysql_result($sql_res2,
                0, 'lfsworld'));
        } else {
            $XMLTEAM[$key]['race_data']['current_sector'] = 0;
        }

        //unset($XMLTEAM[$key]['raw_laps']);
        //unset($XMLTEAM[$key]['filter_laps']);

        // PENALTY AND CORRECTION LAPS

        $XMLTEAM[$key]['race_data']['penalty_laps'] = $TEAMS[$key]['penalty_laps'];
        $XMLTEAM[$key]['race_data']['correction_laps'] = $TEAMS[$key]['standings_correction'];
        $XMLTEAM[$key]['race_data']['corrected_laps'] = $XMLTEAM[$key]['race_data']['laps'] +
            $TEAMS[$key]['penalty_laps'] + $TEAMS[$key]['standings_correction'];
        //$XMLTEAM[$key]['race_data']['corrected_laps'] = $XMLTEAM[$key]['race_data']['laps'] + $TEAMS[$key]['penalty_laps'];


    }

    usort($XMLTEAM, "sort_standings");

    for ($i = 0; $i < count($XMLTEAM); $i++) {
        $XMLTEAM[$i]['race_data']['position'] = ($i + 1);

        if ($i > 0) {
            if ($XMLTEAM[$i]['race_data']['laps'] > 0)
                if (($XMLTEAM[$i - 1]['race_data']['corrected_laps'] - $XMLTEAM[$i]['race_data']['corrected_laps']) >
                    0)
                    $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = "+" . ($XMLTEAM[$i - 1]['race_data']['corrected_laps'] -
                        $XMLTEAM[$i]['race_data']['corrected_laps']) . " laps";
                else
                    $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = normalTime(($XMLTEAM[$i]['race_data']['total_time'] -
                        totalTime($XMLTEAM[$i - 1]['filter_laps'], $race_start, $XMLTEAM[$i]['race_data']['laps'])) *
                        10, false);
            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 (($XMLTEAM[0]['race_data']['corrected_laps'] - $XMLTEAM[$i]['race_data']['corrected_laps']) >
                    0)
                    $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "+" . ($XMLTEAM[0]['race_data']['corrected_laps'] -
                        $XMLTEAM[$i]['race_data']['corrected_laps']) . " laps";
                else //$XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "+" . normalTime(($XMLTEAM[0]['race_data']['total_time'] - $XMLTEAM[$i]['race_data']['total_time'])*10, false);

                    $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "+" . normalTime(($XMLTEAM[$i]['race_data']['total_time'] -
                        totalTime($XMLTEAM[0]['filter_laps'], $race_start, $XMLTEAM[$i]['race_data']['laps'])) *
                        10, false);
            } else
                $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "";
        } else
            $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = $XMLTEAM[$i]['race_data']['corrected_laps'] .
                " laps";


        for ($l = 0; $l < $XMLTEAM[$i]['team_data']['num_drivers']; $l++) {
            $XMLTEAM[$i]['race_data']['drivers'][$l]['driver_lfs'] = $XMLTEAM[$i]['team_data']['drivers'][$l]['driver_lfs'];
            $XMLTEAM[$i]['race_data']['drivers'][$l]['laps'] = 0;
            $XMLTEAM[$i]['race_data']['drivers'][$l]['fastest_lap'] = 99999999999;
        }

        $XMLTEAM[$i]['race_data']['fastest_lap'] = 99999999999;

        for ($k = 0; $k < $XMLTEAM[$i]['race_data']['laps']; $k++) {
            for ($l = 0; $l < $XMLTEAM[$i]['team_data']['num_drivers']; $l++) {
                if (strtolower($XMLTEAM[$i]['filter_laps'][$k]['driverUserName']) == $XMLTEAM[$i]['race_data']['drivers'][$l]['driver_lfs']) {
                    $XMLTEAM[$i]['race_data']['drivers'][$l]['laps']++;
                    if ($XMLTEAM[$i]['filter_laps'][$k]['laptime'] != 0)
                        $XMLTEAM[$i]['race_data']['drivers'][$l]['fastest_lap'] = min($XMLTEAM[$i]['race_data']['drivers'][$l]['fastest_lap'],
                            $XMLTEAM[$i]['filter_laps'][$k]['laptime']);
                }
            }
            if ($XMLTEAM[$i]['filter_laps'][$k]['laptime'] != 0)
                $XMLTEAM[$i]['race_data']['fastest_lap'] = min($XMLTEAM[$i]['filter_laps'][$k]['laptime'],
                    $XMLTEAM[$i]['race_data']['fastest_lap']);
        }

        $XMLTEAM[$i]['race_data']['fastest_lap'] = normalTime($XMLTEAM[$i]['race_data']['fastest_lap']);

        for ($l = 0; $l < $XMLTEAM[$i]['team_data']['num_drivers']; $l++) {
            if ($XMLTEAM[$i]['race_data']['drivers'][$l]['laps'] == 0)
                $XMLTEAM[$i]['race_data']['drivers'][$l]['percent'] = 0;
            else
                $XMLTEAM[$i]['race_data']['drivers'][$l]['percent'] = round((($XMLTEAM[$i]['race_data']['drivers'][$l]['laps'] /
                    $XMLTEAM[$i]['race_data']['laps']) * 100), 1);

            if ($XMLTEAM[$i]['race_data']['drivers'][$l]['fastest_lap'] == 99999999999)
                $XMLTEAM[$i]['race_data']['drivers'][$l]['fastest_lap'] = "";
            else
                $XMLTEAM[$i]['race_data']['drivers'][$l]['fastest_lap'] = $XMLTEAM[$i]['race_data']['drivers'][$l]['fastest_lap'];

        }
    }

    $chat_search = mysql_query("SELECT * FROM " . SQL_LAP .
        " WHERE (type='MSG' OR type='JOIN' OR type='SHIFTS' OR type='RACE_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;
    foreach ($chat_array as $chat) {
        $XMLCHAT[$k]['type'] = $chat['type'];
        $XMLCHAT[$k]['lfsworld'] = $chat['lfsworld'];
        $XMLCHAT[$k]['value'] = $chat['value'];
        $XMLCHAT[$k]['lap'] = $chat['lap'];
        $XMLCHAT[$k]['logged'] = $chat['created_on'];
        $k++;
    }


    /*
    MAIN STATS OUTPUT
    */

    ob_clean();
    ob_start();
    include ('stats.php');
    $statsphp = ob_get_contents();
    ob_clean();

    writeToFile('index.html', $statsphp);
    unset($statsphp);

    foreach ($XMLTEAM as $i => $team) {
        ob_start();
        include ('teamstats.php');
        $teamstats = ob_get_contents();
        ob_clean();
        writeToFile('team_' . intval($team['team_data']['number']) . '.html', $teamstats);
        //sleep(1);
    }

    reset($XMLTEAM);

    foreach ($XMLTEAM as $j => $team) {
        ob_start();
        include ('unfiltered.php');
        $teamstats = ob_get_contents();
        ob_clean();
        writeToFile('unfiltered_' . intval($team['team_data']['number']) . '.html', $teamstats);
        //sleep(1);
    }

    ob_clean();
    ob_start();
    include ('racecontrol.php');
    $statsphp = ob_get_contents();
    ob_clean();

    writeToFile('racecontrol.html', $statsphp);
    unset($statsphp);
}
//echo time();

?>