<?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';

if (!isset($_SESSION["user"])) {
    header("Location: index.php?pfad=login");
    exit();
}
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $_SESSION["old_title"]    = $_POST["title"] ?? '';
        $_SESSION["old_content"]  = $_POST["content"] ?? '';
        $_SESSION["old_category"] = $_POST["category"] ?? '';
        $_SESSION["old_tags"]     = $_POST["tags"] ?? '';

        if(!isset($_POST["title"]) ||!isset($_POST["content"]) || !isset($_POST["category"])){
            $_SESSION["message"] = "missing_parameters";
            header("location: ../../index.php?pfad=createArticle");
            exit();
        } else {
            $title = $_POST["title"];
            $content = $_POST["content"];
            $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);
            }

            // ----------------- Base64-Bilder verarbeiten und auf Server speichern -----------------
            $blocks = json_decode($content, true);
            $uploadDir = __DIR__ . '/../../uploads/';

            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            if (is_array($blocks)) {
                foreach ($blocks as &$block) {
                    // sicherstellen, dass 'type' und 'value' existieren:
                    if (isset($block['type']) && isset($block['value']) && $block['type'] === 'image' && str_starts_with($block['value'], 'data:image/')) {

                        // Base64-String zerlegen
                        $parts = explode(',', $block['value']);

                        // falls der String korrupt ist und kein Komma hat
                        if (count($parts) < 2) {
                            continue;
                        }

                        $metadata = $parts[0];
                        $base64Data = $parts[1];

                        // Dateiendung ermitteln
                        preg_match('/data:image\/(?<extension>.*?);/', $metadata, $matches);
                        $extension = $matches['extension'] ?? 'jpg';
                        if ($extension === 'jpeg') {
                            $extension = 'jpg';
                        }

                        // Eindeutigen Dateinamen generieren
                        $fileName = 'img_' . uniqid() . '.' . $extension;
                        $filePath = $uploadDir . $fileName;

                        // Datei im /uploads speichern:
                        if (file_put_contents($filePath, base64_decode($base64Data)) !== false) {
                            // temporären Base64-String durch den echten Pfad ersetzen
                            $block['value'] = 'uploads/' . $fileName;
                        } else {
                            $_SESSION["message"] = "image_upload_error";
                            header("location: ../../index.php?pfad=createArticle");
                            exit();
                        }
                    }
                }
                unset($block);
            }

            // Aktualisiertes Array wieder in JSON konvertieren
            $finalContent = json_encode($blocks, JSON_UNESCAPED_UNICODE);

            // ----------------- Übertragung der validierten Daten in ArticleManager: ---------------------------
            try {
                $articleManager = ArticleManager::getInstance();
                $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();
        }
    }
?>