<?php
/**
 * CMS - Blog Post Editor
 * Create and edit blog posts
 */

require_once '../config/config.php';
requireLogin();
requireAdmin();

$pageTitle = 'Edit Blog Post';
$success = '';
$error = '';

$db = getDB();

// Get post ID if editing
$postId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$isEdit = $postId > 0;

// Initialize post data
$post = [
    'title' => '',
    'slug' => '',
    'excerpt' => '',
    'content' => '',
    'featured_image' => '',
    'status' => 'draft',
    'featured' => 0,
    'allow_comments' => 1,
    'meta_title' => '',
    'meta_description' => '',
    'meta_keywords' => ''
];

// Load existing post if editing
if ($isEdit) {
    $stmt = $db->prepare("SELECT * FROM cms_posts WHERE id = ?");
    $stmt->execute([$postId]);
    $existingPost = $stmt->fetch();
    
    if (!$existingPost) {
        redirect('cms-posts.php');
    }
    
    $post = $existingPost;
    $pageTitle = 'Edit Post: ' . $post['title'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    try {
        $title = sanitize($_POST['title'] ?? '');
        $slug = sanitize($_POST['slug'] ?? '');
        $excerpt = sanitize($_POST['excerpt'] ?? '');
        $content = $_POST['content'] ?? ''; // Don't sanitize - TinyMCE handles this
        $featuredImage = sanitize($_POST['featured_image'] ?? '');
        $status = sanitize($_POST['status'] ?? 'draft');
        $featured = isset($_POST['featured']) ? 1 : 0;
        $allowComments = isset($_POST['allow_comments']) ? 1 : 0;
        $metaTitle = sanitize($_POST['meta_title'] ?? '');
        $metaDescription = sanitize($_POST['meta_description'] ?? '');
        $metaKeywords = sanitize($_POST['meta_keywords'] ?? '');
        
        // Validate required fields
        if (empty($title)) {
            throw new Exception('Title is required');
        }
        
        // Generate slug if empty
        if (empty($slug)) {
            $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
        }
        
        // Check for duplicate slug
        $stmt = $db->prepare("SELECT id FROM cms_posts WHERE slug = ? AND id != ?");
        $stmt->execute([$slug, $postId]);
        if ($stmt->fetch()) {
            $slug .= '-' . time();
        }
        
        if ($isEdit) {
            // Update existing post
            $sql = "UPDATE cms_posts SET 
                    title = ?, slug = ?, excerpt = ?, content = ?, 
                    featured_image = ?, status = ?, featured = ?, allow_comments = ?,
                    meta_title = ?, meta_description = ?, meta_keywords = ?,
                    updated_at = NOW()";
            
            $params = [$title, $slug, $excerpt, $content, $featuredImage, $status, 
                      $featured, $allowComments, $metaTitle, $metaDescription, $metaKeywords];
            
            // Set published_at if status is published and not set yet
            if ($status === 'published' && empty($post['published_at'])) {
                $sql .= ", published_at = NOW()";
            }
            
            $sql .= " WHERE id = ?";
            $params[] = $postId;
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            
            $success = 'Post updated successfully.';
            logAudit($_SESSION['user_id'], 'update', 'cms_posts', $postId, 'Updated blog post');
            
        } else {
            // Create new post
            $sql = "INSERT INTO cms_posts 
                    (title, slug, excerpt, content, featured_image, status, featured, 
                     allow_comments, meta_title, meta_description, meta_keywords, 
                     author_id, published_at, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $publishedAt = ($status === 'published') ? date('Y-m-d H:i:s') : null;
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $title, $slug, $excerpt, $content, $featuredImage, $status, 
                $featured, $allowComments, $metaTitle, $metaDescription, $metaKeywords,
                $_SESSION['user_id'], $publishedAt
            ]);
            
            $postId = $db->lastInsertId();
            $isEdit = true;
            
            $success = 'Post created successfully.';
            logAudit($_SESSION['user_id'], 'create', 'cms_posts', $postId, 'Created blog post');
        }
        
        // Reload post data
        $stmt = $db->prepare("SELECT * FROM cms_posts WHERE id = ?");
        $stmt->execute([$postId]);
        $post = $stmt->fetch();
        
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4" style="margin-top: 56px;">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">
                    <i class="fas fa-edit"></i> <?php echo $isEdit ? 'Edit' : 'New'; ?> Blog Post
                </h1>
                <div class="btn-toolbar">
                    <a href="cms-posts.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Posts
                    </a>
                </div>
            </div>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <form method="POST" class="needs-validation" novalidate>
                <?php echo csrfField(); ?>
                
                <div class="row">
                    <!-- Main Content Column -->
                    <div class="col-lg-8">
                        <!-- Title -->
                        <div class="card shadow mb-4">
                            <div class="card-header">
                                <h6 class="m-0 font-weight-bold text-primary">Post Content</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Title <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="title" 
                                           value="<?php echo e($post['title']); ?>" 
                                           required id="postTitle">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Slug (URL)</label>
                                    <input type="text" class="form-control" name="slug" 
                                           value="<?php echo e($post['slug']); ?>" 
                                           id="postSlug"
                                           placeholder="auto-generated-from-title">
                                    <small class="form-text text-muted">Leave empty to auto-generate from title</small>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Excerpt</label>
                                    <textarea class="form-control" name="excerpt" rows="3"><?php echo e($post['excerpt']); ?></textarea>
                                    <small class="form-text text-muted">Brief summary shown in post listings</small>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Content</label>
                                    <textarea class="form-control" name="content" id="postContent" rows="15"><?php echo e($post['content']); ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- SEO Settings -->
                        <div class="card shadow mb-4">
                            <div class="card-header">
                                <h6 class="m-0 font-weight-bold text-primary">SEO Settings</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Meta Title</label>
                                    <input type="text" class="form-control" name="meta_title" 
                                           value="<?php echo e($post['meta_title']); ?>"
                                           maxlength="60">
                                    <small class="form-text text-muted">Recommended: 50-60 characters</small>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Meta Description</label>
                                    <textarea class="form-control" name="meta_description" rows="2" 
                                              maxlength="160"><?php echo e($post['meta_description']); ?></textarea>
                                    <small class="form-text text-muted">Recommended: 150-160 characters</small>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Meta Keywords</label>
                                    <input type="text" class="form-control" name="meta_keywords" 
                                           value="<?php echo e($post['meta_keywords']); ?>"
                                           placeholder="keyword1, keyword2, keyword3">
                                    <small class="form-text text-muted">Comma-separated keywords</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Sidebar Column -->
                    <div class="col-lg-4">
                        <!-- Publish Settings -->
                        <div class="card shadow mb-4">
                            <div class="card-header">
                                <h6 class="m-0 font-weight-bold text-primary">Publish Settings</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status">
                                        <option value="draft" <?php echo $post['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="published" <?php echo $post['status'] === 'published' ? 'selected' : ''; ?>>Published</option>
                                    </select>
                                </div>

                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="featured" 
                                           id="featured" <?php echo $post['featured'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="featured">
                                        Featured Post
                                    </label>
                                </div>

                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="allow_comments" 
                                           id="allowComments" <?php echo $post['allow_comments'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="allowComments">
                                        Allow Comments
                                    </label>
                                </div>

                                <?php if ($isEdit): ?>
                                <div class="mb-3">
                                    <small class="text-muted">
                                        <strong>Created:</strong> <?php echo date('M d, Y', strtotime($post['created_at'])); ?><br>
                                        <?php if ($post['published_at']): ?>
                                        <strong>Published:</strong> <?php echo date('M d, Y', strtotime($post['published_at'])); ?><br>
                                        <?php endif; ?>
                                        <strong>Views:</strong> <?php echo number_format($post['views']); ?>
                                    </small>
                                </div>
                                <?php endif; ?>

                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> <?php echo $isEdit ? 'Update' : 'Create'; ?> Post
                                    </button>
                                    <?php if ($isEdit && $post['status'] === 'published'): ?>
                                    <a href="../public/post.php?slug=<?php echo $post['slug']; ?>" 
                                       class="btn btn-outline-success" target="_blank">
                                        <i class="fas fa-eye"></i> View Post
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Featured Image -->
                        <div class="card shadow mb-4">
                            <div class="card-header">
                                <h6 class="m-0 font-weight-bold text-primary">Featured Image</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <input type="text" class="form-control" name="featured_image" 
                                           id="featuredImage"
                                           value="<?php echo e($post['featured_image']); ?>"
                                           placeholder="Image URL">
                                    <small class="form-text text-muted">Enter image URL or upload via Media Library (coming soon)</small>
                                </div>
                                
                                <?php if (!empty($post['featured_image'])): ?>
                                <div class="text-center">
                                    <img src="<?php echo e($post['featured_image']); ?>" 
                                         alt="Featured Image" 
                                         class="img-fluid rounded"
                                         style="max-height: 200px;">
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </main>
    </div>
</div>

<!-- TinyMCE Editor -->
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
    selector: '#postContent',
    height: 500,
    menubar: true,
    plugins: [
        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
        'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
    ],
    toolbar: 'undo redo | blocks | ' +
        'bold italic forecolor | alignleft aligncenter ' +
        'alignright alignjustify | bullist numlist outdent indent | ' +
        'removeformat | help',
    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
});

// Auto-generate slug from title
document.getElementById('postTitle').addEventListener('blur', function() {
    const slugField = document.getElementById('postSlug');
    if (!slugField.value) {
        const title = this.value;
        const slug = title.toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
        slugField.value = slug;
    }
});
</script>

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