Bib-Arts/Controller/NewsController.php

109 lines
3.5 KiB
PHP

<?php
namespace Blog\Controller;
use Blog\Model\NewsModel;
class NewsController {
private $model;
private $view;
public function __construct($view) {
$this->model = new NewsModel();
$this->view = $view;
}
public function showNews() {
$news = $this->model->getNews();
$this->view->setVars(['news' => $news]);
}
public function createNews() {
if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
header('Location: index.php?controller=News&do=showNews');
exit;
}
$data = [
'name' => $_POST['name'] ?? '',
'description' => $_POST['description'] ?? '',
'date' => $_POST['date'] ?? date('Y-m-d'),
];
$errors = [];
if (empty($data['name']) || empty($data['description']) || empty($data['date'])) {
$errors['news'] = 'Bitte alle Felder ausfüllen.';
}
if (!empty($errors)) {
$this->view->setVars(['errors' => $errors, 'validData' => $data]);
$this->view->setDoMethodName('createNewsForm');
return;
}
$this->model->createNews($data);
$this->view->setDoMethodName('showCreateSuccess');
}
public function createNewsForm() {
if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
header('Location: index.php?controller=News&do=showNews');
exit;
}
// Leere Felder für das Formular
$this->view->setVars([
'errors' => [],
'validData' => []
]);
}
public function editNewsForm() {
if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
header('Location: index.php?controller=News&do=showNews');
exit;
}
$id = $_GET['id'] ?? null;
if ($id) {
$news = $this->model->getNewsById($id);
$validData = [
'name' => $news['name'] ?? '',
'description' => $news['description'] ?? '',
'date' => $news['date'] ?? date('Y-m-d'),
];
$this->view->setVars(['validData' => $validData, 'id' => $id, 'errors' => []]);
}
}
public function updateNews() {
if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
header('Location: index.php?controller=News&do=showNews');
exit;
}
$id = $_POST['id'] ?? null;
$data = [
'name' => $_POST['name'] ?? '',
'description' => $_POST['description'] ?? '',
'date' => $_POST['date'] ?? date('Y-m-d'),
];
$errors = [];
if (empty($data['name']) || empty($data['description']) || empty($data['date'])) {
$errors['news'] = 'Bitte alle Felder ausfüllen.';
}
if (!empty($errors)) {
$this->view->setVars(['errors' => $errors, 'validData' => $data, 'id' => $id]);
$this->view->setDoMethodName('editNewsForm');
return;
}
$this->model->updateNews($id, $data);
$this->view->setDoMethodName('showEditSuccess');
}
public function deleteNews() {
if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
header('Location: index.php?controller=News&do=showNews');
exit;
}
$id = $_GET['id'] ?? null;
if ($id) {
$this->model->deleteNews($id);
}
$this->view->setDoMethodName('showDeleteSuccess');
}
}