<?php
/**
 * IBVTE Admin - Blog/News CMS with Rich Text Editor
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Check database connection before proceeding
if (!checkDBConnection()) {
    exit;
}

Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$flash = getFlashMessage();

// Handle file uploads
// Handle file uploads with security checks
function uploadFile($file, $type = 'image') {
    $allowedImageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $allowedDocExtensions = ['pdf', 'doc', 'docx'];
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ($type === 'image') ? $allowedImageExtensions : $allowedDocExtensions;
    
    if (!in_array($ext, $allowed)) {
        return false;
    }

    // Check MIME type to prevent spoofing
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if ($type === 'image' && strpos($mime, 'image/') !== 0) return false;
    if ($type === 'doc' && $mime !== 'application/pdf' && !strpos($mime, 'msword') && !strpos($mime, 'officedocument')) return false;

    $uploadDir = UPLOADS_PATH . ($type === 'image' ? 'images/' : 'documents/');
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    
    $filename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
    $filepath = $uploadDir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return str_replace(ROOT_PATH, '', $filepath);
    }
    return false;
}

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

    $action = $_POST['action'] ?? '';
    
    if ($action === 'add' || $action === 'edit') {
        $featuredImage = '';
        if (!empty($_FILES['featured_image']['name'])) {
            $featuredImage = uploadFile($_FILES['featured_image'], 'image');
        }
        
        $data = [
            'title' => cleanInput($_POST['title'] ?? ''),
            'slug' => strtolower(preg_replace('/[^a-zA-Z0-9-]/', '-', cleanInput($_POST['title'] ?? ''))),
            'excerpt' => cleanInput($_POST['excerpt'] ?? ''),
            'content' => $_POST['content'] ?? '',
            'category' => cleanInput($_POST['category'] ?? ''),
            'tags' => json_encode(explode(',', cleanInput($_POST['tags'] ?? ''))),
            'author_id' => $_SESSION['user_id'],
            'is_published' => isset($_POST['is_published']) ? 1 : 0,
            'is_featured' => isset($_POST['is_featured']) ? 1 : 0,
            'meta_title' => cleanInput($_POST['meta_title'] ?? ''),
            'meta_description' => cleanInput($_POST['meta_description'] ?? ''),
            'meta_keywords' => cleanInput($_POST['meta_keywords'] ?? ''),
            'published_at' => isset($_POST['is_published']) ? date('Y-m-d H:i:s') : null
        ];
        
        if ($featuredImage) $data['featured_image'] = $featuredImage;
        
        if ($action === 'add') {
            $db->insert('blogs', $data);
            redirectWithMessage('blogs.php', 'Blog post published successfully', 'success');
        } else {
            $id = intval($_POST['id'] ?? 0);
            if (!$featuredImage) unset($data['featured_image']);
            $db->update('blogs', $data, ['id' => $id]);
            redirectWithMessage('blogs.php', 'Blog post updated successfully', 'success');
        }
    }
    
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        $db->delete('blogs', ['id' => $id]);
        redirectWithMessage('blogs.php', 'Blog post deleted', 'success');
    }
}

// Get all blogs
$blogs = $db->fetchAll("SELECT b.*, u.full_name as author_name 
                       FROM blogs b 
                       LEFT JOIN users u ON b.author_id = u.id 
                       ORDER BY b.created_at DESC");

// Get single blog for edit
$editBlog = null;
if (isset($_GET['edit'])) {
    $editBlog = $db->fetchOne("SELECT * FROM blogs WHERE id = ?", [intval($_GET['edit'])]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog/News CMS - <?= 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">
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs5.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
    <style>
        .blog-card { transition: all 0.3s ease; }
        .blog-card:hover { transform: translateY(-5px); }
        .blog-image { height: 200px; object-fit: cover; }
        .category-badge { position: absolute; top: 10px; left: 10px; }
        .featured-badge { position: absolute; top: 10px; right: 10px; }
    </style>
</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 flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                    <h1 class="h2"><i class="fas fa-blog me-2 text-primary"></i>Blog/News CMS</h1>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#blogModal">
                        <i class="fas fa-plus me-2"></i>Create Post
                    </button>
                </div>
                
                <?php if ($flash): ?>
                    <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show">
                        <?= htmlspecialchars($flash['message']) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <!-- Stats Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card text-center py-3">
                            <h3 class="text-primary mb-0"><?= count($blogs) ?></h3>
                            <small class="text-muted">Total Posts</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center py-3">
                            <h3 class="text-success mb-0"><?= count(array_filter($blogs, fn($b) => $b['is_published'])) ?></h3>
                            <small class="text-muted">Published</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center py-3">
                            <h3 class="text-warning mb-0"><?= count(array_filter($blogs, fn($b) => !$b['is_published'])) ?></h3>
                            <small class="text-muted">Drafts</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center py-3">
                            <h3 class="text-info mb-0"><?= count(array_filter($blogs, fn($b) => $b['is_featured'])) ?></h3>
                            <small class="text-muted">Featured</small>
                        </div>
                    </div>
                </div>
                
                <!-- Blog Posts Grid -->
                <div class="row">
                    <?php foreach ($blogs as $blog): ?>
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card blog-card h-100 <?= $blog['is_published'] ? '' : 'border-warning' ?>">
                                <div class="position-relative">
                                    <img src="<?= $blog['featured_image'] ? '../' . $blog['featured_image'] : '../assets/images/default-blog.jpg' ?>" 
                                         class="card-img-top blog-image" alt="">
                                    <?php if ($blog['category']): ?>
                                        <span class="badge bg-primary category-badge"><?= htmlspecialchars($blog['category']) ?></span>
                                    <?php endif; ?>
                                    <?php if ($blog['is_featured']): ?>
                                        <span class="badge bg-warning text-dark featured-badge"><i class="fas fa-star me-1"></i>Featured</span>
                                    <?php endif; ?>
                                </div>
                                <div class="card-body">
                                    <h5 class="card-title"><?= htmlspecialchars($blog['title']) ?></h5>
                                    <p class="card-text text-muted small"><?= substr(strip_tags($blog['excerpt'] ?: $blog['content']), 0, 100) ?>...</p>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">
                                            <i class="fas fa-user me-1"></i><?= htmlspecialchars($blog['author_name'] ?? 'Admin') ?>
                                            <br><i class="fas fa-calendar me-1"></i><?= formatDateTime($blog['created_at'], 'd M Y') ?>
                                        </small>
                                        <span class="badge bg-<?= $blog['is_published'] ? 'success' : 'warning text-dark' ?>">
                                            <?= $blog['is_published'] ? 'Published' : 'Draft' ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="card-footer bg-white">
                                    <div class="btn-group w-100">
                                        <a href="?edit=<?= $blog['id'] ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        <a href="../blog/<?= $blog['slug'] ?>.php" target="_blank" class="btn btn-sm btn-outline-info">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this post?')">
                                            <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $blog['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Blog Modal -->
    <div class="modal fade" id="blogModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header" style="background: linear-gradient(135deg, #3b0b7c, #6c4ab6); color: white;">
                    <h5 class="modal-title"><i class="fas fa-pen-fancy me-2"></i><?= $editBlog ? 'Edit' : 'Create' ?> Blog Post</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                        <input type="hidden" name="action" value="<?= $editBlog ? 'edit' : 'add' ?>">
                        <?php if ($editBlog): ?>
                            <input type="hidden" name="id" value="<?= $editBlog['id'] ?>">
                        <?php endif; ?>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Title</label>
                                    <input type="text" name="title" class="form-control form-control-lg" required 
                                           value="<?= $editBlog ? htmlspecialchars($editBlog['title']) : '' ?>">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Excerpt</label>
                                    <textarea name="excerpt" class="form-control" rows="2" 
                                              placeholder="Brief summary of the post"><?= $editBlog ? htmlspecialchars($editBlog['excerpt']) : '' ?></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Content <small class="text-muted">(Rich Text Editor - MS Office style)</small></label>
                                    <textarea name="content" id="summernote" class="form-control"><?= $editBlog ? htmlspecialchars($editBlog['content']) : '' ?></textarea>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Featured Image</label>
                                    <input type="file" name="featured_image" class="form-control" accept="image/*">
                                    <?php if ($editBlog && $editBlog['featured_image']): ?>
                                        <img src="../<?= $editBlog['featured_image'] ?>" class="img-fluid mt-2 rounded">
                                    <?php endif; ?>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Category</label>
                                    <input type="text" name="category" class="form-control" list="categories"
                                           value="<?= $editBlog ? htmlspecialchars($editBlog['category']) : '' ?>">
                                    <datalist id="categories">
                                        <option value="News">
                                        <option value="Events">
                                        <option value="Admissions">
                                        <option value="Results">
                                        <option value="Notifications">
                                        <option value="Career">
                                    </datalist>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Tags <small class="text-muted">(comma separated)</small></label>
                                    <input type="text" name="tags" class="form-control" 
                                           value="<?= $editBlog ? htmlspecialchars(implode(', ', json_decode($editBlog['tags'] ?? '[]', true))) : '' ?>">
                                </div>
                                
                                <div class="card mb-3">
                                    <div class="card-header bg-light">
                                        <strong>SEO Settings</strong>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-2">
                                            <label class="small">Meta Title</label>
                                            <input type="text" name="meta_title" class="form-control form-control-sm"
                                                   value="<?= $editBlog ? htmlspecialchars($editBlog['meta_title']) : '' ?>">
                                        </div>
                                        <div class="mb-2">
                                            <label class="small">Meta Description</label>
                                            <textarea name="meta_description" class="form-control form-control-sm" rows="2"><?= $editBlog ? htmlspecialchars($editBlog['meta_description']) : '' ?></textarea>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" name="is_published" id="isPublished" 
                                           <?= ($editBlog && $editBlog['is_published']) || !$editBlog ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-bold" for="isPublished">Publish Now</label>
                                </div>
                                
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" name="is_featured" id="isFeatured" 
                                           <?= $editBlog && $editBlog['is_featured'] ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-bold" for="isFeatured">Featured Post</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-2"></i><?= $editBlog ? 'Update' : 'Publish' ?> Post
                        </button>
                    </div>
                </form>
            </div>
        </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-bs5.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#summernote').summernote({
                height: 400,
                placeholder: 'Write your blog content here... (MS Office style editor)',
                toolbar: [
                    ['style', ['style', 'bold', 'italic', 'underline', 'clear', 'strikethrough', 'superscript', 'subscript']],
                    ['font', ['fontname', 'fontsize', 'color']],
                    ['para', ['ul', 'ol', 'paragraph', 'height']],
                    ['insert', ['table', 'link', 'picture', 'video', 'hr']],
                    ['view', ['fullscreen', 'codeview', 'help']],
                    ['history', ['undo', 'redo']]
                ],
                fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica', 'Impact', 'Tahoma', 'Times New Roman', 'Verdana'],
                fontSizes: ['8', '9', '10', '11', '12', '14', '16', '18', '20', '22', '24', '28', '32', '36'],
                callbacks: {
                    onImageUpload: function(files) {
                        // Handle image upload to server
                        for (let i = 0; i < files.length; i++) {
                            uploadImageToServer(files[i]);
                        }
                    }
                }
            });
            
            function uploadImageToServer(file) {
                let formData = new FormData();
                formData.append('image', file);
                
                $.ajax({
                    url: '../api/upload_image.php',
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        if (response.url) {
                            $('#summernote').summernote('insertImage', response.url);
                        }
                    }
                });
            }
        });
        
        <?php if ($editBlog): ?>
        var blogModal = new bootstrap.Modal(document.getElementById('blogModal'));
        blogModal.show();
        <?php endif; ?>
    </script>
</body>
</html>
