<?php
// views/pages.php - Custom Page CMS renderer and editor
require_once __DIR__ . '/../auth.php';

$user = current_user();
$slug = $_GET['slug'] ?? '';
$page = null;
$editor_mode = isset($_GET['edit']) && can_edit_pages();
$create_mode = isset($_GET['new']) && can_edit_pages();

$errors = [];
$success_msg = '';

// 1. Fetch current page if slug is specified
if (!empty($slug) && !$create_mode) {
    $stmt = $pdo->prepare("SELECT * FROM pages WHERE slug = :slug");
    $stmt->execute([':slug' => $slug]);
    $page = $stmt->fetch(PDO::FETCH_ASSOC);
}

// 2. Handle Page Save (Insert or Update)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && can_edit_pages() && isset($_POST['action']) && $_POST['action'] === 'save_page') {
    $page_id = intval($_POST['page_id'] ?? 0);
    $page_title = trim($_POST['title'] ?? '');
    $page_slug = preg_replace('/[^a-z0-9\-]/', '', strtolower(trim($_POST['slug'] ?? '')));
    $page_content = trim($_POST['content'] ?? '');
    
    if (empty($page_title) || empty($page_slug) || empty($page_content)) {
        $errors[] = "Titel, URL-Slug und Inhalt dürfen nicht leer sein.";
    }

    // Check slug uniqueness
    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM pages WHERE slug = :slug AND id != :id");
        $stmt->execute([':slug' => $page_slug, ':id' => $page_id]);
        if ($stmt->fetchColumn() > 0) {
            $errors[] = "Dieser URL-Slug wird bereits für eine andere Seite verwendet.";
        }
    }

    // Upload Image Handling
    $image_path = $_POST['existing_image'] ?? '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $img_name = $_FILES['image']['name'];
        $img_tmp = $_FILES['image']['tmp_name'];
        $img_ext = strtolower(pathinfo($img_name, PATHINFO_EXTENSION));
        
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($img_ext, $allowed)) {
            // Delete old
            if (!empty($image_path) && file_exists(__DIR__ . '/../' . $image_path)) {
                @unlink(__DIR__ . '/../' . $image_path);
            }
            $new_img_name = 'page_img_' . time() . '.' . $img_ext;
            if (move_uploaded_file($img_tmp, __DIR__ . '/../uploads/' . $new_img_name)) {
                $image_path = 'uploads/' . $new_img_name;
            }
        } else {
            $errors[] = "Ungültiges Bildformat. Erlaubt sind JPG, PNG, GIF.";
        }
    }

    // Upload File Attachment Handling
    $file_path = $_POST['existing_file'] ?? '';
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $f_name = $_FILES['file']['name'];
        $f_tmp = $_FILES['file']['tmp_name'];
        $f_ext = strtolower(pathinfo($f_name, PATHINFO_EXTENSION));
        
        // Allow general non-executable attachments
        $forbidden = ['php', 'php3', 'php4', 'php5', 'phtml', 'exe', 'bat', 'cmd', 'sh'];
        if (!in_array($f_ext, $forbidden)) {
            // Delete old
            if (!empty($file_path) && file_exists(__DIR__ . '/../' . $file_path)) {
                @unlink(__DIR__ . '/../' . $file_path);
            }
            $new_file_name = 'page_file_' . time() . '.' . $f_ext;
            if (move_uploaded_file($f_tmp, __DIR__ . '/../uploads/' . $new_file_name)) {
                $file_path = 'uploads/' . $new_file_name;
            }
        } else {
            $errors[] = "Dieser Dateityp ist aus Sicherheitsgründen nicht erlaubt.";
        }
    }

    // Execute save
    if (empty($errors)) {
        try {
            if ($page_id > 0) {
                // Update
                $stmt = $pdo->prepare("UPDATE pages SET title = :title, slug = :slug, content = :content, image_path = :image_path, file_path = :file_path, updated_by = :user_id, updated_at = CURRENT_TIMESTAMP WHERE id = :id");
                $stmt->execute([
                    ':title' => $page_title,
                    ':slug' => $page_slug,
                    ':content' => $page_content,
                    ':image_path' => $image_path,
                    ':file_path' => $file_path,
                    ':user_id' => $user['id'],
                    ':id' => $page_id
                ]);
            } else {
                // Insert
                $stmt = $pdo->prepare("INSERT INTO pages (title, slug, content, image_path, file_path, updated_by) VALUES (:title, :slug, :content, :image_path, :file_path, :user_id)");
                $stmt->execute([
                    ':title' => $page_title,
                    ':slug' => $page_slug,
                    ':content' => $page_content,
                    ':image_path' => $image_path,
                    ':file_path' => $file_path,
                    ':user_id' => $user['id']
                ]);
            }
            
            // Redirect to view the page
            header("Location: index.php?view=pages&slug=" . urlencode($page_slug) . "&success=1");
            exit;
        } catch (PDOException $e) {
            $errors[] = "Fehler beim Speichern der Seite: " . $e->getMessage();
        }
    }
}

// 3. Handle Page Deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && can_edit_pages() && isset($_POST['action']) && $_POST['action'] === 'delete_page') {
    $page_id = intval($_POST['page_id'] ?? 0);
    if ($page_id > 0) {
        // Fetch files to delete them
        $stmt = $pdo->prepare("SELECT image_path, file_path FROM pages WHERE id = :id");
        $stmt->execute([':id' => $page_id]);
        $p_files = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($p_files) {
            if (!empty($p_files['image_path']) && file_exists(__DIR__ . '/../' . $p_files['image_path'])) @unlink(__DIR__ . '/../' . $p_files['image_path']);
            if (!empty($p_files['file_path']) && file_exists(__DIR__ . '/../' . $p_files['file_path'])) @unlink(__DIR__ . '/../' . $p_files['file_path']);
        }

        $stmt = $pdo->prepare("DELETE FROM pages WHERE id = :id");
        $stmt->execute([':id' => $page_id]);
        header("Location: index.php?view=dashboard&success_delete=1");
        exit;
    }
}

if (isset($_GET['success'])) {
    $success_msg = 'Seite erfolgreich gespeichert!';
}
?>

<?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) ?></div>
<?php endif; ?>

<?php if ($create_mode || ($editor_mode && $page)): ?>
    <!-- Editor Mode Form -->
    <div class="card" style="max-width: 900px; margin: 0 auto;">
        <h3 class="card-title"><?= $create_mode ? 'Neue Seite erstellen' : 'Seite bearbeiten: ' . htmlspecialchars($page['title']) ?></h3>
        
        <form id="news_form" method="POST" enctype="multipart/form-data" action="" style="margin-top: 15px;">
            <input type="hidden" name="action" value="save_page">
            <input type="hidden" name="page_id" value="<?= $create_mode ? '0' : $page['id'] ?>">
            <input type="hidden" name="existing_image" value="<?= $create_mode ? '' : htmlspecialchars($page['image_path']) ?>">
            <input type="hidden" name="existing_file" value="<?= $create_mode ? '' : htmlspecialchars($page['file_path']) ?>">

            <div class="form-group">
                <label for="title">Seitentitel</label>
                <input type="text" id="title" name="title" value="<?= $create_mode ? '' : htmlspecialchars($page['title']) ?>" required>
            </div>

            <div class="form-group">
                <label for="slug">URL-Slug (Kleinschreibung, nur Kleinbuchstaben, Zahlen & Bindestriche)</label>
                <input type="text" id="slug" name="slug" value="<?= $create_mode ? '' : htmlspecialchars($page['slug']) ?>" placeholder="z. b. vorstand-news" required>
            </div>

            <div class="form-group">
                <label>Inhalt</label>
                <input type="hidden" id="content" name="content" value="<?= $create_mode ? '' : htmlspecialchars($page['content']) ?>">
                <div id="news_editor" style="height: 350px; background: white; color: black; border-radius: 4px;"><?= $create_mode ? '' : $page['content'] ?></div>
            </div>

            <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 0;">
                <div class="form-group">
                    <label for="image">Bilder-Header hochladen</label>
                    <input type="file" id="image" name="image">
                    <?php if (!$create_mode && !empty($page['image_path'])): ?>
                        <p style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">Aktuelles Bild: <a href="<?= htmlspecialchars($page['image_path']) ?>" target="_blank">Öffnen</a></p>
                    <?php endif; ?>
                </div>
                <div class="form-group">
                    <label for="file">Dateianhang zum Download hochladen</label>
                    <input type="file" id="file" name="file">
                    <?php if (!$create_mode && !empty($page['file_path'])): ?>
                        <p style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">Aktuelle Datei: <a href="<?= htmlspecialchars($page['file_path']) ?>" target="_blank">Herunterladen</a></p>
                    <?php endif; ?>
                </div>
            </div>

            <div style="display: flex; gap: 15px; margin-top: 20px;">
                <button type="submit" class="btn btn-primary">Speichern</button>
                <a href="<?= $create_mode ? 'index.php?view=dashboard' : 'index.php?view=pages&slug=' . urlencode($page['slug']) ?>" class="btn btn-secondary">Abbrechen</a>
            </div>
        </form>
    </div>

<?php elseif ($page): ?>
    <!-- Page Display Mode -->
    <div style="max-width: 900px; margin: 0 auto;">
        
        <div class="no-print" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 10px;">
            <div>
                <a href="index.php?view=dashboard" style="font-size: 14px; font-weight: 600; color: var(--primary); text-decoration: none;">&larr; Zurück zum Dashboard</a>
            </div>
            
            <div style="display: flex; gap: 10px;">
                <?php if (can_edit_pages()): ?>
                    <a href="index.php?view=pages&slug=<?= urlencode($page['slug']) ?>&edit=1" class="btn btn-secondary btn-sm">Seite bearbeiten</a>
                    <form method="POST" action="" onsubmit="return confirm('Möchten Sie diese Seite wirklich löschen?')">
                        <input type="hidden" name="action" value="delete_page">
                        <input type="hidden" name="page_id" value="<?= $page['id'] ?>">
                        <button type="submit" class="btn btn-danger btn-sm">Löschen</button>
                    </form>
                <?php endif; ?>
                <button class="btn btn-secondary btn-sm" onclick="triggerPrint()">Aushang drucken</button>
            </div>
        </div>

        <div class="card tm-news-sheet" style="padding: 40px; margin-bottom: 30px; background-color: #ffffff !important; color: #0f172a !important; border: 1px solid #cbd5e1 !important; box-shadow: var(--shadow-md) !important;">
            <?php if (!empty($page['image_path']) && file_exists(__DIR__ . '/../' . $page['image_path'])): ?>
                <img src="<?= htmlspecialchars($page['image_path']) ?>" style="width: 100%; max-height: 350px; object-fit: cover; border-radius: var(--radius); margin-bottom: 30px;" alt="Beitragsbild">
            <?php endif; ?>

            <h1 style="font-size: 32px; font-weight: 800; color: #0f172a !important; margin-bottom: 10px;"><?= htmlspecialchars($page['title']) ?></h1>
            <p style="font-size: 12px; color: #64748b !important; margin-bottom: 25px; border-bottom: 1px solid #e2e8f0 !important; padding-bottom: 15px;">
                Aktualisiert am: <?= date('d.m.Y H:i', strtotime($page['updated_at'])) ?>
            </p>

            <div style="font-size: 16px; line-height: 1.6; color: #334155 !important;">
                <?= $page['content'] ?>
            </div>

            <?php if (!empty($page['file_path']) && file_exists(__DIR__ . '/../' . $page['file_path'])): ?>
                <div style="margin-top: 40px; padding: 20px; background-color: #f8fafc !important; border: 1px solid #e2e8f0 !important; border-radius: var(--radius); display: flex; justify-content: space-between; align-items: center; color: #0f172a !important;">
                    <div>
                        <strong style="font-size: 15px; color: #0f172a !important;">Dateianhang verfügbar</strong>
                        <p style="font-size: 12px; color: #64748b !important; margin-top: 2px;">Laden Sie das beigefügte Dokument herunter.</p>
                    </div>
                    <a href="<?= htmlspecialchars($page['file_path']) ?>" download class="btn btn-primary btn-sm">Herunterladen</a>
                </div>
            <?php endif; ?>
        </div>

        <!-- Print QR Notice -->
        <div class="qr-notice">
            <img id="qr-code-img" src="" alt="QR Code" style="width: 120px; height: 120px; border: 1px solid #cbd5e1; padding: 5px;">
            <div>
                <h2 style="font-size: 18px; font-weight: 700; color: #000;">Diesen Aushang digital aufrufen</h2>
                <p style="font-size: 12px; color: #475569; margin-top: 4px; line-height: 1.4;">Scannen Sie den QR-Code, um diesen Artikel ("<?= htmlspecialchars($page['title']) ?>") online aufzurufen, Fotos anzusehen oder die Anhänge direkt auf Ihr Smartphone herunterzuladen.</p>
                <p style="font-size: 11px; color: #94a3b8; margin-top: 6px;">Team Mania PRO - <?= htmlspecialchars($club_name) ?></p>
            </div>
        </div>
    </div>
<?php else: ?>
    <!-- 404 Page Not Found -->
    <div style="text-align: center; padding: 60px 20px;">
        <h2 style="font-size: 28px; font-weight: 700; color: var(--secondary);">Seite nicht gefunden</h2>
        <p style="color: var(--text-muted); margin-top: 10px;">Die angeforderte Vereinsseite existiert nicht oder wurde gelöscht.</p>
        <a href="index.php?view=dashboard" class="btn btn-primary" style="margin-top: 25px;">Zurück zum Dashboard</a>
    </div>
<?php endif; ?>

<script>
document.addEventListener("DOMContentLoaded", function() {
    if (document.getElementById('news_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 newsQuill = new Quill('#news_editor', {
            theme: 'snow',
            placeholder: 'Schreibe den Artikelinhalt hier...',
            modules: { toolbar: toolbarOptions }
        });
        document.getElementById('news_form').addEventListener('submit', function() {
            document.getElementById('content').value = newsQuill.root.innerHTML;
        });
    }
});
</script>
