<?php
// views/forum.php - Forum module (Marketing upsell & fully functional forum)
require_once __DIR__ . '/../auth.php';
require_login();

$user = current_user();
$forum_active = !empty(get_setting('forum_license', ''));
$errors = [];
$success_msg = '';

// Check activation via form direct trigger (simulates license insert)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'activate_forum_demo') {
    set_setting('forum_license', 'DEMO-FORUM-UNLOCKED-SixDev');
    header("Location: index.php?view=forum");
    exit;
}

// IF FORUM IS ACTIVE: Initialize categories if empty
if ($forum_active) {
    $cat_count = intval($pdo->query("SELECT COUNT(*) FROM forum_categories")->fetchColumn());
    if ($cat_count === 0) {
        try {
            $pdo->beginTransaction();
            $pdo->exec("INSERT INTO forum_categories (id, name, description) VALUES (1, '⚽ Allgemeiner Vereinstalk', 'Diskussionen rund um das Vereinsleben und allgemeine Themen.')");
            $pdo->exec("INSERT INTO forum_categories (id, name, description) VALUES (2, '📅 Turniere & Events', 'Planung von Sommerfesten, Meisterschaftsspielen und Turnieren.')");
            $pdo->exec("INSERT INTO forum_categories (id, name, description) VALUES (3, '🛒 Tausch- & Flohmarkt', 'Suche und biete gebrauchte Trikots, Schuhe oder Trainingsgeräte.')");
            $pdo->commit();
        } catch (PDOException $e) {
            $pdo->rollBack();
        }
    }
}

// Navigation variables for forum hierarchy
$category_id = intval($_GET['cat_id'] ?? 0);
$topic_id = intval($_GET['topic_id'] ?? 0);

// IF ACTIVE: Handle Topic Creation
if ($forum_active && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_topic') {
    $title = trim($_POST['title'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $cat_id = intval($_POST['cat_id'] ?? 0);

    if (empty($title) || empty($message) || $cat_id <= 0) {
        $errors[] = "Bitte Titel und Nachrichtentext eingeben.";
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            
            // Insert Topic
            $stmt = $pdo->prepare("INSERT INTO forum_topics (category_id, title, user_id) VALUES (:cat_id, :title, :uid)");
            $stmt->execute([
                ':cat_id' => $cat_id,
                ':title' => $title,
                ':uid' => $user['id']
            ]);
            $new_topic_id = $pdo->lastInsertId();

            // Insert initial Post
            $stmt = $pdo->prepare("INSERT INTO forum_posts (topic_id, user_id, message) VALUES (:topic_id, :uid, :msg)");
            $stmt->execute([
                ':topic_id' => $new_topic_id,
                ':uid' => $user['id'],
                ':msg' => $message
            ]);

            $pdo->commit();
            header("Location: index.php?view=forum&topic_id=" . $new_topic_id);
            exit;
        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = "Fehler beim Erstellen des Themas: " . $e->getMessage();
        }
    }
}

// IF ACTIVE: Handle Post Reply Creation
if ($forum_active && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_post') {
    $message = trim($_POST['message'] ?? '');
    $t_id = intval($_POST['topic_id'] ?? 0);

    if (empty($message) || $t_id <= 0) {
        $errors[] = "Bitte einen Text für die Antwort eingeben.";
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO forum_posts (topic_id, user_id, message) VALUES (:topic_id, :uid, :msg)");
            $stmt->execute([
                ':topic_id' => $t_id,
                ':uid' => $user['id'],
                ':msg' => $message
            ]);
            header("Location: index.php?view=forum&topic_id=" . $t_id);
            exit;
        } catch (PDOException $e) {
            $errors[] = "Fehler beim Senden der Antwort: " . $e->getMessage();
        }
    }
}

// IF ACTIVE: Handle delete operations (Admins or authors)
if ($forum_active && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_item') {
    $item_id = intval($_POST['item_id'] ?? 0);
    $type = $_POST['item_type'] ?? '';

    if ($item_id > 0) {
        if ($type === 'topic') {
            // Verify ownership or admin
            $stmt = $pdo->prepare("SELECT user_id, category_id FROM forum_topics WHERE id = :id");
            $stmt->execute([':id' => $item_id]);
            $item = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($item && ($item['user_id'] == $user['id'] || $user['role'] === 'admin')) {
                $stmt = $pdo->prepare("DELETE FROM forum_topics WHERE id = :id");
                $stmt->execute([':id' => $item_id]);
                header("Location: index.php?view=forum&cat_id=" . $item['category_id']);
                exit;
            }
        } elseif ($type === 'post') {
            $stmt = $pdo->prepare("SELECT user_id, topic_id FROM forum_posts WHERE id = :id");
            $stmt->execute([':id' => $item_id]);
            $item = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($item && ($item['user_id'] == $user['id'] || $user['role'] === 'admin')) {
                $stmt = $pdo->prepare("DELETE FROM forum_posts WHERE id = :id");
                $stmt->execute([':id' => $item_id]);
                header("Location: index.php?view=forum&topic_id=" . $item['topic_id']);
                exit;
            }
        }
    }
}
?>

<div style="margin-bottom: 24px;">
    <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary);">Vereinsforum</h1>
    <p style="color: var(--text-muted); font-size: 14px;">Gemeinschaftliches Diskussionsboard für alle Abteilungen</p>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?= htmlspecialchars($err) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!$forum_active): ?>
    <!-- 1. MARKETING / LOCKED UPSELL STATE -->
    <div class="card" style="border: 2px solid var(--primary); background: #f0fdf4; padding: 40px; text-align: center; max-width: 800px; margin: 0 auto;">
        <div style="display: inline-block; padding: 12px; background: rgba(16, 185, 129, 0.1); border-radius: 50%; color: var(--primary); font-size: 24px; margin-bottom: 15px;">💬</div>
        <h2 style="font-size: 24px; font-weight: 800; color: var(--secondary); margin-bottom: 10px;">Aktivieren Sie das Vereinsforum für Team Mania PRO!</h2>
        <p style="font-size: 15px; color: var(--text-muted); max-width: 650px; margin: 0 auto 25px; line-height: 1.5;">
            Das **Forum-Modul** fördert die Kommunikation in Ihrem Verein. Mitglieder können selbstständig Themen eröffnen, Ausrüstung verkaufen, Fragen an den Vorstand stellen oder Termine planen. Vollständig moderierbar durch Administratoren.
        </p>
        <div style="display: flex; justify-content: center; gap: 15px;">
            <a href="https://team-mania.de/pro/forum" target="_blank" class="btn btn-primary">Jetzt Forum erwerben</a>
            <form method="POST" action="">
                <input type="hidden" name="action" value="activate_forum_demo">
                <button type="submit" class="btn btn-secondary">Demo-Modul freischalten</button>
            </form>
        </div>
    </div>

<?php else: ?>
    <!-- 2. ACTIVE FORUM STATE -->
    
    <?php if ($topic_id > 0): 
        // View individual topic & posts
        $stmt = $pdo->prepare("SELECT t.*, u.first_name, u.last_name, c.name as category_name 
                               FROM forum_topics t 
                               JOIN forum_categories c ON t.category_id = c.id
                               JOIN users u ON t.user_id = u.id 
                               WHERE t.id = :id");
        $stmt->execute([':id' => $topic_id]);
        $topic = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($topic):
            $posts_stmt = $pdo->prepare("SELECT p.*, u.first_name, u.last_name, u.photo_path, u.role 
                                         FROM forum_posts p 
                                         JOIN users u ON p.user_id = u.id 
                                         WHERE p.topic_id = :tid 
                                         ORDER BY p.id ASC");
            $posts_stmt->execute([':tid' => $topic_id]);
            $posts = $posts_stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $roles_labels = [
                'admin' => 'Admin', 'vorstand' => 'Vorstand', 'kassenwart' => 'Kassenwart',
                'trainer' => 'Trainer', 'materialwart' => 'Wart', 'member' => 'Mitglied'
            ];
    ?>
            <!-- Forum Breadcrumbs -->
            <div style="margin-bottom: 20px;">
                <a href="index.php?view=forum" style="text-decoration: none; color: var(--primary); font-weight: 600;">Forum</a> &rarr; 
                <a href="index.php?view=forum&cat_id=<?= $topic['category_id'] ?>" style="text-decoration: none; color: var(--primary); font-weight: 600;"><?= htmlspecialchars($topic['category_name']) ?></a> &rarr;
                <span style="color: var(--text-muted);"><?= htmlspecialchars($topic['title']) ?></span>
            </div>

            <!-- Posts List -->
            <div style="display: flex; flex-direction: column; gap: 20px;">
                <?php foreach ($posts as $p): ?>
                    <div class="card tm-forum-post" style="display: grid; grid-template-columns: 160px 1fr; gap: 20px;">
                        <!-- Author Info -->
                        <div class="tm-forum-post-author" style="text-align: center; border-right: 1px solid var(--border-color); padding-right: 15px;">
                            <?php if (!empty($p['photo_path']) && file_exists(__DIR__ . '/../' . $p['photo_path'])): ?>
                                <img src="<?= htmlspecialchars($p['photo_path']) ?>" style="width: 64px; height: 64px; border-radius: 50%; object-fit: cover;" alt="Avatar">
                            <?php else: ?>
                                <div style="width: 64px; height: 64px; border-radius: 50%; background-color: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: bold; margin: 0 auto;">
                                    <?= strtoupper(substr($p['first_name'], 0, 1) . substr($p['last_name'], 0, 1)) ?>
                                </div>
                            <?php endif; ?>
                            <h4 style="font-size: 14px; font-weight: 700; margin-top: 10px; color: var(--secondary);"><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></h4>
                            <span style="font-size: 11px; padding: 2px 6px; background: #e2e8f0; border-radius: 4px; display: inline-block; margin-top: 5px; font-weight: 600; color: #475569;">
                                <?= $roles_labels[$p['role']] ?? 'Mitglied' ?>
                            </span>
                        </div>

                        <!-- Content Info -->
                        <div style="display: flex; flex-direction: column; justify-content: space-between;">
                            <div>
                                <div style="font-size: 11px; color: var(--text-muted); margin-bottom: 10px;">
                                    Verfasst am: <?= date('d.m.Y H:i', strtotime($p['created_at'])) ?>
                                </div>
                                <div style="font-size: 15px; color: var(--text-main); line-height: 1.5;">
                                    <?= $p['message'] ?>
                                </div>
                            </div>
                            
                            <!-- Delete button (Admin or author only) -->
                            <?php if ($p['user_id'] == $user['id'] || $user['role'] === 'admin'): ?>
                                <div style="text-align: right; margin-top: 15px;">
                                    <form method="POST" action="" onsubmit="return confirm('Möchten Sie diesen Beitrag löschen?')">
                                        <input type="hidden" name="action" value="delete_item">
                                        <input type="hidden" name="item_type" value="post">
                                        <input type="hidden" name="item_id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn btn-danger btn-sm" style="padding: 3px 8px; font-size: 11px;">Beitrag löschen</button>
                                    </form>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Answer Form -->
            <div class="card" style="margin-top: 30px;">
                <h3 class="card-title">✍️ Auf das Thema antworten</h3>
                <form id="reply_form" method="POST" action="" style="margin-top: 15px;">
                    <input type="hidden" name="action" value="create_post">
                    <input type="hidden" name="topic_id" value="<?= $topic_id ?>">

                    <div class="form-group">
                        <input type="hidden" id="forum_reply" name="message">
                        <div id="reply_editor" style="height: 150px; background: white; color: black; border-radius: 4px;"></div>
                    </div>

                    <button type="submit" class="btn btn-primary" style="margin-top: 10px;">Antwort absenden</button>
                </form>
            </div>

        <?php else: ?>
            <p>Das gesuchte Thema existiert nicht.</p>
        <?php endif; ?>

    <?php elseif ($category_id > 0): 
        // View specific category topics
        $stmt = $pdo->prepare("SELECT * FROM forum_categories WHERE id = :id");
        $stmt->execute([':id' => $category_id]);
        $cat = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($cat):
            $topics_stmt = $pdo->prepare("SELECT t.*, u.first_name, u.last_name, 
                                         (SELECT COUNT(*) FROM forum_posts WHERE topic_id = t.id) - 1 as replies 
                                         FROM forum_topics t 
                                         JOIN users u ON t.user_id = u.id 
                                         WHERE t.category_id = :cid 
                                         ORDER BY t.id DESC");
            $topics_stmt->execute([':cid' => $category_id]);
            $topics = $topics_stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>
            <!-- Forum Breadcrumbs -->
            <div style="margin-bottom: 20px;">
                <a href="index.php?view=forum" style="text-decoration: none; color: var(--primary); font-weight: 600;">Forum</a> &rarr; 
                <span style="color: var(--text-muted);"><?= htmlspecialchars($cat['name']) ?></span>
            </div>

            <div class="grid" style="grid-template-columns: 2fr 1fr; gap: 24px;">
                <!-- Topics list -->
                <div class="card">
                    <h3 class="card-title">💬 Themen in <?= htmlspecialchars($cat['name']) ?></h3>
                    
                    <div class="table-responsive" style="margin-top: 15px;">
                        <table>
                            <thead>
                                <tr>
                                    <th>Thema</th>
                                    <th>Ersteller</th>
                                    <th style="width: 100px; text-align: center;">Antworten</th>
                                    <?php if (has_role('admin')): ?><th style="width: 80px;">Aktionen</th><?php endif; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($topics)): ?>
                                    <?php foreach ($topics as $tp): ?>
                                        <tr>
                                            <td>
                                                <a href="index.php?view=forum&topic_id=<?= $tp['id'] ?>" style="font-weight: 600; color: var(--secondary); text-decoration: none;">
                                                    <?= htmlspecialchars($tp['title']) ?>
                                                </a>
                                            </td>
                                            <td><?= htmlspecialchars($tp['first_name'] . ' ' . $tp['last_name']) ?></td>
                                            <td style="text-align: center; font-weight: bold;"><?= intval($tp['replies']) ?></td>
                                            <?php if (has_role('admin') || $tp['user_id'] == $user['id']): ?>
                                                <td>
                                                    <form method="POST" action="" onsubmit="return confirm('Möchten Sie dieses Thema löschen?')">
                                                        <input type="hidden" name="action" value="delete_item">
                                                        <input type="hidden" name="item_type" value="topic">
                                                        <input type="hidden" name="item_id" value="<?= $tp['id'] ?>">
                                                        <button type="submit" class="btn btn-danger btn-sm" style="padding: 2px 6px; font-size: 10px;">Löschen</button>
                                                    </form>
                                                </td>
                                            <?php endif; ?>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="4" style="text-align: center; color: var(--text-muted); padding: 30px;">Keine Themen in dieser Kategorie vorhanden.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Create topic form -->
                <div class="card">
                    <h3 class="card-title">✍️ Neues Thema erstellen</h3>
                    
                    <form id="topic_form" method="POST" action="" style="margin-top: 15px;">
                        <input type="hidden" name="action" value="create_topic">
                        <input type="hidden" name="cat_id" value="<?= $category_id ?>">
                        
                        <div class="form-group">
                            <label for="t_title">Titel / Thema</label>
                            <input type="text" id="t_title" name="title" placeholder="Aussagekräftiger Titel" required>
                        </div>

                        <div class="form-group">
                            <label>Beitragstext</label>
                            <input type="hidden" id="t_msg" name="message">
                            <div id="topic_editor" style="height: 200px; background: white; color: black; border-radius: 4px;"></div>
                        </div>

                        <button type="submit" class="btn btn-primary" style="width: 100%;">Thema veröffentlichen</button>
                    </form>
                </div>
            </div>
        <?php endif; ?>

    <?php else: 
        // 3. Root Forum Categories List
        $categories = $pdo->query("SELECT * FROM forum_categories ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
    ?>
        <!-- Categories Overview -->
        <div class="card">
            <h3 class="card-title">📂 Forums-Kategorien</h3>
            <div style="display: flex; flex-direction: column; gap: 15px; margin-top: 15px;">
                <?php foreach ($categories as $cat): 
                    // Count topics in category
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM forum_topics WHERE category_id = :cid");
                    $stmt->execute([':cid' => $cat['id']]);
                    $t_count = intval($stmt->fetchColumn());
                ?>
                    <div style="padding: 20px; background-color: var(--bg-app); border: 1px solid var(--border-color); border-radius: var(--radius); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
                        <div>
                            <h4 style="font-size: 16px; font-weight: 700; color: var(--secondary);">
                                <a href="index.php?view=forum&cat_id=<?= $cat['id'] ?>" style="text-decoration: none; color: inherit; hover: { color: var(--primary); }">
                                    <?= htmlspecialchars($cat['name']) ?>
                                </a>
                            </h4>
                            <p style="font-size: 13px; color: var(--text-muted); margin-top: 4px;"><?= htmlspecialchars($cat['description']) ?></p>
                        </div>
                        <div style="text-align: right; min-width: 120px;">
                            <span style="font-size: 13px; font-weight: 600; color: var(--secondary);"><?= $t_count ?> Themen</span>
                            <a href="index.php?view=forum&cat_id=<?= $cat['id'] ?>" class="btn btn-secondary btn-sm" style="margin-top: 6px; display: block; text-align: center;">Öffnen</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

<?php endif; ?>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const toolbarOptions = [
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'font': [] }, { 'size': [] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'script': 'sub'}, { 'script': 'super' }],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'indent': '-1'}, { 'indent': '+1' }],
        [{ 'align': [] }],
        ['link', 'image', 'video', 'blockquote', 'code-block'],
        ['clean']
    ];

    if (document.getElementById('reply_editor')) {
        const replyQuill = new Quill('#reply_editor', {
            theme: 'snow',
            placeholder: 'Schreibe deine Antwort hier...',
            modules: { toolbar: toolbarOptions }
        });
        document.getElementById('reply_form').addEventListener('submit', function() {
            document.getElementById('forum_reply').value = replyQuill.root.innerHTML;
        });
    }

    if (document.getElementById('topic_editor')) {
        const topicQuill = new Quill('#topic_editor', {
            theme: 'snow',
            placeholder: 'Beschreibe dein Anliegen...',
            modules: { toolbar: toolbarOptions }
        });
        document.getElementById('topic_form').addEventListener('submit', function() {
            document.getElementById('t_msg').value = topicQuill.root.innerHTML;
        });
    }
});
</script>

