<?php
include 'includes/header.php';
$page_title = $lang_frontend['PAGE_TITLE_NEWS'] ?? 'News';
?>

<?php
// Fetch news from database ordered by date (newest first)
try {
    if (isLoggedIn() && isAdmin()) {
        // Admin: fetch all news, including future/planned
        $stmt = $pdo->prepare("SELECT *, (created_at > NOW()) AS is_planned FROM news ORDER BY created_at DESC");
        $stmt->execute();
        $news_items = $stmt->fetchAll();
    } else {
        // Regular users: only published news
        $stmt = $pdo->prepare("SELECT *, 0 AS is_planned FROM news WHERE created_at <= NOW() ORDER BY created_at DESC");
        $stmt->execute();
        $news_items = $stmt->fetchAll();
    }
} catch (PDOException $e) {
    $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_ERROR_LOADING_NEWS'] ?? 'Error loading news: %s', $e->getMessage()), 'danger');
    $news_items = [];
}
?>

<div class="card mb-4">
    <div class="card-body">
        <?php if (isLoggedIn() && isAdmin()): ?>
            <div class="mb-4">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addNewsModal">
                    <i class="bi bi-plus"></i> <?php echo $lang_frontend['NEWS_BUTTON_ADD_NEW'] ?? 'Add New News'; ?>
                </button>
            </div>
        <?php endif; ?>

        <?php if (empty($news_items)): ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i>
                <?php echo $lang_frontend['NEWS_NO_ITEMS_AVAILABLE'] ?? 'No news available yet. Check back later.'; ?>
            </div>
        <?php else: ?>
            <div class="news-container">
                <?php foreach ($news_items as $news): ?>
                    <div class="card mb-4 bg-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h4 class="card-title mb-0 news-title-clickable" style="cursor: pointer;"
                                    data-news-id="<?php echo $news['id']; ?>">
                                    <?php echo htmlspecialchars($news['title']); ?>
                                    <?php if (isLoggedIn() && isAdmin() && !empty($news['is_planned']) && $news['is_planned']): ?>
                                        <span
                                            class="badge bg-warning text-dark ms-2"><?php echo $lang_frontend['NEWS_BADGE_NOT_PUBLISHED_YET'] ?? 'NOT PUBLISHED YET'; ?></span>
                                    <?php endif; ?>
                                </h4>
                                <?php if (!empty($news['category'])): ?>
                                    <span class="badge bg-primary"><?php echo htmlspecialchars($news['category']); ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="text-muted mb-3">
                                <small>
                                    <i class="bi bi-calendar"></i>
                                    <?php echo getFormattedDate($news['created_at'], DATETIME_FORMAT); ?>
                                </small>
                            </div>
                            <div class="news-content" id="news-content-<?php echo $news['id']; ?>" style="display: none;">
                                <?php echo makeLinksClickable(cleanHTML(html_entity_decode($news['message'], ENT_QUOTES | ENT_HTML5, 'UTF-8'))); ?>
                            </div>

                            <?php if (isLoggedIn() && isAdmin()): ?>
                                <div class="mt-3">
                                    <button type="button" class="btn btn-sm btn-outline-primary edit-news-btn"
                                        data-id="<?php echo $news['id']; ?>"
                                        data-title="<?php echo htmlspecialchars($news['title']); ?>"
                                        data-message="<?php echo htmlspecialchars($news['message']); ?>"
                                        data-category="<?php echo htmlspecialchars($news['category'] ?? ''); ?>"
                                        data-created-at="<?php echo htmlspecialchars($news['created_at']); ?>">
                                        <i class="bi bi-pencil"></i> <?php echo $lang_frontend['BUTTON_EDIT'] ?? 'Edit'; ?>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-danger delete-news-btn"
                                        data-id="<?php echo $news['id']; ?>">
                                        <i class="bi bi-trash"></i> <?php echo $lang_frontend['BUTTON_DELETE'] ?? 'Delete'; ?>
                                    </button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php if (isLoggedIn() && isAdmin()): ?>
    <!-- Add News Modal -->
    <div class="modal fade" id="addNewsModal" tabindex="-1" aria-labelledby="addNewsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addNewsModalLabel">
                        <?php echo $lang_frontend['NEWS_MODAL_TITLE_ADD'] ?? 'Add New News'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
                </div>
                <form action="<?php echo getCleanUrl('news_update'); ?>" method="post">
                    <div class="modal-body">
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="action" value="add">
                        <div class="mb-3">
                            <label for="title"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_TITLE'] ?? 'Title'; ?></label>
                            <input type="text" class="form-control" id="title" name="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="message"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_MESSAGE'] ?? 'Message'; ?></label>
                            <textarea class="form-control" id="message" name="message" rows="5" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="category"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_CATEGORY'] ?? 'Category'; ?></label>
                            <input type="text" class="form-control" id="category" name="category">
                        </div>
                        <div class="mb-3">
                            <label for="created_at"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_DATE'] ?? 'Date'; ?></label>
                            <input type="datetime-local" class="form-control" id="created_at" name="created_at"
                                value="<?php echo date('Y-m-d\TH:i'); ?>">
                            <div class="form-text">
                                <?php echo $lang_frontend['NEWS_FORM_HELP_DATE'] ?? 'Set the date and time for this news item. Future news will not be shown until their date.'; ?>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                        <button type="submit"
                            class="btn btn-primary"><?php echo $lang_frontend['NEWS_MODAL_BUTTON_ADD'] ?? 'Add News'; ?></button>
                    </div>
                </form>
                <script>
                    window.magicAIConfig = {
                        AI_OPENAI: '<?php echo AI_OPENAI; ?>',
                        AI_CLAUDE: '<?php echo AI_CLAUDE; ?>',
                        AI_GEMINI: '<?php echo AI_GEMINI; ?>',
                        AI_MISTRAL: '<?php echo AI_MISTRAL; ?>',
                        AI_DEEPSEEK: '<?php echo AI_DEEPSEEK; ?>'
                    };
                </script>
                <script>
                    $(document).ready(function () {
                        $('#message').summernote({
                            toolbar: [
                                ['style', ['bold', 'italic', 'underline', 'clear']],
                                ['para', ['ul', 'ol']],
                                ['insert', ['link']],
                                ['magic', ['SummernoteMagic']]
                            ],
                            height: 300,
                            minHeight: 150,
                            maxHeight: null,
                            dialogsFade: true,
                            dialogsInBody: true,
                            tabDisable: false,
                            spellCheck: true
                        });
                    });
                </script>
            </div>
        </div>
    </div>

    <!-- Edit News Modal -->
    <div class="modal fade" id="editNewsModal" tabindex="-1" aria-labelledby="editNewsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editNewsModalLabel">
                        <?php echo $lang_frontend['NEWS_MODAL_TITLE_EDIT'] ?? 'Edit News'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
                </div>
                <form action="<?php echo getCleanUrl('news_update'); ?>" method="post">
                    <div class="modal-body">
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="id" id="edit-id">
                        <div class="mb-3">
                            <label for="edit-title"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_TITLE'] ?? 'Title'; ?></label>
                            <input type="text" class="form-control" id="edit-title" name="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit-message"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_MESSAGE'] ?? 'Message'; ?></label>
                            <textarea class="form-control" id="edit-message" name="message" rows="5" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="edit-category"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_CATEGORY'] ?? 'Category'; ?></label>
                            <input type="text" class="form-control" id="edit-category" name="category">
                        </div>
                        <div class="mb-3">
                            <label for="edit-created_at"
                                class="form-label"><?php echo $lang_frontend['NEWS_FORM_LABEL_DATE'] ?? 'Date'; ?></label>
                            <input type="datetime-local" class="form-control" id="edit-created_at" name="created_at">
                            <div class="form-text">
                                <?php echo $lang_frontend['NEWS_FORM_HELP_DATE'] ?? 'Set the date and time for this news item. Future news will not be shown until their date.'; ?>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                        <button type="submit"
                            class="btn btn-primary"><?php echo $lang_frontend['NEWS_MODAL_BUTTON_UPDATE'] ?? 'Update News'; ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete News Modal -->
    <div class="modal fade" id="deleteNewsModal" tabindex="-1" aria-labelledby="deleteNewsModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteNewsModalLabel">
                        <?php echo $lang_frontend['NEWS_MODAL_TITLE_CONFIRM_DELETE'] ?? 'Confirm Delete'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
                </div>
                <form action="<?php echo getCleanUrl('news_update'); ?>" method="post">
                    <div class="modal-body">
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" id="delete-id">
                        <p><?php echo $lang_frontend['NEWS_DELETE_CONFIRMATION_MESSAGE'] ?? 'Are you sure you want to delete this news item? This action cannot be undone.'; ?>
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                        <button type="submit"
                            class="btn btn-danger"><?php echo $lang_frontend['BUTTON_DELETE'] ?? 'Delete'; ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endif; ?>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // News content toggle functionality
        document.querySelectorAll('.news-title-clickable').forEach(title => {
            title.addEventListener('click', function () {
                const newsId = this.getAttribute('data-news-id');
                const content = document.getElementById('news-content-' + newsId);

                if (content.style.display === 'none') {
                    // Show content
                    content.style.display = 'block';
                    this.style.color = '#0d6efd'; // Bootstrap primary color
                } else {
                    // Hide content
                    content.style.display = 'none';
                    this.style.color = ''; // Reset to default color
                }
            });
        });

        // Set up edit news modal (only if admin)
        <?php if (isLoggedIn() && isAdmin()): ?>
            document.querySelectorAll('.edit-news-btn').forEach(button => {
                button.addEventListener('click', function () {
                    const id = this.getAttribute('data-id');
                    const title = this.getAttribute('data-title');
                    const message = this.getAttribute('data-message');
                    const category = this.getAttribute('data-category');
                    const createdAt = this.getAttribute('data-created-at');

                    document.getElementById('edit-id').value = id;
                    document.getElementById('edit-title').value = title;
                    document.getElementById('edit-message').value = message;
                    document.getElementById('edit-category').value = category || '';
                    document.getElementById('edit-created_at').value = createdAt ? createdAt.replace(' ', 'T').slice(0, 16) : '';

                    // Show the modal
                    var editNewsModal = new bootstrap.Modal(document.getElementById('editNewsModal'));
                    editNewsModal.show();

                    // Initialize summernote after the modal is shown
                    $('#editNewsModal').on('shown.bs.modal', function () {

                        $('#edit-message').summernote({
                            toolbar: [
                                ['style', ['bold', 'italic', 'underline', 'clear']],
                                ['para', ['ul', 'ol']],
                                ['insert', ['link']],
                                ['magic', ['SummernoteMagic']]
                            ],
                            height: 300,
                            minHeight: 150,
                            maxHeight: null,
                            dialogsFade: true,
                            dialogsInBody: true,
                            tabDisable: false,
                            spellCheck: true,
                            focus: true
                        });



                    });
                });
            });
            // Clean up summernote when the modal is hidden
            $('#editNewsModal').on('hidden.bs.modal', function () {
                $('#edit-message').summernote('destroy');
                $('#editNewsModal').off('shown.bs.modal');
            });

            // Set up delete news modal
            document.querySelectorAll('.delete-news-btn').forEach(button => {
                button.addEventListener('click', function () {
                    const id = this.getAttribute('data-id');
                    document.getElementById('delete-id').value = id;

                    var deleteNewsModal = new bootstrap.Modal(document.getElementById('deleteNewsModal'));
                    deleteNewsModal.show();
                });
            });
        <?php endif; ?>
    });
</script>

<script>
    $(document).ready(function () {

    });
</script>

<?php include 'includes/footer.php'; ?>