<?php
include 'renderer.php';

class Projectsmanagement extends Renderer {
    protected array $formFields = [
        ['label' => 'Projekt', 'type' => 'dbselect', 'size' => 0, 'name' => 'shorttitle', 'combine_with_next_line' => true, 'filter' => FILTER_SANITIZE_NUMBER_INT, 'dbfield' => 'shorttitle',
            'sourcedb' => 'project', 'optionfield' => 'short_title', 'encryption' => false, 'with_null_field' => true],
        ['label' => '', 'type' => 'text', 'size' => 20, 'name' => 'new_title', 'combine_with_next_line' => true, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'shorttitle', 
            'optional' => true],
        ['label' => '', 'type' => 'button', 'size' => 0, 'name' => 'addproject', 'combine_with_next_line' => false, 'filter' => false, 'text' => 'Projekt hinzufügen'],
        ['label' => 'Kurze Beschreibung', 'type' => 'text', 'size' => 50, 'name' => 'description', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'description',
            'optionial' => true],
        ['label' => 'Projektart', 'type' => 'dbselect', 'size' => 0, 'name' => 'projecttype', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_NUMBER_INT, 'dbfield' => 'project_type_id',
            'sourcedb' => 'project_type', 'optionfield' => 'caption', 'encryption' => false, 'with_null_field' => false],
    ];
    protected bool $isAjaxForm = true;

    public function render(): void {
        $action = trim(filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING));
        if ($action != '') {
            switch ($action) {
                case 'create':
                    $this->createProject();
                    break;
                case 'getdetails':
                    $this->getDetails();
                    break;
                case 'setdescription':
                    $this->setDescription();
                    break;
                case 'setprojecttype':
                    $this->setProjectType();
                    break;
            }
            return;
        }
        parent::render();
    }
    
    protected function createProject(): void {
        $newName = trim(filter_input(INPUT_POST, 'newname', FILTER_SANITIZE_STRING));
        if ($newName == '') {
            echo '{"error": "Jedes Projekt benötigt einen Namen."}';
            return;
        }
        $query = sprintf('select id from project p where short_title = "%s"', $newName);
        $dbResult = mysqli_query($this->dbConnection, $query);
        if (mysqli_num_rows($dbResult) > 0) {
            echo '{"error": "Ein Projekt mit dem Namen existiert bereits."}';
            return;
        }
        $query = sprintf('INSERT INTO project (short_title, description, project_type_id)
            SELECT "%s", "", id 
            FROM project_type p
            WHERE caption = "Fortlaufende Projekte"', $newName);
        mysqli_query($this->dbConnection, $query);
        $id = mysqli_insert_id($this->dbConnection);
        $query = 'SELECT id, short_title, project_type_id FROM project p ORDER BY short_title';
        $dbResult = mysqli_query($this->dbConnection, $query);
        $list = [];
        while ($row = mysqli_fetch_assoc($dbResult)) {
            $list[] = ['id' => $row['id'], 'title' => $row['short_title'], 'project_type_id' => $row['project_type_id'] ];
        }
        echo json_encode(['list' => $list, 'id' => $id, 'types' => $this->getProjectTypes()]);
    }

    protected function setDescription(): void {
        $newDescription = trim(filter_input(INPUT_POST, 'description', FILTER_SANITIZE_ADD_SLASHES));
        $query = sprintf('UPDATE project SET description = "%s" WHERE id = "%d"', $newDescription, filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT));
        mysqli_query($this->dbConnection, $query);
        echo '{}';
    }
    
    protected function getDetails(): void {
        $query = sprintf('SELECT description, project_type_id  FROM project WHERE id = %d', filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT));
        $dbResult = mysqli_query($this->dbConnection, $query);
        if ($row = mysqli_fetch_assoc($dbResult)) {
            echo json_encode(['description' => $row['description'], 'projecttype' => $row['project_type_id']]);
        } else {
            echo json_encode(['description' => '', 'projecttype' => '1']);
        }
        
    }
    
    protected function setProjectType(): void {
        $newProjectType = trim(filter_input(INPUT_POST, 'newtype', FILTER_SANITIZE_NUMBER_INT));
        $query = sprintf('UPDATE project SET project_type_id = "%d" WHERE id = "%d"', $newProjectType, filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT));
        mysqli_query($this->dbConnection, $query);
        echo '{}';
    }
    
    protected function generateContent(): void {
        $types = $this->getProjectTypes();
        $query = 'SELECT * FROM project ORDER BY short_title';
        $result = mysqli_query($this->dbConnection, $query);
        $overviewHtml = '<table id="projectoverview"><thead><tr><th>Projekt</th><th>Projekttyp</th><tr><thead><tbody>';
        while ($row = mysqli_fetch_assoc($result)) {
            $overviewHtml .= '<tr><td>' . $row['short_title'] . '</td>';
            $overviewHtml .= '<td><select name="project_type" data="' . $row['id'] . '">';
            foreach ($types as $id => $type) {
                $overviewHtml .= '<option value="' . $id . '"' . ($id == $row['project_type_id'] ? ' selected' : '') . '>' . $type . '</option>';
            }
            $overviewHtml .= '</select></td>';
            $overviewHtml .= '</tr>';
        }
        $overviewHtml .= '</tbody></table>';
        $this->content['projects'] = $overviewHtml;
    }
    
    protected function getProjectTypes(): array {
        $typesQuery = 'SELECT * FROM project_type ORDER BY id';
        $typesResult = mysqli_query($this->dbConnection, $typesQuery);
        $types = [];
        while ($row = mysqli_fetch_assoc($typesResult)) {
            $types[$row['id'] ] = $row['caption'];
        }
        return $types;
    }
}
