<?php

namespace Blog\Model;

use PDOException;

class GutscheinModel extends Database {

    public function getGutscheine() {
        $pdo = $this->linkDB();
        $sql = "SELECT * FROM voucher ORDER BY valid_until 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 Gutscheine.", $e);
            die;
        }
    }

    public function getGutschein($id) {
        $pdo = $this->linkDB();
        $sql = "SELECT * FROM voucher WHERE voucher_id = :id;";
        $params = [":id" => $id];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
            return $sth->fetch(\PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Lesen des Gutscheins.", $e);
            die;
        }
    }

    public function createGutschein($data) {
        $pdo = $this->linkDB();
        $sql = "INSERT INTO voucher (code, discount, event_id, valid_until) VALUES (:code, :discount, :event_id, :valid_until);";
        $params = [
            ":code" => $data['code'],
            ":discount" => $data['discount'],
            ":event_id" => $data['event_id'],
            ":valid_until" => $data['valid_until']
        ];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
            return $sth;
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Erstellen des Gutscheins.", $e);
            die;
        }
    }

    public function updateGutschein($id, $data) {
        $pdo = $this->linkDB();
        $sql = "UPDATE voucher SET code = :code, discount = :discount, event_id = :event_id, valid_until = :valid_until WHERE voucher_id = :id;";
        $params = [
            ":code" => $data['code'],
            ":discount" => $data['discount'],
            ":event_id" => $data['event_id'],
            ":valid_until" => $data['valid_until'],
            ":id" => $id
        ];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Aktualisieren des Gutscheins.", $e);
            die;
        }
    }

    public function deleteGutschein($id) {
        $pdo = $this->linkDB();
        $sql = "DELETE FROM voucher WHERE voucher_id = :id;";
        $params = [":id" => $id];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Löschen des Gutscheins.", $e);
            die;
        }
    }
}