<?php

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

include_once './includes/users/MemberLister.inc.php';
include_once './includes/users/Member.inc.php';
include_once './includes/users/MemberFormatter.inc.php';

include_once './includes/users/userRights/MemberRight.inc.php';
include_once './includes/users/userRights/MemberRightListFormatter.inc.php';

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

include_once './includes/exceptions/BadFormatException.inc.php';

/**
 * This class represents the administration part of the users system.
 *
 * TODO: Localization
 *
 * @author Thomas Schwery <thomas.schwery@epfl.ch>
 */
class UserAdministrationPage extends AdministrationPage {

    private $content;

    private $title;

    protected function constructAdmin() {
        if (key_exists("username", $_POST)) {
            $this->saveMember();
        } else if (key_exists("type", $_GET) AND ($_GET['type'] == "create")) {
            $this->createMember();
        } else if (key_exists("type", $_GET) AND ($_GET['type'] == "delete")) {
            $this->deleteMember();
        } else if (key_exists("user", $_GET)) {
            $this->modifyMember();
        } else {
            $this->listMembers();
        }
    }

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

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

    private function listMembers() {
        $this->title = Localization::userAdmin;
        $this->content = "";

        $users = MemberLister::getAll();
        ;

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

        foreach ($users as $user) {
            $this->content .= MemberFormatter::getAdminBox($user);
            $this->content .= "<a href='./?page=UserAdministration&user=" .
                    $user->getUsername() . "'>$labelEdit</a> - ";
            $this->content .= "<a href='./?page=UserAdministration&user=" .
                    $user->getUsername() . "&type=delete'>$labelDelete</a><br><br>";
        }

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

    private function modifyMember() {
        $user = MemberLister::getByLogin($_GET['user']);

        if (!$user) {
            return;
        }

        $fullName = $user->getFullName();
        $username = $user->getUsername();
        $birthday = $user->getBirthday();
        $rights = $user->getRights();
        $mail = $user->getMail();

        $this->formMember($username, $fullName, $birthday, $rights, $mail, true);
    }

    private function createMember() {

        $fullName = Localization::userFullName;
        $username = Localization::userUsername;
        $birthday = time();
        $rights = array();
        $mail = "username@somewhere.com";

        $this->formMember($username, $fullName, $birthday, $rights, $mail, false);
    }

    /**
     * Generates an HTML form to edit the informations concerning an user.
     *
     * @param <type> $username
     * @param <type> $fullName
     * @param <type> $birthday
     * @param <type> $rights
     * @param <type> $mail
     *
     */
    private function formMember($username, $fullName, $birthday, $rights, $mail, $readonly) {
        
        $this->title = Localization::userEdit;

        if ($readonly) {
            $formReadOnly = 'readonly="readonly"';
        } else {
            $formReadOnly = "";
        }

        $labelEdit = Localization::generalEdit;
        $labelUsername = Localization::userUsername;
        $labelFullname = Localization::userFullName;
        $labelBirthday = Localization::userBirthday;
        $labelMail = Localization::userMail;
        $labelPassword = Localization::userPassword;
        $labelSubmit = Localization::generalSubmit;

        $user = MemberLister::getByLogin($username);

        if ($user) {
            $rightsPart = MemberRightListFormatter::GetForm($user);
        } else {
            $rightsPart = MemberRightListFormatter::GetBlankForm();
        }

        $birthdayPart = DateFormatter::GetDMYForm("userBirthday", $birthday);

        $this->content = <<<FORM
<form name="userCreation" method="post" action="./?page=UserAdministration">
    <fieldset>
        <legend>$labelEdit : $fullName</legend>
        <label for="username">$labelUsername</label>
        <input name="username" id="username" type="text" value="$username" $formReadOnly><br>
        <label for="userFullName">$labelFullname</label>
        <input name="userFullName" id="userFullName" type="text" value="$fullName"><br>
        <label for="userBirthday">$labelBirthday</label>
        $birthdayPart<br>
        <label for="userMail">$labelMail</label>
        <input name="userMail" id="userMail" type="text" value="$mail"><br>
        <label for="userPassword">$labelPassword</label>
        <input name="userPassword" id="userPassword" type="text" value=""><br>
                <fieldset>
                <legend>Rights</legend>
                $rightsPart
                </fieldset>
        <input type="submit" name="Submit" value="$labelSubmit">
    </fieldset>
</form>
FORM;
    }

    private function saveMember() {
        $this->title = Localization::userAdmin;

        $username = InputSanitizer::Username($_POST['username']);
        $fullName = InputSanitizer::Sanitize($_POST['userFullName']);

        $birthday = mktime(0,0,0,
                $_POST['userBirthday_months'], $_POST['userBirthday_days'], $_POST['userBirthday_year']);

        $mail = $_POST['userMail'];

        $memberRightsArray = array();

        if (key_exists("memberRight", $_POST)) {
            $memberRights = $_POST['memberRight'];
            foreach ($memberRights as $memberRight) {
                $memberRightsArray[] = MemberRight::Get($memberRight);
            }
        }

        if (key_exists("memberHiddenRight", $_POST)) {
            $memberHiddenRights = $_POST['memberHiddenRight'];
            foreach ($memberHiddenRights as $memberHiddenRight) {
                $memberRightsArray[] = MemberRight::Get($memberHiddenRight);
            }
        }

        $user = MemberLister::getByLogin($username);

        if (key_exists("userPassword", $_POST)) {
            $password = $_POST['userPassword'];
        } else {
            $password = "";
        }

        if (!$user) {
            $user = Member::Create($fullName, $username, $password, $birthday, $mail, $memberRightsArray);
        } else {
            $user->setInformations($fullName, $memberRightsArray, $password, $birthday, $mail);
        }

        $this->title = Localization::userEdit;
        $this->content .= "<br>";
        $this->content .= "<a href='./?page=UserAdministration'>" . Localization::generalBackAdmin . "</a>";
    }

    private function deleteMember() {
        $user = false;
        $this->title = Localization::userAdmin;

        if (key_exists('user', $_GET)) {
            $user = MemberLister::getByLogin($_GET['user']);
        } else if (key_exists('user', $_POST)) {
            $user = MemberLister::getByLogin($_POST['user']);
        }

        if (!$user) {
            $this->content.= "<a href='./?page=UserAdministration'>" . Localization::generalBackAdmin . "</a>";
            return;
        }

        if (key_exists('deleteArticles', $_POST)) {

            $identifier = $user->getIdentifier();
            $deleteArticles = ($_POST['deleteArticles'] == 'delete');
            $result = Member::Remove($identifier, $deleteArticles);

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

        } else {
            $username = $user->getUsername();
            $fullName = $user->getFullName();

            $labelDelete = Localization::userDeleteArticles;
            $labelKeep = Localization::userKeepArticles;
            $labelSubmit = Localization::generalSubmit;
            $labelDeletion = Localization::generalDelete;

            $this->content = <<<FORM
<form name="userDeletion" method="post" action="./?page=UserAdministration&type=delete">
    <fieldset>
        <legend>$labelDeletion : $fullName</legend>
        <input type="hidden" name="user" value="$username">
        <label for="delete">$labelDelete</label>
        <input type="radio" checked="checked" name="deleteArticles" value="delete" id="delete"><br>
        <label for="keep">$labelKeep</label>
        <input type="radio" name="deleteArticles" value="keep" id="keep"><br>
        <input type="submit" name="Submit" value="$labelSubmit">
    </fieldset>
</form>
FORM;
        }
    }
}
?>
