<?php

namespace Blog\Controller;

use Blog\Model\GutscheinModel;

class GutscheinController {

    private $model;
    private $view;

    public function __construct($view) {
        $this->model = new GutscheinModel();
        $this->view = $view;
    }

    public function showGutscheine() {
        $gutscheine = $this->model->getGutscheine();
        $this->view->setVars(['gutscheine' => $gutscheine]);
    }

    public function createGutscheinForm() {
        if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
            header('Location: index.php');
            exit;
        }
        $this->view->setDoMethodName('createGutscheinForm');
    }

    public function createGutschein() {
        if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
            header('Location: index.php');
            exit;
        }
        $data = [
            'code' => $_POST['code'] ?? null,
            'discount' => $_POST['discount'] ?? null,
            'event_id' => $_POST['event_id'] ?? null,
            'valid_until' => $_POST['valid_until'] ?? null
        ];
        $this->model->createGutschein($data);
        $this->view->setDoMethodName('showCreateSuccess');
    }

    public function editGutscheinForm() {
        $id = $_GET['gutscheinid'];
        if ($id) {
            $gutschein = $this->model->getGutschein($id);
            $this->view->setVars(['gutschein' => $gutschein]);
        }
    }

    public function updateGutschein() {
        $id = $_POST['gutscheinid'];
        $data = [
            'code' => $_POST['code'] ?? null,
            'discount' => $_POST['discount'] ?? null,
            'event_id' => $_POST['event_id'] ?? null,
            'valid_until' => $_POST['valid_until'] ?? null
        ];
        $this->model->updateGutschein($id, $data);
        header('Location: index.php?controller=Gutschein&do=adminVerwaltung');
        exit;
    }

    public function deleteGutschein() {
        $id = $_GET['gutscheinid'] ?? null;
        $this->model->deleteGutschein($id);
        header('Location: index.php?controller=Gutschein&do=adminVerwaltung');
        exit;
    }

    public function adminVerwaltung() {
        if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
            header('Location: index.php');
            exit;
        }
        $gutscheine = $this->model->getGutscheine();
        $this->view->setVars(['gutscheine' => $gutscheine]);
        $this->view->setDoMethodName('showGutscheine');
    }
}