<?php

namespace Blog\Model;

use PDOException;

class TicketModel extends Database {

    public function getTickets() {
        $pdo = $this->linkDB();
        $sql = "SELECT * FROM ticket ORDER BY ticket_id 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 (user_id, event_id, purchase_date, valid_until)
                VALUES (:user_id, :event_id, :purchase_date, :valid_until);";
        $params = [
            ":user_id" => $data['user_id'],
            ":event_id" => $data['event_id'],
            ":purchase_date" => $data['purchase_date'],
            ":valid_until" => $data['valid_until']
        ];
        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($user_id, $event_id) {
        $pdo = $this->linkDB();
        $sql = "SELECT COUNT(*) as count FROM ticket WHERE user_id = :user_id AND event_id = :event_id;";
        $params = [
            ":user_id" => $user_id,
            ":event_id" => $event_id
        ];
        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($ticket_id) {
        $pdo = $this->linkDB();
        $sql = "DELETE FROM ticket WHERE ticket_id = :ticket_id;";
        $params = [":ticket_id" => $ticket_id];
        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;
        }
    }
}