<?php

namespace Blog\Model;

use PDOException;

class NewsModel extends Database {

    public function getNewsById($newsId) {
        $pdo = $this->linkDB();
        $sql = "SELECT * FROM news WHERE newsid = :newsid;";
        $params = [":newsid" => $newsId];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
            return $sth->fetch(\PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Lesen der News.", $e);
            die;
        }
    }

    public function updateNews($newsId, $news) {
        $pdo = $this->linkDB();
        $sql = "UPDATE news SET name = :name, beschreibung = :beschreibung, datum = :datum WHERE newsid = :newsid;";
        $params = [
            ":name" => $news['titel'],
            ":beschreibung" => $news['inhalt'],
            ":datum" => $news['datum'],
            ":newsid" => $newsId
        ];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
            return $sth;
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Aktualisieren der News.", $e);
            die;
        }
    }

    public function getNews() {
        $pdo = $this->linkDB();
        $sql = "SELECT * FROM news ORDER BY datum DESC;";
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute();
            return $sth->fetchAll(\PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Lesen der News.", $e);
            die;
        }
    }

    public function createNews($news) {
        $pdo = $this->linkDB();
        $sql = "INSERT INTO news (name, beschreibung, datum) VALUES (:name, :beschreibung, :datum);";
        $params = [
            ":name" => $news['titel'],
            ":beschreibung" => $news['inhalt'],
            ":datum" => $news['datum']
        ];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
            return $sth;
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Schreiben der News.", $e);
            die;
        }
    }

    public function deleteNews($newsId) {
        $pdo = $this->linkDB();
        $sql = "DELETE FROM news WHERE newsid = :newsid;";
        $params = [":newsid" => $newsId];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Löschen der News.", $e);
            die;
        }
    }
}