<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../model/LocalArticleManager.php';
require_once '../model/ArticleManager.php';
require_once '../validator/article-validator.php';
require_once '../../includes/article-block-helper.php';

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

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

    $uploadDir = __DIR__ . '/../../uploads/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    // Formularzustand (Titel/Tags/Kategorie/Blöcke) immer sichern, damit er nach einem
    // Redirect (PRG-Pattern oder Validierungsfehler) wieder angezeigt werden kann.
    $_SESSION["old_title"]    = $_POST["title"] ?? '';
    $_SESSION["old_category"] = $_POST["category"] ?? '';
    $_SESSION["old_tags"]     = $_POST["tags"] ?? '';

    $blocks = rebuildBlocksFromPost($_POST['blocks'] ?? [], $_FILES['blocks'] ?? [], $uploadDir);
    $_SESSION["old_content"] = json_encode($blocks, JSON_UNESCAPED_UNICODE);

    // ---------------------------------------------------------------------
    // Zwischenspeichern
    // ---------------------------------------------------------------------
    if (isset($_POST['editor_action']) && $_POST['editor_action'] !== '') {
        $action = $_POST['editor_action'];

        if ($action === 'add_text') {
            $blocks[] = ['type' => 'text', 'value' => ''];
        } elseif ($action === 'add_image') {
            $blocks[] = ['type' => 'image', 'value' => ''];
        } elseif (str_starts_with($action, 'delete_block:')) {
            $deleteIndex = (int) substr($action, strlen('delete_block:'));
            unset($blocks[$deleteIndex]);
            $blocks = array_values($blocks);
        }

        $_SESSION["old_content"] = json_encode($blocks, JSON_UNESCAPED_UNICODE);
        header("location: ../../index.php?pfad=createArticle");
        exit();
    }

    // ---------------------------------------------------------------------
    // Echtes Veröffentlichen
    // ---------------------------------------------------------------------
    if (!isset($_POST["title"]) || !isset($_POST["category"])) {
        $_SESSION["message"] = "missing_parameters";
        header("location: ../../index.php?pfad=createArticle");
        exit();
    } else {
        $title    = $_POST["title"];
        $content  = json_encode($blocks, JSON_UNESCAPED_UNICODE);
        $author   = $_SESSION["user_email"];
        $category = $_POST["category"];
        $tags     = $_POST['tags'] ?? '';

        // -------------------------------- Validierung der Daten: -------------------------
        if (!articleTitleValidator($title)) {
            $_SESSION["message"] = "invalid_title";
            header("location: ../../index.php?pfad=createArticle");
            exit();
        }

        if (!articleContentValidator($content)) {
            $_SESSION["message"] = "invalid_content";
            header("location: ../../index.php?pfad=createArticle");
            exit();
        }

        if (!articleCategoryValidator($category)) {
            $_SESSION["message"] = "invalid_category";
            header("location: ../../index.php?pfad=createArticle");
            exit();
        }

        if (!articleTagValidator($tags)) {
            $_SESSION["message"] = "invalid_tags";
            header("location: ../../index.php?pfad=createArticle");
            exit();
        } else {
            $cleanedTags = [];
            $rawTags = explode(',', $tags);
            foreach ($rawTags as $rawTag) {
                // Leerzeichen am Anfang/Ende des einzelnen Tags entfernen:
                $tag = trim($rawTag);
                $cleanedTags[] = $tag;
            }
            // Duplikate entfernen:
            $cleanedTags = array_unique($cleanedTags);
            $cleanedTags = implode(',', $cleanedTags);
        }

        // ----------------- Übertragung der validierten Daten in ArticleManager: ---------------------------
        try {
            $articleManager = ArticleManager::getInstance();
            // $content enthält bereits die finalen "uploads/..."-Pfade (kein Base64 mehr),
            // da rebuildBlocksFromPost() Datei-Uploads sofort verarbeitet.
            $articleManager->addArticle($title, $content, $author, $category, $cleanedTags);

            // Formulardaten nach erfolgreichem Erstellen aus der Session löschen
            unset($_SESSION["old_title"], $_SESSION["old_content"], $_SESSION["old_category"], $_SESSION["old_tags"]);

        } catch (\Throwable $e) {
            $_SESSION["message"] = "internal_error";
            header("location: ../../index.php?pfad=createArticle");
            exit();
        }

        $_SESSION["message"] = "new_article";
        // Weiterleitung zur Homepage
        header("location: ../../index.php");
        exit();
    }
}
?>