<?php
include 'renderer.php';

class Planboard extends Renderer {
    public function __construct() {
        parent::__construct();
    }
    
    protected function generateContent(): void {
        $this->setOwnColor();
        $this->setColorLegend();
        $this->setContentTopics();
    }
    
    protected function setOwnColor(): void {
        $query = sprintf('SELECT c.color 
            FROM `user` u
            JOIN color c 
            ON c.id = u.color_id 
            WHERE u.id = %d', $_SESSION['userid']);
        $dbResult = mysqli_query($this->dbConnection, $query);
        $row = mysqli_fetch_assoc($dbResult);
        $this->content['owncolor'] = (!$row) ? '000000' : $row['color'];
    }
    
    protected function setColorLegend(): void {
        $legendData = [];
        $query = 'SELECT c.color, c2.last_name, c2.first_name, u.realname, u.salt usalt, c2.salt csalt
            FROM `user` u
            JOIN color c 
            ON c.id = u.color_id
            LEFT JOIN clubmember c2 
            ON c2.user_id = u.id 
            WHERE u.active = 1';
        $dbResult = mysqli_query($this->dbConnection, $query);
        while ($row = mysqli_fetch_assoc($dbResult)) {
            $legendData[] = '<div style="color:#' . $row['color'] . '">' . (($row['last_name']) 
                ? $this->decode($row['last_name'], $row['csalt']) . ', ' . $this->decode($row['first_name'], $row['csalt'])
                : $this->decode($row['realname'], $row['usalt'])) . '</div>';
        }
        $this->content['colors'] = implode('', $legendData);
    }
    
    protected function setContentTopics(): void {
        $topics = $this->getAllTopics();
        $prerenderedTopics = [];
        foreach ($topics as $topic) {
            $prerenderedTopics[] = '<option value="' . $topic['id'] . '">' . $topic['title'] . '</option>';
        }
        $this->content['topics'] = implode('', $prerenderedTopics);
    }
    
    public function render(): void {
        $action = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);
        if ($action === 'generate') {
            $this->generateDiscussion();
            return;
        }
        if ($action === 'fetchtopic') {
            $this->fetchTopic();
            return;
        }
        if ($action === 'setshortdescription') {
            $this->setShortDescription();
            return;
        }
        if ($action == 'setdiscussion') {
            $this->setDiscussion();
        }
        parent::render();
    }
    
    protected function generateDiscussion(): void {
        $topicName = TRIM(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
        if ($topicName === '') {
            echo '{"error": "Der Topic darf nicht leer sein."}';
            return;
        }
        $query = sprintf('SELECT id
            FROM discussion d 
            where title = "%s"', $topicName);
        $dbResult = mysqli_query($this->dbConnection, $query);
        if (mysqli_num_rows($dbResult) > 0) {
            echo '{"error": "Der Topic existiert schon."}';
            return;
        }
        $query = sprintf('INSERT INTO discussion (title, short_description, discussion) VALUES ("%s", "", "[]")', $topicName);
        mysqli_query($this->dbConnection, $query);
        $id = mysqli_insert_id($this->dbConnection);
        $output = [
            'topics' => $this->getAllTopics(),
            'id' => $id,
        ];
        echo json_encode($output);
    }
    
    protected function getAllTopics(): array {
        $query = 'SELECT d.id, d.title 
			FROM discussion d
			ORDER BY d.title ';
        $dbResult = mysqli_query($this->dbConnection, $query);
        $result = [];
        while ($row = mysqli_fetch_assoc($dbResult)) {
            $result[] = ['id' => $row['id'], 'title' => $row['title'] ];
        }
        return $result;
    }
    
    protected function fetchTopic(): void {
        $query = sprintf('SELECT short_description, discussion  
			FROM discussion d
			WHERE id = %d', TRIM(filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING)));
        $dbResult = mysqli_query($this->dbConnection, $query);
        $row = mysqli_fetch_assoc($dbResult);
        $result = [
            'shortdescription' => ($row ? $row['short_description'] : ''),
            'discussion' => ($row ? $row['discussion'] : '[]'),
        ];
        echo json_encode($result);
    }
    
    protected function setShortDescription(): void {
        $query = sprintf('UPDATE discussion SET short_description = "%s" WHERE id = %d',
                         filter_input(INPUT_POST, 'text', FILTER_SANITIZE_ADD_SLASHES),
                         filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT));
        mysqli_query($this->dbConnection, $query);
        echo '{"result":"success"}';
    }
    
    protected function setDiscussion(): void {
        $query = sprintf('UPDATE discussion SET discussion = "%s" WHERE id = %d',
                         filter_input(INPUT_POST, 'text', FILTER_SANITIZE_ADD_SLASHES),
                         filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT));
        mysqli_query($this->dbConnection, $query);
        echo '{"result":"success"}';
    }
}
