<?php
/**
 * IBVTE Admin - Manage News & Notifications
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$action = $_GET['action'] ?? 'list';
$flash = getFlashMessage();

// Handle form submission for Add/Edit/Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        redirectWithMessage('manage-news.php', 'Security session expired. Please try again.', 'danger');
    }

    $action_post = $_POST['action'] ?? '';

    // Handle Delete (now via POST)
    if ($action_post === 'delete' && isset($_POST['id'])) {
        $db->delete('news_posts', ['id' => $_POST['id']]);
        redirectWithMessage('manage-news.php', 'Post deleted', 'success');
    }

    $title = cleanInput($_POST['title']);
    $content = $_POST['content']; // Rich text, don't strictly clean HTML here
    $post_type = cleanInput($_POST['post_type']);
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Generate slug
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
    
    $data = [
        'title' => $title,
        'slug' => $slug,
        'content' => $content,
        'post_type' => $post_type,
        'is_active' => $is_active
    ];
    
    // Handle File Upload with Security
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];
        $ext = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $uploadDir = __DIR__ . '/../assets/uploads/news/';
            if (!is_dir($uploadDir)) @mkdir($uploadDir, 0755, true);
            $filename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
            if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadDir . $filename)) {
                $data['featured_image'] = $filename;
            }
        }
    }

    if (isset($_POST['id']) && !empty($_POST['id'])) {
        $db->update('news_posts', $data, ['id' => $_POST['id']]);
        redirectWithMessage('manage-news.php', 'Post updated successfully', 'success');
    } else {
        $db->insert('news_posts', $data);
        redirectWithMessage('manage-news.php', 'Post created successfully', 'success');
    }
}


// Fetch single record for edit
$post = null;
if ($action === 'edit' && isset($_GET['id'])) {
    $post = $db->fetchOne("SELECT * FROM news_posts WHERE id = ?", [$_GET['id']]);
}

// Fetch all records for list
$posts = [];
if ($action === 'list') {
    $posts = $db->fetchAll("SELECT * FROM news_posts ORDER BY created_at DESC");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage News & Updates - <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- Summernote CSS -->
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
</head>
<body>
    <?php include __DIR__ . '/../includes/admin_header.php'; ?>
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-bullhorn me-2 text-primary"></i>Manage News & Updates</h2>
                    <?php if ($action === 'list'): ?>
                        <a href="?action=add" class="btn btn-primary"><i class="fas fa-plus me-1"></i> Add New Post</a>
                    <?php else: ?>
                        <a href="manage-news.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to List</a>
                    <?php endif; ?>
                </div>

                <?php if ($flash): ?>
                    <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm">
                        <?= htmlspecialchars($flash['message']) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if ($action === 'list'): ?>
                <!-- List View -->
                <div class="card shadow-sm border-0" style="border-radius:15px;">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="ps-4">Title</th>
                                        <th>Type</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                        <th class="text-end pe-4">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(empty($posts)): ?>
                                        <tr><td colspan="5" class="text-center py-4 text-muted">No posts found.</td></tr>
                                    <?php endif; ?>
                                    <?php foreach ($posts as $p): ?>
                                    <tr>
                                        <td class="ps-4 fw-bold"><?= htmlspecialchars($p['title']) ?></td>
                                        <td><span class="badge bg-secondary"><?= strtoupper($p['post_type']) ?></span></td>
                                        <td>
                                            <?php if($p['is_active']): ?>
                                                <span class="badge bg-success">Live</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">Hidden</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= date('d M Y', strtotime($p['created_at'])) ?></td>
                                        <td class="text-end pe-4">
                                            <a href="?action=edit&id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-edit"></i></a>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure?')">
                                                <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <?php else: ?>
                <!-- Add/Edit Form -->
                <div class="card shadow-sm border-0" style="border-radius:15px;">
                    <div class="card-body p-4">
                        <form method="POST" action="manage-news.php" enctype="multipart/form-data">
                            <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                            <?php if ($post): ?>
                                <input type="hidden" name="id" value="<?= $post['id'] ?>">
                            <?php endif; ?>
                            
                            <div class="row mb-3">
                                <div class="col-md-8">
                                    <label class="form-label fw-bold">Post Title</label>
                                    <input type="text" name="title" class="form-control border-2" required value="<?= htmlspecialchars($post['title'] ?? '') ?>">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label fw-bold">Post Type</label>
                                    <select name="post_type" class="form-select border-2">
                                        <option value="news" <?= ($post['post_type'] ?? '') === 'news' ? 'selected' : '' ?>>News</option>
                                        <option value="result" <?= ($post['post_type'] ?? '') === 'result' ? 'selected' : '' ?>>Result</option>
                                        <option value="notification" <?= ($post['post_type'] ?? '') === 'notification' ? 'selected' : '' ?>>Notification</option>
                                    </select>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label fw-bold">Content (Rich Text)</label>
                                <textarea name="content" id="summernote" class="form-control"><?= htmlspecialchars($post['content'] ?? '') ?></textarea>
                            </div>

                            <div class="row mb-4 align-items-center">
                                <div class="col-md-6">
                                    <label class="form-label fw-bold">Attachment (Image/PDF) Optional</label>
                                    <input type="file" name="attachment" class="form-control border-2">
                                    <?php if(!empty($post['featured_image'])): ?>
                                        <small class="text-success mt-1 d-block"><i class="fas fa-paperclip me-1"></i> Current file: <?= $post['featured_image'] ?></small>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6 pt-4">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="is_active" id="isActive" <?= (!isset($post) || $post['is_active']) ? 'checked' : '' ?>>
                                        <label class="form-check-label fw-bold" for="isActive">Make this post live immediately</label>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" class="btn btn-primary btn-lg px-5 shadow"><i class="fas fa-save me-2"></i>Save Post</button>
                        </form>
                    </div>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
    <script>
        $(document.ready(function() {
            $('#summernote').summernote({
                placeholder: 'Type your content here. You can paste images, format text, and insert links.',
                tabsize: 2,
                height: 300,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link', 'picture', 'video']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });
        });
    </script>
</body>
</html>
