<?php

include_once './includes/database/MySQLDatabase.inc.php';

/**
 * This class represents a category.
 *
 * @author Thomas Schwery <thomas.schwery@epfl.ch>
 */
class Category {

    private $identifier;

    private $name;

    private $needSaving;

    public static function Get($identifier) {
        $newCategory = new Category($identifier);

        $sql = "SELECT * FROM categories WHERE identifier = $identifier LIMIT 1;";

        $result = MySQLDatabase::getInstance()->runRequest($sql);

        $result = $result[0];

        if (!$result) {
            return false;
        }

        $newCategory->name = $result['name'];

        $newCategory->needSaving = false;

        return $newCategory;
    }

    public static function Create($name) {
        $name = InputSanitizer::Sanitize($name);

        $sql = "INSERT INTO `categories` (`identifier`, `name`)
            VALUES (NULL, '$name');";

        $result = MySQLDatabase::getInstance()->runOperation($sql);

        $sql = "SELECT identifier FROM categories WHERE name = $name LIMIT 1;";
        $result = $database->runRequest($sql);

        $identifier = $result[0]['identifier'];

        $newCategory = Category::Get($identifier);
        return $newCategory;
    }

    public static function Remove($identifier) {

        $sql = "DELETE FROM `categories` WHERE `identifier` = $identifier;";
        $result = MySQLDatabase::getInstance()->runOperation($sql);

        $sql = "DELETE FROM `tournamentsEntries` WHERE `categoryId` = $identifier;";
        $result += MySQLDatabase::getInstance()->runOperation($sql);

        return $result;
    }

    private function __construct($identifier) {
        $this->identifier = $identifier;
    }

    public function  __destruct() {
        if ($this->needSaving) {
            $this->save();
        }
    }

    private function save() {
        $sql = "UPDATE `categories` SET
            `name` = '$this->name'
            WHERE `identifier` = $this->identifier;";

        $result = MySQLDatabase::getInstance()->runOperation($sql);
    }

    public function getIdentifier() {
        return $this->identifier;
    }

    public function getName() {
        return $this->name;
    }

    public function setContent($name) {
        $this->name = $name;

        $this->needSaving = true;
    }

}
?>
