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

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

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

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (isset($_SESSION["user_email"])) {
        $user = $_SESSION["user_email"];
    } else {
        $_SESSION = [];
        session_destroy();

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

    if (isset($_POST["id"]) && !empty($_POST["id"])) {
        $id = $_POST["id"];
    } else {
        $_SESSION["message"] = "missing_id";
        header("location: ../../index.php?pfad=profile");
        exit();
    }

    try {

        $articleManager = ArticleManager::getInstance();
        $articleManager->deleteArticle($id, $user);

    } catch (\Exception $e) {
        $_SESSION["message"] = $e->getMessage();
        header("location: ../../index.php?pfad=profile");
        exit();
    }

    $_SESSION["message"] = "article_deleted";
    header("location: ../../index.php?pfad=profile");
    exit();
}
