<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . "/../model/UserManager.php";
require_once __DIR__ . "/../model/ArticleManager.php";

if (!isset($_SESSION["user"])) {
    header("Location: index.php?pfad=login");
    exit();
}

/*
    Deregistrierung
    Funktion: Entfernt User aus der Datenbank und beendet die Session
*/

try {

    $dao = UserManager::getInstance();
    $articleManager = ArticleManager::getInstance();

    if (isset($_SESSION["user_email"])) {
        $dao->deleteUser($_SESSION["user_email"]);

        $articles = $articleManager->getArticlesByAuthor($_SESSION["user_email"]);
        foreach ($articles as $article) {
            $articleManager->deleteArticle($article->getId(), $_SESSION["user_email"]);
        }

    } else {
        throw new NotFoundException("missing_user_email");
    }

    $_SESSION = [];
    session_destroy();

    header("Location: ../../index.php");
    exit();

} catch (Exception $e) {

    $_SESSION["message"] = "internal_error";

    header("Location: ../../index.php?pfad=profile");
    exit();
}