<?php

require_once("classes/User.php");
require_once("classes/SubjectData.php");
require_once("classes/TopicData.php");
require_once("classes/Task.php");

session_start();

if (!isset($_SESSION['user']) || !$_SESSION['user']->isLoggedIn()) {
    header("Location: index.php");
    die();
}

$allSubjects = SubjectData::getAll();
$editingTopic = null;

$defaultValues = array();
$defaultValues['displayName'] = "";
$defaultValues['id'] = "";
$defaultValues['subjectId'] = "";
$defaultValues['description'] = "";
$defaultValues['icon'] = "fa-book";
$defaultValues['relatedTopics'] = "";
$defaultValues['existing_files'] = "";
$defaultValues['formulas'] = "";
$defaultValues['article'] = "";

$errors = array();

if (isset($_GET['subject']) && isset($_GET['topic'])) {
    if (isset($allSubjects[$_GET['subject']]->getTopics()[$_GET['topic']])) {
        $editingTopic = $allSubjects[$_GET['subject']]->getTopics()[$_GET['topic']];

        $defaultValues['displayName'] = $editingTopic->getDisplayName();
        $defaultValues['id'] = $editingTopic->getId();
        $defaultValues['subjectId'] = $editingTopic->getSubjectId();
        $defaultValues['description'] = $editingTopic->getDescription();
        $defaultValues['icon'] = $editingTopic->getIcon();
        $defaultValues['relatedTopics'] = implode(", ", $editingTopic->getRelatedTopics());
        $defaultValues['existing_files'] = implode(", ", $editingTopic->getFiles());

        $tasks = array();
        foreach($editingTopic->getTasks() as $task) {
            $variables = array();
            foreach($task->getVariables() as $name => $variable) {
                $variables[] = $name . "::" . $variable;
            }

            $tasks[] = $task->getText() . ";;" . implode(";;", $variables);
        }
        $defaultValues['formulas'] = implode(";;;;", $tasks);
        $defaultValues['article'] = $editingTopic->getFinishedArticle();
    }
} else if (isset($_GET['subject'])) {
    $defaultValues['subjectId'] = $_GET['subject'];
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    foreach ($defaultValues as $key => $value) {
        $defaultValues[$key] = $_POST[$key];
    }

    if (!isset($_POST['displayName']) || trim($_POST['displayName']) == "") {
        $errors["displayName"] = "Bitte geben Sie einen Namen an.";
    }

    if (!isset($_POST['id']) || trim($_POST['id']) == "") {
        $errors["id"] = "Bitte geben Sie eine ID an.";
    }

    if (!isset($_POST['subjectId']) || trim($_POST['subjectId']) == "") {
        $errors["subjectId"] = "Bitte geben Sie ein Fach an.";
    }

    if (!isset($_POST['description']) || trim($_POST['description']) == "") {
        $errors["description"] = "Bitte geben Sie eine Beschreibung an.";
    }

    if (!isset($_POST['icon']) || trim($_POST['icon']) == "") {
        $errors["icon"] = "Bitte geben Sie ein Icon an.";
    }

    if (!isset($_POST['relatedTopics'])) {
        $errors["relatedTopics"] = "Feld relatedTopics nicht mitgesendet!";
    }

    if (!isset($_POST['existing_files'])) {
        $errors["existing_files"] = "Feld existing_files nicht mitgesendet!";
    }

    if (!isset($_POST['formulas'])) {
        $errors["formulas"] = "Feld formulas nicht mitgesendet!";
    }

    if (!isset($_POST['article']) || trim($_POST['article']) == "") {
        $errors["article"] = "Bitte geben Sie einen Erklärtext an.";
    }

    if (!isset($_POST['submit']) || !($_POST['submit'] == "Speichern" || $_POST['submit'] == "Thema löschen")) {
        $errors["submit"] = "Ungültig abgeschickt!";
    }

    if (empty($errors)) {
        $newTopic = false;

        $relatedTopics = array();
        foreach (explode(",", $_POST['relatedTopics']) as $relatedTopic) {
            $relatedTopic = trim($relatedTopic);
            if ($relatedTopic == "") {
                continue;
            }
            $relatedTopics[] = $relatedTopic;
        }

        $existingFiles = array();
        foreach (explode(",", $_POST['existing_files']) as $existingTopic) {
            $existingTopic = trim($existingTopic);
            if ($existingTopic == "") {
                continue;
            }
            $existingFiles[] = trim($existingTopic);
        }

        $formulas = array();
        foreach (explode(";;;;", $_POST['formulas']) as $formulaString) {
            $text = false;
            $answers = array();
            foreach (explode(";;", $formulaString) as $formulaEntry) {
                if(!$text) {
                    $text = trim($formulaEntry);
                    continue;
                }

                $answer = explode("::", $formulaEntry);
                if(count($answer) != 2) {
                    $errors['formulas'] = "Jede Formel muss einen Text und mindestens eine Antwortmöglichkeit haben!";
                    break;
                }

                $answers[trim($answer[0])] = trim($answer[1]);
            }

            if(!$text) {
                $errors['formulas'] = "Jede Formel muss einen Text haben!";
                break;
            }

            if(count($answers) == 0) {
                $errors['formulas'] = "Jede Formel muss mindestens eine Antwortmöglichkeit haben!";
                break;
            }

            $formulas[] = new Task($text, $answers);
        }

        $article = htmlentities($_POST['article'], ENT_HTML401, 'UTF-8');
        $dom = new DOMDocument();
        $dom->encoding = 'UTF-8';
        $dom->loadHTML($article, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
        $htmlImages = $dom->getElementsByTagName('img');
        $newImages = array();
        foreach ($htmlImages as $htmlImage) {
            $src = $htmlImage->getAttribute('src');
            if (str_starts_with($src, "data:image")) {
                $image = file_get_contents($src);
                if (!$image) {
                    continue;
                }

                $image_format = false;
                if (str_starts_with($src, 'data:image/jpeg;')) {
                    $image_format = "jpg";
                } else if (str_starts_with($src, 'data:image/png;')) {
                    $image_format = "png";
                }

                if (!$image_format) {
                    continue;
                }
                $imagename = uniqid("image_", true) . ".$image_format";
                $newImages[$imagename] = $image;
            } else {
                $imagePath = explode("/", $src);
                $imagename = end($imagePath);
            }
            $htmlImage->setAttribute("src", '__TOPICPATH__/' . $imagename);
        }

        // extension=mbstring in php.ini muss aktiviert sein!
        $article = mb_convert_encoding($dom->saveHTML(), 'UTF-8', 'HTML-ENTITIES');
        $article = preg_replace("/^[ \r\n\t]*<p><p>/", "<p>", $article);
        $article = preg_replace("#</p></p>[ \r\n\t]*$#", "</p>", $article);

        if (isset($allSubjects[$_POST['subjectId']]->getTopics()[$_POST['id']])) {
            $newTopic = $allSubjects[$_POST['subjectId']]->getTopics()[$_POST['id']];

            $newTopic->setDisplayName($_POST['displayName']);
            $newTopic->setSubjectId($_POST['subjectId']);
            $newTopic->setDescription($_POST['description']);
            $newTopic->setIcon($_POST['icon']);
            $newTopic->setRelatedTopics($relatedTopics);
            foreach ($newTopic->getFiles() as $file) {
                if (!in_array($file, $existingFiles)) {
                    $newTopic->deleteDownload($file);
                }
            }
            $newTopic->setArticle($article);
            $newTopic->removeAllTasks();
        } else {
            $newTopic = TopicData::createNew($_POST['id'], $_POST['subjectId'], $_POST['displayName'], $_POST['icon'], $_POST['description'], $relatedTopics, $article);
        }

        if (!$newTopic) {
            $errors["error"] = "Fehler beim Speichern des Themas.";
        } else {
            for ($i = 0; $i < count($_FILES['new_files']['name']); $i++) {
                !$newTopic->addDownload($_FILES['new_files']['name'][$i], $_FILES['new_files']['tmp_name'][$i]);
            }

            foreach ($newImages as $name => $image) {
                $newTopic->uploadImage($name, $image);
            }

            foreach ($formulas as $formula) {
                $newTopic->addTask($formula);
            }

            if ($_POST['submit'] == "Thema löschen") {
                $newTopic->delete();
                header("Location: " . "subject.php?subject=" . $_POST['subjectId']);
            } else {
                $newTopic->save();
                header("Location: " . "topic.php?subject=" . $newTopic->getSubjectId() . "&topic=" . $newTopic->getId());
            }

        }
    }

}

?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Lehrer Dashboard</title>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/css/topic.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet"/>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="assets/js/quill_mod.js"></script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.19/dist/katex.min.css"
          integrity="sha384-7lU0muIg/i1plk7MgygDUp3/bNRA65orrBub4/OSWHECgwEsY83HaS1x3bljA/XV" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/katex@0.16.19/dist/katex.min.js"
            integrity="sha384-RdymN7NRJ+XoyeRY4185zXaxq9QWOOx3O7beyyrRK4KQZrPlCDQQpCu95FoCGPAE"
            crossorigin="anonymous"></script>
    <script src="assets/js/katex_autorender_mod.js"></script>
</head>

<body class="min-h-screen bg-gray-50">

<?php include 'header.php'; ?>

<div class="content mt-24 max-w-7xl mx-[16px] xl:mx-auto">

    <form id="topicForm" method="post" enctype="multipart/form-data" class="space-y-8">
        <div class="grid grid-cols-1 xl:grid-cols-2 gap-8">
            <!-- Left column - Topic details -->
            <div class="space-y-6">
                <div>
                    <label for="topicNameSelect" class="block text-sm font-medium text-gray-700 mb-2">Themenname</label>
                    <input id="topicNameSelect" type="text" name="displayName"
                           class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg enabled:hover:border-gray-400"
                           required
                           value="<?php echo $defaultValues['displayName']; ?>">
                </div>

                <div>
                    <label for="topicIdSelect" class="block text-sm font-medium text-gray-700 mb-2">ID</label>
                    <input id="topicIdSelect" type="text" name="id"
                           class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg enabled:hover:border-gray-400"
                           required
                           value="<?php echo $defaultValues['id']; ?>">
                </div>

                <div>
                    <label for="topicSubjectSelect" class="block text-sm font-medium text-gray-700 mb-2">Fach</label>
                    <div class="relative">
                        <select id="topicSubjectSelect" name="subjectId"
                                class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg enabled:hover:border-gray-400 appearance-none bg-white">
                            <?php
                            foreach ($allSubjects as $subject) {
                                $selected = "";
                                if ($defaultValues['subjectId'] === $subject->getId()) {
                                    $selected = "selected";
                                }

                                echo "<option $selected value='" . $subject->getId() . "'>" . $subject->getDisplayName() . "</option>";
                            }
                            ?>
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                            <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                                <path d="M7 10l5 5 5-5H7z"/>
                            </svg>
                        </div>
                    </div>
                </div>

                <div>
                    <label for="topicDescriptionSelect" class="block text-sm font-medium text-gray-700 mb-2">Kurzbeschreibung</label>
                    <textarea id="topicDescriptionSelect" name="description" rows="5"
                              class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg enabled:hover:border-gray-400"
                              required><?php echo $defaultValues['description']; ?></textarea>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Icon</label>
                    <div class="mt-2 h-[180px] overflow-y-auto grid grid-cols-8 gap-2 p-1">
                        <?php
                        $icons = [
                            "fa-book", "fa-calculator", "fa-flask", "fa-atom", "fa-globe-europe", "fa-palette",
                            "fa-music", "fa-dumbbell", "fa-language", "fa-microscope", "fa-keyboard", "fa-dna",
                            "fa-brain", "fa-history", "fa-chart-line", "fa-draw-polygon", "fa-running", "fa-theater-masks",
                            "fa-chart-pie", "fa-plus-minus", "fa-clock", "fa-code", "fa-divide", "fa-x", "fa-sitemap",
                            "fa-map-pin", "fa-feather-pointed", "fa-person", "fa-link", "fa-4"
                        ];
                        foreach ($icons as $icon) {
                            $selectedClass = $defaultValues['icon'] === $icon ? 'bg-blue-50 ring-2 ring-blue-500' : '';
                            echo "<div class='icon-option flex justify-center items-center w-12 h-12 p-2 border rounded-lg cursor-pointer $selectedClass' data-icon='$icon' onclick='selectIcon(this)'><i class='fas $icon'></i></div>";
                        }
                        ?>
                    </div>
                    <input type="hidden" id="selectedIcon" name="icon" value="<?php echo $defaultValues['icon']; ?>">
                </div>
                <div>
                    <label for="relatedTopicSelect" class="block text-sm font-medium text-gray-700 mb-2">Verwandte Themen (IDs, kommagetrennt)</label>
                    <input type="text"
                           name="relatedTopics"
                           id="relatedTopicSelect"
                           class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg enabled:hover:border-gray-400"
                           value="<?php echo $defaultValues['relatedTopics']; ?>">
                </div>

                <div>
                    <label for="existing_files" class="block text-sm font-medium text-gray-700 mb-2">Existierende Übungsblätter</label>
                    <input type="text"
                           name="existing_files"
                           id="existing_files"
                           class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg enabled:hover:border-gray-400"
                           value="<?php echo $defaultValues['existing_files']; ?>">
                </div>

                <div>
                    <label for="new_files" class="block text-sm font-medium text-gray-700 mb-2">
                        Übungsblätter hinzufügen
                    </label>
                    <div class="relative border border-gray-300 rounded-lg p-2 bg-white shadow-sm">
                        <input type="file" name="new_files[]" id="new_files" multiple
                               class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
                        <div class="flex items-center justify-center h-full text-gray-500">
                            <i class="fas fa-upload mr-2"></i>
                            <span>Dateien hier ablegen oder klicken, um Dateien auszuwählen</span>
                        </div>
                    </div>
                </div>

                <div>
                    <label for="formulas" class="block text-sm font-medium text-gray-700 mb-2">Aufgaben</label>
                    <input type="text"
                           name="formulas"
                           id="formulas"
                           class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg enabled:hover:border-gray-400"
                           placeholder="Format: aufgabentext1;;a::2,5;;b::3;;;;aufgabentext2;;a::1"
                           value="<?php echo $defaultValues['formulas']; ?>">
                </div>

            </div>

            <!-- Right column - Editor -->
            <div>
                <div class="mb-6">
                    <div class="flex justify-between items-center mb-2">
                        <label class="block text-sm font-medium text-gray-700">Erklärtext</label>
                        <div class="flex gap-2">
                            <button type="button" onclick="undo()"
                                    class="text-gray-500 hover:text-gray-700 p-1">
                                <i class="fas fa-undo"></i>
                            </button>
                            <button type="button" onclick="redo()"
                                    class="text-gray-500 hover:text-gray-700 p-1">
                                <i class="fas fa-redo"></i>
                            </button>
                        </div>
                    </div>

                    <div id="quillEditor" style="height: 600px;" class="bg-white border rounded-lg"><?php
                        $article = $defaultValues['article'];

                        echo $article;

                        ?></div>
                </div>
            </div>
        </div>

        <div class="flow-root gap-4">
            <?php if (isset($editingTopic)) { ?>
                <input type="submit" value="Thema löschen" name="submit"
                       class="float-left px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-gray-200">
            <?php } ?>
            <input type="submit" value="Speichern" name="submit"
                   class="float-right px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
            <input type="button" value="Abbrechen" onclick="history.back()"
                   class="float-right mx-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200">
        </div>

        <input type="hidden" name="article" id="article-upload-field">
    </form>
</div>
<script>
    function renderFormulas() {
        renderMathInElement(document.body, {
            delimiters: [
                {left: "$$", right: "$$", display: true},
                {left: "\\(", right: "\\)", display: false},
                {left: "\\begin{equation}", right: "\\end{equation}", display: true},
                {left: "\\begin{array}", right: "\\end{array}", display: true},
                {left: "\\begin{align}", right: "\\end{align}", display: true},
                {left: "\\begin{alignat}", right: "\\end{alignat}", display: true},
                {left: "\\begin{gather}", right: "\\end{gather}", display: true},
                {left: "\\begin{CD}", right: "\\end{CD}", display: true},
                {left: "\\[", right: "\\]", display: true}
            ],
            throwOnError : false
        });
    }

    renderFormulas();

    const quill = new Quill('#quillEditor', {
        modules: {
            toolbar: [
                [{'size': []}],
                ['bold', 'italic', 'underline', 'strike'],
                [{'script': 'super'}, {'script': 'sub'}],
                [{'list': 'ordered'}, {'list': 'bullet'}],
                ['link', 'image', 'formula'],
            ]
        },
        theme: 'snow'
    });

    quill.on('text-change', (delta, oldDelta, source) => {
        let html = quill.getSemanticHTML().replace(/&nbsp;/g, " ");
        html = html.replaceAll("<p></p>", "<br>");

        while (html.startsWith("<br>")) {
            html = html.replace(/^<br>/g, "");
        }

        while (html.endsWith("<br>")) {
            html = html.replace(/<br>$/g, "");
        }

        document.getElementById('article-upload-field').value = html;
    });
    quill.emitter.emit('text-change');

    function undo() {
        quill.history.undo();
    }

    function redo() {
        quill.history.redo();
    }

    function selectIcon(element) {
        // Remove active class from all icons
        document.querySelectorAll('.icon-option').forEach(el => {
            el.classList.remove('bg-blue-50', 'ring-2', 'ring-blue-500');
        });

        // Add active class to selected icon
        element.classList.add('bg-blue-50', 'ring-2', 'ring-blue-500');

        // Set the hidden input value
        const iconInput = document.getElementById('selectedIcon');
        iconInput.value = element.getAttribute('data-icon');
    }

    function selectIcon(element) {
        // Remove active class from all icons
        document.querySelectorAll('.icon-option').forEach(el => {
            el.classList.remove('bg-blue-50', 'ring-2', 'ring-blue-500');
        });

        // Add active class to selected icon
        element.classList.add('bg-blue-50', 'ring-2', 'ring-blue-500');

        // Set the hidden input value
        const iconInput = document.getElementById('selectedIcon');
        iconInput.value = element.getAttribute('data-icon');
    }

</script>

</body>
</html>
