<?php
// views/vorstand.php - Board of directors dashboard
require_once __DIR__ . '/../auth.php';
require_role(['admin', 'vorstand']);

$user = current_user();
$errors = [];
$success_msg = '';

if (isset($_GET['success'])) {
    if ($_GET['success'] === 'protocol') $success_msg = 'Sitzungsprotokoll erfolgreich archiviert!';
    if ($_GET['success'] === 'poll') $success_msg = 'Umfrage erfolgreich gestartet!';
    if ($_GET['success'] === 'invite') $success_msg = 'Einladungslink erfolgreich generiert!';
    if ($_GET['success'] === 'delete') $success_msg = 'Eintrag erfolgreich gelöscht!';
}

// 1. Create Board Protocol
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_protocol') {
    $title = trim($_POST['title'] ?? '');
    $meeting_date = $_POST['meeting_date'] ?? date('Y-m-d');
    $content = trim($_POST['content'] ?? '');

    if (empty($title) || empty($content)) {
        $errors[] = "Bitte Titel und Protokoll-Inhalt eingeben.";
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO board_protocols (title, meeting_date, content, author_id) VALUES (:title, :meeting_date, :content, :author_id)");
            $stmt->execute([
                ':title' => $title,
                ':meeting_date' => $meeting_date,
                ':content' => $content,
                ':author_id' => $user['id']
            ]);
            header("Location: index.php?view=vorstand&success=protocol");
            exit;
        } catch (PDOException $e) {
            $errors[] = "Fehler beim Speichern des Protokolls: " . $e->getMessage();
        }
    }
}

// 2. Create Poll
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_poll') {
    $question = trim($_POST['question'] ?? '');
    $options_raw = $_POST['options'] ?? [];
    
    // Filter out empty options
    $options = [];
    foreach ($options_raw as $opt) {
        $opt = trim($opt);
        if (!empty($opt)) $options[] = $opt;
    }

    if (empty($question) || count($options) < 2) {
        $errors[] = "Die Umfrage muss eine Frage und mindestens zwei Antwortmöglichkeiten enthalten.";
    }

    if (empty($errors)) {
        try {
            $options_json = json_encode($options);
            $stmt = $pdo->prepare("INSERT INTO polls (question, options, is_active) VALUES (:question, :options, 1)");
            $stmt->execute([
                ':question' => $question,
                ':options' => $options_json
            ]);
            header("Location: index.php?view=vorstand&success=poll");
            exit;
        } catch (PDOException $e) {
            $errors[] = "Fehler beim Erstellen der Umfrage: " . $e->getMessage();
        }
    }
}

// 3. Create Chat Invite Link
$generated_invite = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_invite') {
    $room_id = intval($_POST['room_id'] ?? 0);
    
    if ($room_id > 0) {
        try {
            $token = bin2hex(random_bytes(12));
            $expires = date('Y-m-d H:i:s', strtotime('+7 days'));
            
            $stmt = $pdo->prepare("INSERT INTO chat_invites (room_id, token, created_by, expires_at) VALUES (:room_id, :token, :created_by, :expires)");
            $stmt->execute([
                ':room_id' => $room_id,
                ':token' => $token,
                ':created_by' => $user['id'],
                ':expires' => $expires
            ]);
            
            $_SESSION['last_invite_link'] = "index.php?view=chat&join=" . $token;
            header("Location: index.php?view=vorstand&success=invite");
            exit;
        } catch (PDOException $e) {
            $errors[] = "Fehler beim Erstellen des Einladungslinks: " . $e->getMessage();
        }
    } else {
        $errors[] = "Bitte wählen Sie einen gültigen Chatraum aus.";
    }
}

// 4. Handle Deletions (Protocol or Poll)
if ($_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 === 'protocol') {
            $stmt = $pdo->prepare("DELETE FROM board_protocols WHERE id = :id");
            $stmt->execute([':id' => $item_id]);
        } elseif ($type === 'poll') {
            $stmt = $pdo->prepare("DELETE FROM polls WHERE id = :id");
            $stmt->execute([':id' => $item_id]);
        }
        header("Location: index.php?view=vorstand&success=delete");
        exit;
    }
}

// Fetch all board protocols
$protocols_stmt = $pdo->query("SELECT p.*, u.first_name, u.last_name FROM board_protocols p LEFT JOIN users u ON p.author_id = u.id ORDER BY p.meeting_date DESC, p.id DESC");
$protocols = $protocols_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all polls
$polls_stmt = $pdo->query("SELECT * FROM polls ORDER BY id DESC");
$polls = $polls_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all chat rooms
$rooms_stmt = $pdo->query("SELECT * FROM chat_rooms ORDER BY name ASC");
$rooms = $rooms_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 10px;">
    <div>
        <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary);">Vorstands-Bereich</h1>
        <p style="color: var(--text-muted); font-size: 14px;">Sitzungsdokumente, Beschlussfassungen und Kommunikation für den Vorstand</p>
    </div>
    
    <div>
        <a href="index.php?view=pages&new=1" class="btn btn-primary btn-sm">📢 Neue News/Seite erstellen</a>
    </div>
</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 (!empty($success_msg)): ?>
    <div class="alert alert-success">
        <?= htmlspecialchars($success_msg) ?>
        <?php if (isset($_SESSION['last_invite_link'])): 
            $full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . '/' . $_SESSION['last_invite_link'];
        ?>
            <div style="margin-top: 10px; padding: 10px; background: #fff; border: 1px solid var(--border-color); border-radius: var(--radius); word-break: break-all;">
                <strong>Einladungslink (7 Tage gültig):</strong><br>
                <input type="text" value="<?= htmlspecialchars($full_url) ?>" style="margin-top: 5px; background: #f8fafc;" readonly onclick="this.select()">
            </div>
            <?php unset($_SESSION['last_invite_link']); ?>
        <?php endif; ?>
    </div>
<?php endif; ?>

<div class="grid">
    <!-- Protocols Column -->
    <div style="grid-column: span 2;">
        <!-- Protocols Archive -->
        <div class="card" style="margin-bottom: 24px;">
            <h3 class="card-title">📂 Sitzungsprotokolle (Archiv)</h3>
            <div class="table-responsive" style="margin-top: 15px;">
                <table>
                    <thead>
                        <tr>
                            <th>Datum</th>
                            <th>Thema / Protokoll</th>
                            <th>Protokollführer</th>
                            <th>Inhalt (Auszug)</th>
                            <th style="width: 80px;">Aktionen</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($protocols)): ?>
                            <?php foreach ($protocols as $p): ?>
                                <tr>
                                    <td style="font-weight: 600;"><?= date('d.m.Y', strtotime($p['meeting_date'])) ?></td>
                                    <td><strong><?= htmlspecialchars($p['title']) ?></strong></td>
                                    <td><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></td>
                                    <td style="color: var(--text-muted); font-size: 13px;">
                                        <?= htmlspecialchars(substr(strip_tags($p['content']), 0, 100)) ?>...
                                    </td>
                                    <td>
                                        <form method="POST" action="" onsubmit="return confirm('Möchten Sie dieses Protokoll unwiderruflich löschen?')">
                                            <input type="hidden" name="action" value="delete_item">
                                            <input type="hidden" name="item_type" value="protocol">
                                            <input type="hidden" name="item_id" value="<?= $p['id'] ?>">
                                            <button type="submit" class="btn btn-danger btn-sm">Löschen</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 30px;">Keine Protokolle hinterlegt.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Protocol Creator -->
        <div class="card">
            <h3 class="card-title">📝 Neues Sitzungsprotokoll verfassen</h3>
            <form id="protocol_form" method="POST" action="" style="margin-top: 15px;">
                <input type="hidden" name="action" value="create_protocol">
                
                <div class="grid" style="grid-template-columns: 2fr 1fr; gap: 15px; margin-bottom: 0;">
                    <div class="form-group">
                        <label for="p_title">Protokoll-Titel / Thema</label>
                        <input type="text" id="p_title" name="title" placeholder="z. B. Vorstandssitzung Q3-2026" required>
                    </div>
                    <div class="form-group">
                        <label for="meeting_date">Sitzungsdatum</label>
                        <input type="date" id="meeting_date" name="meeting_date" value="<?= date('Y-m-d') ?>" required>
                    </div>
                </div>

                <div class="form-group">
                    <label>Inhalt / Beschlüsse / Agenda</label>
                    <input type="hidden" id="p_content" name="content">
                    <div id="protocol_editor" style="height: 250px; background: white; color: black; border-radius: 4px;"></div>
                </div>

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

    <!-- Right Column: Polls & Chat Invites -->
    <div>
        <!-- Chat Inviter -->
        <div class="card" style="margin-bottom: 24px;">
            <h3 class="card-title">💬 Chat Einladungs-Generator</h3>
            <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 12px;">Erstellen Sie temporäre Einladungslinks für Mitglieder, um einem Chatraum beizutreten.</p>
            
            <form method="POST" action="">
                <input type="hidden" name="action" value="create_invite">
                
                <div class="form-group">
                    <label for="room_id">Chatraum auswählen</label>
                    <select id="room_id" name="room_id" required>
                        <option value="">-- Bitte Raum wählen --</option>
                        <?php foreach ($rooms as $r): ?>
                            <option value="<?= $r['id'] ?>"><?= htmlspecialchars($r['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <button type="submit" class="btn btn-secondary btn-sm" style="width: 100%;">Einladungslink generieren</button>
            </form>
        </div>

        <!-- Poll Creator -->
        <div class="card">
            <h3 class="card-title">🗳️ Umfrage / Abstimmung starten</h3>
            <form method="POST" action="" style="margin-top: 15px;">
                <input type="hidden" name="action" value="create_poll">
                
                <div class="form-group">
                    <label for="question">Frage / Beschlussantrag</label>
                    <input type="text" id="question" name="question" placeholder="z. B. Erhöhung der Mitgliedsbeiträge?" required>
                </div>

                <div class="form-group">
                    <label>Antwortoptionen (Optionen ausfüllen)</label>
                    <input type="text" name="options[]" placeholder="Option 1" style="margin-bottom: 8px;" required>
                    <input type="text" name="options[]" placeholder="Option 2" style="margin-bottom: 8px;" required>
                    <input type="text" name="options[]" placeholder="Option 3 (Optional)" style="margin-bottom: 8px;">
                    <input type="text" name="options[]" placeholder="Option 4 (Optional)">
                </div>

                <button type="submit" class="btn btn-primary btn-sm" style="width: 100%; margin-top: 10px;">Umfrage veröffentlichen</button>
            </form>

            <!-- Active Polls List -->
            <div style="margin-top: 30px; border-top: 1px solid var(--border-color); padding-top: 20px;">
                <h4 style="font-size: 14px; font-weight: 700; margin-bottom: 12px; color: var(--secondary);">Laufende Umfragen</h4>
                <?php if (!empty($polls)): ?>
                    <div style="display: flex; flex-direction: column; gap: 12px;">
                        <?php foreach ($polls as $pl): ?>
                            <div style="padding: 10px; background: #f8fafc; border: 1px solid var(--border-color); border-radius: var(--radius); display: flex; justify-content: space-between; align-items: center;">
                                <div style="font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 180px;">
                                    <?= htmlspecialchars($pl['question']) ?>
                                </div>
                                <form method="POST" action="" onsubmit="return confirm('Möchten Sie diese Umfrage löschen?')">
                                    <input type="hidden" name="action" value="delete_item">
                                    <input type="hidden" name="item_type" value="poll">
                                    <input type="hidden" name="item_id" value="<?= $pl['id'] ?>">
                                    <button type="submit" class="btn btn-danger btn-sm" style="padding: 3px 6px; font-size: 10px;">Löschen</button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p style="color: var(--text-muted); font-size: 12px; text-align: center;">Keine Umfragen erfasst.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    if (document.getElementById('protocol_editor')) {
        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']
        ];
        const protocolQuill = new Quill('#protocol_editor', {
            theme: 'snow',
            placeholder: 'Ergebnisse, Beschlüsse und Tagesordnungspunkte hier erfassen...',
            modules: { toolbar: toolbarOptions }
        });
        document.getElementById('protocol_form').addEventListener('submit', function() {
            document.getElementById('p_content').value = protocolQuill.root.innerHTML;
        });
    }
});
</script>


