<?php

namespace Blog\Model;

use PDOException;

class TicketModel extends Database {

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

    public function buyTicket($data) {
        $pdo = $this->linkDB();
        $sql = "INSERT INTO Ticket (userid, eventid, kaufdatum, gültigkeitsdatum)
                VALUES (:userid, :eventid, :kaufdatum, :gültigkeitsdatum);";
        $params = [
            ":userid" => $data['userid'],
            ":eventid" => $data['eventid'],
            ":kaufdatum" => $data['kaufdatum'],
            ":gültigkeitsdatum" => $data['gültigkeitsdatum']
        ];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
            return $pdo->lastInsertId();
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler beim Kauf des Tickets.", $e);
            die;
        }
    }

    public function hasTicket($userid, $eventid) {
        $pdo = $this->linkDB();
        $sql = "SELECT COUNT(*) as count FROM Ticket WHERE userid = :userid AND eventid = :eventid;";
        $params = [
            ":userid" => $userid,
            ":eventid" => $eventid
        ];
        try {
            $sth = $pdo->prepare($sql);
            $sth->execute($params);
            return $sth->fetch(\PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            new \Blog\Library\ErrorMsg("Fehler bei der Ticketprüfung.", $e);
            die;
        }
    }

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