<?php

include_once './pages/AdministrationPage.inc.php';

include_once './includes/tournaments/Tournament.inc.php';
include_once './includes/tournaments/TournamentLister.inc.php';

include_once './includes/tournaments/TournamentEntry.inc.php';
include_once './includes/tournaments/TournamentEntryLister.inc.php';

include_once './includes/tournaments/Category.inc.php';
include_once './includes/tournaments/CategoryLister.inc.php';
include_once './includes/tournaments/CategoryListFormatter.inc.php';

include_once './includes/users/MemberListFormatter.inc.php';

include_once './includes/utils/DateParser.inc.php';
include_once './includes/utils/DateFormatter.inc.php';

/**
 * This class represents the administration page for the tournaments
 * part of the website.
 *
 * @author Thomas Schwery <thomas.schwery@epfl.ch>
 */
class TournamentAdministrationPage extends AdministrationPage {

    private $title;

    private $content;

    protected function constructAdmin() {
        $this->content = "";

        if (key_exists('tournamentIdentifier', $_POST)) {
            $this->save();
        } else if (key_exists("type", $_GET) AND ($_GET['type'] == "create")) {
            $this->create();
        } else if (key_exists("type", $_GET) AND ($_GET['type'] == "delete")) {
            $this->delete();
        } else if (key_exists("tournamentIdentifier", $_GET)) {
            $this->modify();
        } else {
            $this->listing();
        }
    }

    public function getContent() {
        return $this->content;
    }

    public function getTitle() {
        return $this->title;
    }

    public function getHeaderEntry() {

        $entryName = "entryName_'+counter+'";
        $nameSelect = MemberListFormatter::getSelectMembers($entryName, "delete");

        $entryCategory = "entryCategory_'+counter+'";
        $entrySelect = CategoryListFormatter::getSelectCategories($entryCategory, "");

        $formHelper = <<<FORM
<script type="text/javascript">
function test() {
    var tblBody = document.getElementById('tableId').tBodies[0];
    var counter=document.getElementById('tableId').rows.length;
    var newRow = tblBody.insertRow(-1);
    var newCell0 = newRow.insertCell(0);
    newCell0.innerHTML = '$nameSelect';
    newCell0.innerHTML += '$entrySelect';
    var newCell1 = newRow.insertCell(1);
    newCell1.innerHTML = '<input name="entryPoints_'+counter+'"type="input" value="Points '+counter+'"/>';
    var newCell2 = newRow.insertCell(2);
    newCell2.innerHTML = '<input name="entryRank_'+counter+'"type="input" value="Rank '+counter+'"/>';
    newCell2.innerHTML += '<input name="entryParticipants_'+counter+'"type="input" value="Participants '+counter+'"/>';
    var newCell3 = newRow.insertCell(3);
    newCell3.innerHTML = '<input name="entryId_'+counter+'"type="hidden" value="-1"/>';
}
window.onload = test;
</script>
FORM;
        return $formHelper;
    }

    private function create() {
        $identifier = -1;
        $name = Localization::tournamentCategory;
        $type = Localization::tournamentType;
        $date = time();
        $comments = Localization::tournamentComment;
        $location = Localization::tournamentLocation;
        $entries = array();

        $this->form($identifier, $name, $type, $date, $location, $comments, $entries);
    }

    private function modify() {
        $identifier = $_GET['tournamentIdentifier'];
        $tournament = Tournament::Get($identifier);

        $name = $tournament->getName();
        $type = $tournament->getType();
        $date = $tournament->getDate();
        $location = $tournament->getLocation();
        $comments = $tournament->getComments();

        $entries = TournamentEntryLister::getAllEntries($tournament);

        $this->form($identifier, $name, $type, $date, $location, $comments, $entries);
    }

    private function form($identifier, $name, $type, $date, $location, $comments, $entries) {
        $this->title = Localization::tournamentEdition . " : " . $name;

        $existantEntries = "";
        $counter = 0;
        foreach($entries as $entry) {
            $counter++;

            $entryName = $entry->getMember()->getUsername();
            $entryCategory = $entry->getCategory()->getName();
            $entryPoints = $entry->getPoints();
            $entryRank = $entry->getRank();
            $entryParticipants = $entry->getParticipants();
            $entryId = $entry->getIdentifier();

            $existantEntries .= "<tr><td>";
            $existantEntries .= MemberListFormatter::getSelectMembers("entryName_$counter", $entryName);
            $existantEntries .= CategoryListFormatter::getSelectCategories("entryCategory_$counter",$entryCategory);
            $existantEntries .= "</td><td>";
            $existantEntries .= "<input name='entryPoints_$counter' value='$entryPoints' type='input'>";
            $existantEntries .= "</td><td>";
            $existantEntries .= "<input name='entryRank_$counter' value='$entryRank' type='input'>";
            $existantEntries .= "<input name='entryParticipants_$counter' value='$entryParticipants' type='input'>";
            $existantEntries .= "</td><td>";
            $existantEntries .= "<input name='entryId_$counter' value='$entryId' type='hidden'>";
            $existantEntries .= "</td></tr>";
        }

        $labelTournamentName = Localization::tournamentName;
        $labelLocation = Localization::tournamentLocation;
        $labelDate = Localization::tournamentDate;
        $labelType = Localization::tournamentType;
        $labelComments = Localization::tournamentComment;

        $labelName = Localization::userFullName;
        $labelCategory = Localization::tournamentCategory;
        $labelPoints = Localization::tournamentPoints;
        $labelRank = Localization::tournamentRank;
        $labelParticipants = Localization::tournamentParticipants;

        $labelAddEntry = Localization::tournamentAddEntry;
        $labelSubmit = Localization::generalSubmit;

        $datePart = DateFormatter::GetDMYForm("tournamentDate", $date);

        $this->content = <<<FORM
<form method="post" action="./?page=TournamentAdministration">
    <input name="tournamentIdentifier" type="hidden" value="$identifier">
    <label for="tournamentName">$labelTournamentName</label>
    <input name="tournamentName" id="tournamentName" type="text" value="$name"><br>
    <label for="tournamentLocation">$labelLocation</label>
    <input name="tournamentLocation" id="tournamentLocation" type="text" value="$location"><br>
    <label for="tournamentDate">$labelDate</label>
    $datePart<br>
    <label for="tournamentType">$labelType</label>
    <input name="tournamentType" id="tournamentType" type="text" value="$type"><br>
    <label for="tournamentComments">$labelComments</label>
    <input name="tournamentComments" id="tournamentComments" type="text" value="$comments">
    <br><br>
    <table id='tableId' style='width: 100%; text-align: center;'>
        <tr>
            <th>$labelName / $labelCategory</th>
            <th>$labelPoints</th>
            <th>$labelRank / $labelParticipants</th>
        </<tr>
                $existantEntries
    </table>
    <br>
	<input type="button" id="moreFields" onclick="test();" value="$labelAddEntry" />
	<input type="submit" value="$labelSubmit" />
</form>


<!--ZZZEEEEUUUUUU T'AIIIIMMMMMEEEUUUUU!!!! <3 <3 <3 -->
FORM;
    }

    private function listing() {
        $this->title = Localization::tournamentList;

        $labelCreate = Localization::generalCreate;
        $labelModify = Localization::generalEdit;
        $labelDelete = Localization::generalDelete;

        $tournamentsArray = TournamentLister::getAllTournaments();

        foreach ($tournamentsArray as $tournament) {
            $this->content .= TournamentFormatter::getSummary($tournament);
            $this->content .= "<a href='./?page=TournamentAdministration&tournamentIdentifier=" .
                    $tournament->getIdentifier() . "'>$labelModify</a> - ";
            $this->content .= "<a href='./?page=TournamentAdministration&tournamentIdentifier=" .
                    $tournament->getIdentifier() . "&type=delete'>$labelDelete</a><br><br>";
        }

        $this->content .= "<a href='./?page=TournamentAdministration&type=create'>$labelCreate</a><br><br>";
    }

    private function save() {
        $this->title = Localization::tournamentEdition;

        $identifier = $_POST['tournamentIdentifier'];
        $name = $_POST['tournamentName'];
        $type = $_POST['tournamentType'];
        $location = $_POST['tournamentLocation'];
        $comments = $_POST['tournamentComments'];

        $date = mktime(0,0,0,
                $_POST['tournamentDate_months'], $_POST['tournamentDate_days'], $_POST['tournamentDate_year']);

        if ($identifier >= 0) {
            $tournament = Tournament::Get($identifier);
            $tournament->setInformations($name, $location, $date, $type, $comments);
        } else {
            $tournament = Tournament::Create($name, $location, $date, $type, $comments);
        }

        $entryCounter = 1;
        $entries = array();

        while (key_exists("entryName_$entryCounter", $_POST)) {
            $entryName = $_POST["entryName_$entryCounter"];
            $entryPoints = $_POST["entryPoints_$entryCounter"];
            $entryCategory = $_POST["entryCategory_$entryCounter"];
            $entryParticipants = $_POST["entryParticipants_$entryCounter"];
            $entryRank = $_POST["entryRank_$entryCounter"];
            $entryId = $_POST["entryId_$entryCounter"];

            $user = MemberLister::getByLogin($entryName);
            $category = CategoryLister::GetCategoryByName($entryCategory);

            if (!$category || !$user) {
                if($entryId>0) {
                    TournamentEntry::Remove($entryId);
                }
                break;
            }

            if($entryId>0) {
                $entry = TournamentEntry::Get($entryId);
                $entry->setContent($user, $category, $entryPoints, $entryRank, $entryParticipants);
            } else {
                $entry = TournamentEntry::Create($tournament, $user, $category, $entryPoints, $entryRank, $entryParticipants);
            }

            $entryCounter++;
        }

        $this->content .= Localization::generalEditionResult;
        $this->content.= "<br>";
        $this->content.= "<a href='./?page=TournamentAdministration'>" . Localization::generalBackAdmin . "</a>";

    }

    private function delete() {
        $this->title = Localization::tournamentDeletion;

        if (!key_exists("sure", $_GET)) {
            $deleteLabel = Localization::generalDelete;
            $this->content = Localization::generalDeletionConfirmation . "<br>";
            $this->content.= "<a href='./?page=TournamentAdministration&tournamentIdentifier=" .
                    $_GET['tournamentIdentifier'] . "&type=delete&sure=yes'>$deleteLabel</a><br><br>";
        } else {
            $result = Tournament::Remove($_GET['tournamentIdentifier']);
            $this->content .= $result . " " . Localization::generalDeletionNumber;
            $this->content.= "<br>";
            $this->content.= "<a href='./?page=TournamentAdministration'>" . Localization::generalBackAdmin . "</a>";
        }
    }
}
?>
