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

session_start();

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

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

$defaultValues = array();
$defaultValues['displayName'] = "";
$defaultValues['id'] = "";
$defaultValues['description'] = "";
$defaultValues['color'] = "#3b82f6";
$defaultValues['icon'] = "fa-book";

$errors = array();

if (isset($_GET['subject'])) {
    $editingSubject = $allSubjects[$_GET['subject']];

    $defaultValues['displayName'] = $editingSubject->getDisplayName();
    $defaultValues['id'] = $editingSubject->getId();
    $defaultValues['description'] = $editingSubject->getDescription();
    $defaultValues['color'] = $editingSubject->getColor();
    $defaultValues['icon'] = $editingSubject->getIcon();
}

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['description']) || trim($_POST['description']) == "") {
        $errors["description"] = "Bitte geben Sie eine Beschreibung an.";
    }

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

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

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

    if (empty($errors)) {
        $newSubject = false;
        if (isset($allSubjects[$_POST['id']])) {
            $newSubject = $allSubjects[$_POST['id']];
            $newSubject->setDisplayName($_POST['displayName']);
            $newSubject->setDescription($_POST['description']);
            $newSubject->setColor($_POST['color']);
            $newSubject->setIcon($_POST['icon']);
        } else {
            $newSubject = SubjectData::createNew($_POST['id'], $_POST['displayName'], $_POST['description'], $_POST['color'], $_POST['icon'], array());
        }

        if (!$newSubject) {
            $errors["error"] = "Fehler beim Speichern des Faches.";
        } else {
            if ($_POST['submit'] == "Fach löschen") {
                $newSubject->delete();
                header("Location: " . "index.php");
            } else {
                $newSubject->save();
                header("Location: " . "subject.php?subject=" . $newSubject->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/styles.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>
</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="subjectForm" method="post" onsubmit="handleSubjectSubmit(event)">
        <div class="space-y-6">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Name des Fachs</label>
                <input type="text"
                       name="displayName"
                       required
                       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="z.B. Mathematik"
                       value="<?php echo $defaultValues['displayName'] ?>">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">ID des Fachs</label>
                <input type="text"
                       name="id"
                       required
                       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="z.B. mathe"
                       value="<?php echo $defaultValues['id'] ?>">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Beschreibung</label>
                <textarea name="description"
                          required
                          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"
                          rows="4"
                          placeholder="Kurze Beschreibung des Fachs"><?php echo $defaultValues['description'] ?></textarea>
            </div>



            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Farbe</label>
                    <div class="flex items-center space-x-2 mb-2">
                        <input type="color" name="color" required
                               class="w-12 h-12 px-1 py-1 rounded-lg border-2 border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                               value="<?php echo $defaultValues['color'] ?>">
                        <button type="button" class="w-8 h-8 rounded-lg bg-blue-500 border-2 border-gray-300 hover:border-blue-500" onclick="setColor('#3b82f6')" title="Blau"></button>
                        <button type="button" class="w-8 h-8 rounded-lg bg-red-500 border-2 border-gray-300 hover:border-red-500" onclick="setColor('#ef4444')" title="Rot"></button>
                        <button type="button" class="w-8 h-8 rounded-lg bg-green-500 border-2 border-gray-300 hover:border-green-500" onclick="setColor('#10b981')" title="Grün"></button>
                        <button type="button" class="w-8 h-8 rounded-lg bg-yellow-500 border-2 border-gray-300 hover:border-yellow-500" onclick="setColor('#f59e0b')" title="Gelb"></button>
                        <button type="button" class="w-8 h-8 rounded-lg bg-purple-500 border-2 border-gray-300 hover:border-purple-500" onclick="setColor('#8b5cf6')" title="Lila"></button>
                        <button type="button" class="w-8 h-8 rounded-lg bg-pink-500 border-2 border-gray-300 hover:border-pink-500" onclick="setColor('#ec4899')" title="Pink"></button>
                    </div>
                </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-5 sm:grid-cols-8 md:grid-cols-6 lg:grid-cols-8 xl:grid-cols-10 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>

            <?php
            foreach ($errors as $error) {
                echo "<p class='text-red-800'>$error</p>";
            }
            ?>

        </div>

        <div class="flow-root mt-8 gap-4">
            <?php if (isset($editingSubject)) { ?>
                <input type="submit" value="Fach 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>
    </form>
</div>


<script>
    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 setColor(color) {
        document.querySelector('input[name="color"]').value = color;
    }
</script>

</body>
</html>
