<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
require_admin();

$pdo = require __DIR__ . '/../config/database.php';
$action = $_GET['action'] ?? 'list';

// Handle post actions
if ($action === 'delete' && isset($_GET['id'])) {
    if (!verify_csrf($_GET['_csrf'] ?? null)) {
        http_response_code(400);
        exit('Invalid CSRF token');
    }
    $postId = (int)$_GET['id'];
    
    $stmt = $pdo->prepare("DELETE FROM blog_posts WHERE id = ?");
    $stmt->execute([$postId]);
    
    set_flash('success', 'Post deleted successfully');
    redirect('/admin/blog.php');
}

if ($action === 'new') {
    $authorId = $_SESSION['user']['id'] ?? 1;
    $stmt = $pdo->prepare("INSERT INTO blog_posts (title, slug, status, author_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute(['New Post', 'new-post-' . time(), 'draft', $authorId, date('c'), date('c')]);
    $newId = $pdo->lastInsertId();
    
    // Also create SEO entry
    $stmt = $pdo->prepare("INSERT INTO blog_seo (post_id, created_at, updated_at) VALUES (?, ?, ?)");
    $stmt->execute([$newId, date('c'), date('c')]);
    
    redirect("/admin/blog.php?action=edit&id=$newId");
}

if ($action === 'edit' && isset($_GET['id'])) {
    $postId = (int)$_GET['id'];
    
    // Handle AJAX requests
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_save'])) {
        ensure_csrf();
        
        header('Content-Type: application/json');
        
        try {
            $title = $_POST['title'] ?? '';
            $slug = $_POST['slug'] ?? '';
            $content = $_POST['content'] ?? '';
            $excerpt = $_POST['excerpt'] ?? '';
            $featuredImage = $_POST['featured_image'] ?? '';
            $status = $_POST['status'] ?? 'draft';
            $publishedAt = $_POST['published_at'] ?? '';
            
            // Handle file upload for AJAX
            if (isset($_FILES['featured_image_file']) && $_FILES['featured_image_file']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['featured_image_file'];
                
                $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $maxSize = 5 * 1024 * 1024; // 5MB
                
                if (!in_array($file['type'], $allowedTypes)) {
                    echo json_encode(['success' => false, 'message' => 'Invalid file type']);
                    exit;
                }
                
                if ($file['size'] > $maxSize) {
                    echo json_encode(['success' => false, 'message' => 'File size too large']);
                    exit;
                }
                
                $uploadDir = __DIR__ . '/../uploads/blog/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $filename = 'blog_' . uniqid() . '_' . time() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
                $uploadPath = $uploadDir . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                    $featuredImage = '/uploads/blog/' . $filename;
                } else {
                    echo json_encode(['success' => false, 'message' => 'Upload failed']);
                    exit;
                }
            }
            
            // Update post
            $stmt = $pdo->prepare("UPDATE blog_posts SET title = ?, slug = ?, content = ?, excerpt = ?, featured_image = ?, status = ?, published_at = ?, updated_at = ? WHERE id = ?");
            $stmt->execute([$title, $slug, $content, $excerpt, $featuredImage, $status, $publishedAt, date('c'), $postId]);
            
            // Update SEO data
            $stmt = $pdo->prepare("UPDATE blog_seo SET seo_title = ?, meta_description = ?, focus_keyword = ?, meta_keywords = ?, og_title = ?, og_description = ?, twitter_title = ?, twitter_description = ?, canonical_url = ?, robots_index = ?, updated_at = ? WHERE post_id = ?");
            $stmt->execute([
                $_POST['seo_title'] ?? '',
                $_POST['meta_description'] ?? '',
                $_POST['focus_keyword'] ?? '',
                $_POST['meta_keywords'] ?? '',
                $_POST['og_title'] ?? '',
                $_POST['og_description'] ?? '',
                $_POST['twitter_title'] ?? '',
                $_POST['twitter_description'] ?? '',
                $_POST['canonical_url'] ?? '',
                isset($_POST['robots_index']) ? 1 : 0,
                date('c'),
                $postId
            ]);
            
            echo json_encode([
                'success' => true, 
                'message' => isset($_POST['auto_save']) ? 'Auto-saved' : 'Draft saved',
                'timestamp' => date('c')
            ]);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Save failed: ' . $e->getMessage()]);
        }
        exit;
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        ensure_csrf();
        
        $title = $_POST['title'] ?? '';
        $slug = $_POST['slug'] ?? '';
        $content = $_POST['content'] ?? '';
        $excerpt = $_POST['excerpt'] ?? '';
        $featuredImage = $_POST['featured_image'] ?? '';
        $status = $_POST['status'] ?? 'draft';
        $publishedAt = $_POST['published_at'] ?? '';
        
        // Handle file upload
        if (isset($_FILES['featured_image_file']) && $_FILES['featured_image_file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['featured_image_file'];
            
            // Validate file
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $maxSize = 5 * 1024 * 1024; // 5MB
            
            if (!in_array($file['type'], $allowedTypes)) {
                set_flash('error', 'Invalid file type. Please upload JPEG, PNG, GIF, or WebP images.');
                redirect("/admin/blog.php?action=edit&id=$postId");
            }
            
            if ($file['size'] > $maxSize) {
                set_flash('error', 'File size too large. Maximum size is 5MB.');
                redirect("/admin/blog.php?action=edit&id=$postId");
            }
            
            // Create upload directory if it doesn't exist
            $uploadDir = __DIR__ . '/../uploads/blog/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            // Generate unique filename
            $filename = 'blog_' . uniqid() . '_' . time() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $uploadPath = $uploadDir . $filename;
            
            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                $featuredImage = '/uploads/blog/' . $filename;
            } else {
                set_flash('error', 'Failed to upload image. Please try again.');
                redirect("/admin/blog.php?action=edit&id=$postId");
            }
        }
        
        // Update post
        $stmt = $pdo->prepare("UPDATE blog_posts SET title = ?, slug = ?, content = ?, excerpt = ?, featured_image = ?, status = ?, published_at = ?, updated_at = ? WHERE id = ?");
        $stmt->execute([$title, $slug, $content, $excerpt, $featuredImage, $status, $publishedAt, date('c'), $postId]);
        
        // Update SEO data
        $stmt = $pdo->prepare("UPDATE blog_seo SET seo_title = ?, meta_description = ?, focus_keyword = ?, meta_keywords = ?, og_title = ?, og_description = ?, twitter_title = ?, twitter_description = ?, canonical_url = ?, robots_index = ?, updated_at = ? WHERE post_id = ?");
        $stmt->execute([
            $_POST['seo_title'] ?? '',
            $_POST['meta_description'] ?? '',
            $_POST['focus_keyword'] ?? '',
            $_POST['meta_keywords'] ?? '',
            $_POST['og_title'] ?? '',
            $_POST['og_description'] ?? '',
            $_POST['twitter_title'] ?? '',
            $_POST['twitter_description'] ?? '',
            $_POST['canonical_url'] ?? '',
            isset($_POST['robots_index']) ? 1 : 0,
            date('c'),
            $postId
        ]);
        
        set_flash('success', 'Post updated successfully');
        redirect('/admin/blog.php');
    }
    
    // Get post data
    $stmt = $pdo->prepare("SELECT p.*, s.seo_title, s.meta_description, s.focus_keyword, s.meta_keywords, s.og_title, s.og_description, s.twitter_title, s.twitter_description, s.canonical_url, s.robots_index FROM blog_posts p LEFT JOIN blog_seo s ON p.id = s.post_id WHERE p.id = ?");
    $stmt->execute([$postId]);
    $post = $stmt->fetch();
    
    if (!$post) {
        set_flash('error', 'Post not found');
        redirect('/admin/blog.php');
    }
    
    include __DIR__ . '/../includes/header.php';
    ?>
    <style>
    .blog-editor { 
        max-width: 1200px; 
        margin: 0 auto; 
        padding: 40px 20px;
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    }
    
    .editor-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32px;
        padding-bottom: 20px;
        border-bottom: 2px solid #f3f4f6;
    }
    
    .editor-title {
        font-size: 28px;
        font-weight: 700;
        color: #1f2937;
        margin: 0;
    }
    
    .editor-actions {
        display: flex;
        gap: 12px;
    }
    
    .editor-tabs { 
        display: flex; 
        border-bottom: 2px solid #e5e7eb; 
        margin-bottom: 32px;
        background: #f8fafc;
        border-radius: 12px 12px 0 0;
        overflow: hidden;
    }
    
    .tab-button { 
        padding: 16px 32px; 
        background: none; 
        border: none; 
        cursor: pointer; 
        border-bottom: 3px solid transparent;
        font-weight: 600;
        color: #64748b;
        transition: all 0.2s ease;
        position: relative;
    }
    
    .tab-button:hover {
        background: rgba(79, 70, 229, 0.05);
        color: var(--primary);
    }
    
    .tab-button.active { 
        border-bottom-color: var(--primary); 
        color: var(--primary);
        background: white;
    }
    
    .tab-content { 
        display: none;
        animation: fadeIn 0.3s ease;
    }
    
    .tab-content.active { 
        display: block;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .form-section {
        background: #f8fafc;
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        padding: 24px;
        margin-bottom: 24px;
    }
    
    .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 20px 0;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .form-row { 
        display: grid; 
        grid-template-columns: 1fr 1fr; 
        gap: 20px;
        margin-bottom: 20px;
    }
    
    .form-group { 
        margin-bottom: 24px;
    }
    
    .form-label { 
        display: block; 
        font-weight: 600; 
        margin-bottom: 8px;
        color: #374151;
        font-size: 14px;
    }
    
    .form-input, .form-textarea, .form-select { 
        width: 100%; 
        padding: 12px 16px; 
        border: 2px solid #e5e7eb; 
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.2s ease;
        background: white;
    }
    
    .form-input:focus, .form-textarea:focus, .form-select:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }
    
    .form-textarea { 
        min-height: 200px;
        resize: vertical;
    }
    
    .form-help {
        font-size: 12px;
        color: #64748b;
        margin-top: 4px;
        display: flex;
        align-items: center;
        gap: 4px;
    }
    
    .character-count {
        font-size: 12px;
        color: #64748b;
        text-align: right;
        margin-top: 4px;
    }
    
    .character-count.warning {
        color: #d97706;
    }
    
    .character-count.error {
        color: #dc2626;
    }
    
    .seo-score { 
        padding: 16px 20px; 
        border-radius: 12px; 
        margin-bottom: 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border: 2px solid;
    }
    
    .seo-good { 
        background: #f0fdf4; 
        color: #16a34a;
        border-color: #16a34a;
    }
    
    .seo-ok { 
        background: #fef3c7; 
        color: #d97706;
        border-color: #d97706;
    }
    
    .seo-bad { 
        background: #fef2f2; 
        color: #dc2626;
        border-color: #dc2626;
    }
    
    .seo-score-value {
        font-size: 24px;
        font-weight: 700;
    }
    
    .seo-score-details {
        font-size: 14px;
        opacity: 0.8;
    }
    
    .preview-section {
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        padding: 24px;
        margin-top: 24px;
    }
    
    .preview-title {
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 16px 0;
    }
    
    .preview-content {
        color: #64748b;
        line-height: 1.6;
    }
    
    .action-buttons {
        display: flex;
        gap: 12px;
        justify-content: flex-end;
        padding-top: 24px;
        border-top: 2px solid #f3f4f6;
        margin-top: 32px;
    }
    
    .btn {
        padding: 12px 24px;
        border-radius: 8px;
        font-weight: 600;
        text-decoration: none;
        border: none;
        cursor: pointer;
        transition: all 0.2s ease;
        font-size: 14px;
    }
    
    .btn.primary {
        background: var(--primary);
        color: white;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        box-shadow: 0 4px 14px rgba(79, 70, 229, 0.3);
        border: 2px solid var(--primary);
    }
    
    .btn.primary:hover {
        background: #059669;
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(79, 70, 229, 0.4);
        border-color: #059669;
    }
    
    .btn.secondary {
        background: #f3f4f6;
        color: #374151;
        border: 1px solid #d1d5db;
    }
    
    .btn.secondary:hover {
        background: #e5e7eb;
    }
    
    .status-indicator {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }
    
    .status-draft {
        background: #fef3c7;
        color: #d97706;
    }
    
    .status-published {
        background: #d1fae5;
        color: #065f46;
    }
    
    .status-archived {
        background: #f1f5f9;
        color: #64748b;
    }
    
    .auto-save-indicator {
        position: fixed;
        top: 20px;
        right: 20px;
        background: #10b981;
        color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        opacity: 0;
        transform: translateY(-20px);
        transition: all 0.3s ease;
        z-index: 1001;
        pointer-events: none;
    }
    
    .auto-save-indicator.show {
        opacity: 1;
        transform: translateY(0);
    }
    
    .auto-save-indicator.saving {
        background: #f59e0b;
    }
    
    .auto-save-indicator.error {
        background: #ef4444;
    }
    
    .floating-publish {
        position: fixed;
        bottom: 30px;
        right: 30px;
        z-index: 1000;
        opacity: 0;
        transform: translateY(100px);
        transition: all 0.3s ease;
        pointer-events: none;
    }
    
    .floating-publish.visible {
        opacity: 1;
        transform: translateY(0);
        pointer-events: all;
    }
    
    .floating-publish .btn {
        font-size: 16px;
        padding: 16px 24px;
        border-radius: 50px;
        box-shadow: 0 8px 25px rgba(79, 70, 229, 0.4);
        animation: pulse 2s infinite;
    }
    
    @keyframes pulse {
        0% { box-shadow: 0 8px 25px rgba(79, 70, 229, 0.4); }
        50% { box-shadow: 0 8px 35px rgba(79, 70, 229, 0.6); }
        100% { box-shadow: 0 8px 25px rgba(79, 70, 229, 0.4); }
    }
    
    @media (max-width: 768px) {
        .blog-editor {
            padding: 20px 16px;
        }
        
        .editor-header {
            flex-direction: column;
            gap: 16px;
            align-items: flex-start;
        }
        
        .form-row {
            grid-template-columns: 1fr;
        }
        
        .editor-tabs {
            flex-direction: column;
        }
        
        .tab-button {
            border-bottom: 1px solid #e5e7eb;
            border-right: none;
        }
        
        .tab-button.active {
            border-bottom-color: var(--primary);
        }
        
        .action-buttons {
            flex-direction: column;
        }
    }
    </style>
    
    <div class="blog-editor">
        <div class="editor-header">
            <div>
                <h1 class="editor-title">Edit Blog Post</h1>
                <div style="margin-top: 8px;">
                    <span class="status-indicator status-<?=e($post['status'])?>">
                        <?=ucfirst($post['status'])?>
                    </span>
                    <span style="margin-left: 12px; color: #64748b; font-size: 14px;">
                        Last updated: <?=date('M j, Y g:i A', strtotime($post['updated_at']))?>
                    </span>
                </div>
            </div>
            <div class="editor-actions">
                <a href="/admin/blog.php" class="btn secondary">← Back to Posts</a>
                <button type="button" onclick="testFunction()" class="btn secondary">🧪 Test</button>
                <button type="button" onclick="previewPost()" class="btn secondary">👁️ Preview</button>
            </div>
        </div>
        
        <form method="post" action="/admin/blog.php?action=edit&id=<?= (int)$postId ?>" enctype="multipart/form-data" id="blog-form">
            <?=csrf_field()?>
            
            <div class="editor-tabs">
                <button type="button" class="tab-button active" onclick="switchTab('content')">Content</button>
                <button type="button" class="tab-button" onclick="switchTab('seo')">SEO</button>
                <button type="button" class="tab-button" onclick="switchTab('social')">Social</button>
            </div>
            
            <!-- Content Tab -->
            <div id="content-tab" class="tab-content active">
                <div class="form-section">
                    <h3 class="section-title">📝 Basic Information</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Post Title *</label>
                        <input type="text" name="title" value="<?=e($post['title'])?>" class="form-input" required placeholder="Enter an engaging title for your blog post">
                        <div class="form-help">
                            💡 A compelling title helps attract readers and improves SEO
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">URL Slug</label>
                            <input type="text" name="slug" value="<?=e($post['slug'])?>" class="form-input" placeholder="url-friendly-slug">
                            <div class="form-help">
                                🔗 This will be part of the URL: blog.com/<strong>your-slug</strong>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="draft" <?=$post['status'] === 'draft' ? 'selected' : ''?>>📝 Draft</option>
                                <option value="published" <?=$post['status'] === 'published' ? 'selected' : ''?>>📢 Published</option>
                                <option value="archived" <?=$post['status'] === 'archived' ? 'selected' : ''?>>📦 Archived</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Excerpt</label>
                        <textarea name="excerpt" class="form-textarea" rows="3" placeholder="Write a brief summary that will appear in blog listings and social media..."><?=e($post['excerpt'])?></textarea>
                        <div class="character-count" id="excerpt-count">
                            <?=strlen($post['excerpt'])?> / 150 characters recommended
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3 class="section-title">📄 Content</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Blog Content *</label>
                        <textarea name="content" class="form-textarea" rows="20" required placeholder="Write your amazing blog content here...

You can use:
• Paragraphs for main content
• Headers for structure
• Lists for readability
• Links to reference sources
• Bold/italic for emphasis"><?=e($post['content'])?></textarea>
                        <div class="form-help">
                            💡 Tip: Break up long paragraphs and use headings to improve readability
                        </div>
                        <div class="character-count" id="content-count">
                            <?=strlen($post['content'])?> characters
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3 class="section-title">🖼️ Media & Publishing</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Featured Image</label>
                        <div style="display: flex; gap: 12px; align-items: flex-start;">
                            <div style="flex: 1;">
                                <input type="file" name="featured_image_file" class="form-input" accept="image/*" onchange="handleImageUpload(this)">
                                <div class="form-help">
                                    🖼️ Upload an image (recommended: 1200x630px, max 5MB)
                                </div>
                            </div>
                            <div style="flex: 1;">
                                <input type="text" name="featured_image" value="<?=e($post['featured_image'])?>" class="form-input" placeholder="Or enter image URL">
                                <div class="form-help">
                                    � Or paste image URL directly
                                </div>
                            </div>
                        </div>
                        <?php if (!empty($post['featured_image'])): ?>
                        <div style="margin-top: 12px;">
                            <img src="<?=e($post['featured_image'])?>" alt="Featured Image" style="max-width: 200px; height: auto; border-radius: 8px; border: 1px solid #e5e7eb;">
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Published Date</label>
                            <input type="datetime-local" name="published_at" value="<?=e($post['published_at'])?>" class="form-input">
                            <div class="form-help">
                                📅 Schedule when this post should go live
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Reading Time (estimated)</label>
                            <input type="text" value="<?=ceil(str_word_count($post['content']) / 200)?> min read" class="form-input" readonly>
                            <div class="form-help">
                                ⏱️ Based on average reading speed of 200 words/minute
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- SEO Tab -->
            <div id="seo-tab" class="tab-content">
                <div class="seo-score" id="seo-score">
                    <div>
                        <div class="seo-score-value" id="score-text">Calculating...</div>
                        <div class="seo-score-details">SEO optimization score</div>
                    </div>
                    <div style="font-size: 24px;">🔍</div>
                </div>
                
                <div class="form-section">
                    <h3 class="section-title">🎯 Search Engine Optimization</h3>
                    
                    <div class="form-group">
                        <label class="form-label">SEO Title</label>
                        <input type="text" name="seo_title" value="<?=e($post['seo_title'])?>" class="form-input" maxlength="60" placeholder="Compelling title for search results">
                        <div class="character-count" id="seo-title-count">
                            <?=strlen($post['seo_title'])?> / 60 characters
                        </div>
                        <div class="form-help">
                            🔍 This appears in search engine results and browser tabs
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Meta Description</label>
                        <textarea name="meta_description" class="form-textarea" rows="3" maxlength="160" placeholder="Compelling description that encourages clicks..."><?=e($post['meta_description'])?></textarea>
                        <div class="character-count" id="meta-desc-count">
                            <?=strlen($post['meta_description'])?> / 160 characters
                        </div>
                        <div class="form-help">
                            🔍 This appears below your title in search results
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Focus Keyword</label>
                            <input type="text" name="focus_keyword" value="<?=e($post['focus_keyword'])?>" class="form-input" placeholder="main keyword">
                            <div class="form-help">
                                🎯 Primary keyword you want to rank for
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Meta Keywords</label>
                            <input type="text" name="meta_keywords" value="<?=e($post['meta_keywords'])?>" class="form-input" placeholder="keyword1, keyword2, keyword3">
                            <div class="form-help">
                                🏷️ Comma-separated additional keywords
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Canonical URL</label>
                        <input type="url" name="canonical_url" value="<?=e($post['canonical_url'])?>" class="form-input" placeholder="https://example.com/blog/post-url">
                        <div class="form-help">
                            🔗 Prevent duplicate content issues by specifying the canonical URL
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                            <input type="checkbox" name="robots_index" <?=$post['robots_index'] ? 'checked' : ''?> style="width: auto;">
                            <span class="form-label" style="margin: 0;">Allow search engines to index this post</span>
                        </label>
                        <div class="form-help">
                            🤖 Uncheck this if you don't want this post to appear in search results
                        </div>
                    </div>
                </div>
                
                <div class="preview-section">
                    <h4 class="preview-title">🔍 Search Result Preview</h4>
                    <div class="preview-content">
                        <div style="color: #1a0dab; font-size: 18px; margin-bottom: 4px;" id="preview-title">Your SEO Title Here</div>
                        <div style="color: #006621; font-size: 14px; margin-bottom: 8px;" id="preview-url">yourblog.com/your-url</div>
                        <div style="color: #545454; font-size: 13px; line-height: 1.4;" id="preview-description">Your meta description will appear here...</div>
                    </div>
                </div>
            </div>
            
            <!-- Social Tab -->
            <div id="social-tab" class="tab-content">
                <div class="form-section">
                    <h3 class="section-title">📘 Facebook / Open Graph</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Facebook Title</label>
                        <input type="text" name="og_title" value="<?=e($post['og_title'])?>" class="form-input" placeholder="Title for Facebook shares">
                        <div class="character-count" id="og-title-count">
                            <?=strlen($post['og_title'])?> characters
                        </div>
                        <div class="form-help">
                            📘 Custom title when shared on Facebook (defaults to SEO title)
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Facebook Description</label>
                        <textarea name="og_description" class="form-textarea" rows="3" placeholder="Description for Facebook shares..."><?=e($post['og_description'])?></textarea>
                        <div class="character-count" id="og-desc-count">
                            <?=strlen($post['og_description'])?> characters
                        </div>
                        <div class="form-help">
                            📘 Custom description when shared on Facebook
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3 class="section-title">🐦 Twitter Card</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Twitter Title</label>
                        <input type="text" name="twitter_title" value="<?=e($post['twitter_title'])?>" class="form-input" placeholder="Title for Twitter shares">
                        <div class="character-count" id="twitter-title-count">
                            <?=strlen($post['twitter_title'])?> characters
                        </div>
                        <div class="form-help">
                            🐦 Custom title when shared on Twitter (max 70 chars recommended)
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Twitter Description</label>
                        <textarea name="twitter_description" class="form-textarea" rows="3" placeholder="Description for Twitter shares..."><?=e($post['twitter_description'])?></textarea>
                        <div class="character-count" id="twitter-desc-count">
                            <?=strlen($post['twitter_description'])?> characters
                        </div>
                        <div class="form-help">
                            🐦 Custom description when shared on Twitter (max 200 chars recommended)
                        </div>
                    </div>
                </div>
                
                <div class="preview-section">
                    <h4 class="preview-title">🐦 Twitter Card Preview</h4>
                    <div class="preview-content">
                        <div style="border: 1px solid #e1e8ed; border-radius: 12px; overflow: hidden; max-width: 350px;">
                            <div style="background: #f3f4f6; height: 120px; display: flex; align-items: center; justify-content: center; color: #64748b;">
                                🖼️ Featured Image Preview
                            </div>
                            <div style="padding: 12px;">
                                <div style="font-size: 14px; font-weight: 600; margin-bottom: 4px;" id="twitter-preview-title">Your Twitter Title Here</div>
                                <div style="font-size: 13px; color: #5b7083; line-height: 1.4;" id="twitter-preview-desc">Your Twitter description will appear here...</div>
                            </div>
                        </div>
            </div>
            
            <div class="action-buttons">
                <button type="button" onclick="saveDraftAjax()" class="btn secondary">💾 Save Draft</button>
                <a href="/admin/blog.php" class="btn secondary">Cancel</a>
                <button type="submit" class="btn primary" style="font-size: 16px; padding: 14px 28px;">
                    <?php if ($post['status'] === 'published'): ?>
                        🔄 Update Published Post
                    <?php elseif ($post['status'] === 'draft'): ?>
                        📢 Publish Post
                    <?php else: ?>
                        📢 Update Post
                    <?php endif; ?>
                </button>
            </div>
        </form>
    </div>
    
    <!-- Auto-save Indicator -->
    <div class="auto-save-indicator" id="auto-save-indicator">✅ Saved</div>
    
    <!-- Floating Publish Button -->
    <div class="floating-publish" id="floating-publish">
        <button type="submit" form="blog-form" class="btn primary">
            <?php if ($post['status'] === 'published'): ?>
                🔄 Update
            <?php elseif ($post['status'] === 'draft'): ?>
                📢 Publish
            <?php else: ?>
                📢 Update
            <?php endif; ?>
        </button>
    </div>
    
    <script>
    // Auto-generate slug from title
    function generateSlug(title) {
        return title
            .toLowerCase()
            .replace(/[^\w\s-]/g, '') // Remove special characters
            .replace(/\s+/g, '-') // Replace spaces with hyphens
            .replace(/-+/g, '-') // Replace multiple hyphens with single hyphen
            .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
    }
    
    // Auto-update slug when title changes (if slug is empty)
    function setupSlugAutoGeneration() {
        const titleField = document.querySelector('input[name="title"]');
        const slugField = document.querySelector('input[name="slug"]');
        
        if (titleField && slugField) {
            titleField.addEventListener('input', () => {
                if (!slugField.value || slugField.dataset.autoGenerated === 'true') {
                    slugField.value = generateSlug(titleField.value);
                    slugField.dataset.autoGenerated = 'true';
                }
            });
            
            slugField.addEventListener('input', () => {
                slugField.dataset.autoGenerated = 'false';
            });
        }
    }
    
    // Image upload handling
    function handleImageUpload(input) {
        if (input.files && input.files[0]) {
            const file = input.files[0];
            
            // Validate file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                input.value = '';
                return;
            }
            
            // Validate file type
            if (!file.type.startsWith('image/')) {
                alert('Please select a valid image file');
                input.value = '';
                return;
            }
            
            // Create preview
            const reader = new FileReader();
            reader.onload = function(e) {
                // Update the URL field with the preview
                const urlField = document.querySelector('input[name="featured_image"]');
                if (urlField) {
                    urlField.value = e.target.result;
                    
                    // Show preview image
                    let preview = document.querySelector('#image-preview');
                    if (!preview) {
                        preview = document.createElement('div');
                        preview.id = 'image-preview';
                        preview.style.marginTop = '12px';
                        input.closest('.form-group').appendChild(preview);
                    }
                    preview.innerHTML = `<img src="${e.target.result}" alt="Preview" style="max-width: 200px; height: auto; border-radius: 8px; border: 1px solid #e5e7eb;">`;
                }
            };
            reader.readAsDataURL(file);
        }
    }
    
    // Character counters
    function updateCharacterCount(fieldId, countId, maxLength = null) {
        const field = document.querySelector(fieldId);
        const count = document.querySelector(countId);
        
        if (field && count) {
            const updateCount = () => {
                const length = field.value.length;
                const text = maxLength ? `${length} / ${maxLength} characters` : `${length} characters`;
                count.textContent = text;
                
                // Update color based on length
                count.classList.remove('warning', 'error');
                if (maxLength && length > maxLength * 0.9) {
                    count.classList.add('warning');
                }
                if (maxLength && length > maxLength) {
                    count.classList.add('error');
                }
            };
            
            field.addEventListener('input', updateCount);
            updateCount(); // Initial count
        }
    }
    
    // Live preview updates
    function updatePreviews() {
        const seoTitle = document.querySelector('input[name="seo_title"]');
        const metaDesc = document.querySelector('textarea[name="meta_description"]');
        const twitterTitle = document.querySelector('input[name="twitter_title"]');
        const twitterDesc = document.querySelector('textarea[name="twitter_description"]');
        const postTitle = document.querySelector('input[name="title"]');
        const slug = document.querySelector('input[name="slug"]');
        
        // SEO preview
        if (seoTitle && document.getElementById('preview-title')) {
            seoTitle.addEventListener('input', () => {
                document.getElementById('preview-title').textContent = seoTitle.value || postTitle.value || 'Your SEO Title Here';
            });
        }
        
        if (metaDesc && document.getElementById('preview-description')) {
            metaDesc.addEventListener('input', () => {
                document.getElementById('preview-description').textContent = metaDesc.value || 'Your meta description will appear here...';
            });
        }
        
        if (slug && document.getElementById('preview-url')) {
            slug.addEventListener('input', () => {
                document.getElementById('preview-url').textContent = `yourblog.com/${slug.value || 'your-url'}`;
            });
        }
        
        // Twitter preview
        if (twitterTitle && document.getElementById('twitter-preview-title')) {
            twitterTitle.addEventListener('input', () => {
                document.getElementById('twitter-preview-title').textContent = twitterTitle.value || postTitle.value || 'Your Twitter Title Here';
            });
        }
        
        if (twitterDesc && document.getElementById('twitter-preview-desc')) {
            twitterDesc.addEventListener('input', () => {
                document.getElementById('twitter-preview-desc').textContent = twitterDesc.value || 'Your Twitter description will appear here...';
            });
        }
    }
    
    // Auto-save functionality
    let autoSaveTimer;
    function startAutoSave() {
        const form = document.querySelector('form');
        if (!form) return;
        
        const saveData = () => {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            localStorage.setItem('blog_draft_' + <?= (int)$postId ?>, JSON.stringify(data));
            console.log('Draft auto-saved');
        };
        
        form.addEventListener('input', () => {
            clearTimeout(autoSaveTimer);
            autoSaveTimer = setTimeout(saveData, 2000); // Save after 2 seconds of inactivity
        });
        
        // Load draft on page load
        const savedDraft = localStorage.getItem('blog_draft_' + <?= (int)$postId ?>);
        if (savedDraft) {
            const data = JSON.parse(savedDraft);
            // You could implement draft restoration here
            console.log('Draft found in localStorage');
        }
    }
    
    // AJAX save draft function
    window.saveDraftAjax = function() {
        const form = document.querySelector('form');
        const formData = new FormData(form);
        
        // Update status to draft
        formData.set('status', 'draft');
        formData.set('ajax_save', '1');
        
        // Show saving indicator
        const saveBtn = document.querySelector('button[onclick*="saveDraft"]');
        if (saveBtn) {
            const originalText = saveBtn.textContent;
            saveBtn.textContent = '💾 Saving...';
            saveBtn.disabled = true;
            
            // Send AJAX request
            fetch('/admin/blog.php?action=edit&id=<?= (int)$postId ?>', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    saveBtn.textContent = '✅ Saved!';
                    setTimeout(() => {
                        saveBtn.textContent = originalText;
                        saveBtn.disabled = false;
                    }, 2000);
                    
                    // Update last modified time
                    const lastUpdated = document.querySelector('.editor-header span[style*="color: #64748b"]');
                    if (lastUpdated) {
                        lastUpdated.textContent = 'Last updated: Just now';
                    }
                } else {
                    throw new Error(data.message || 'Save failed');
                }
            })
            .catch(error => {
                console.error('Save error:', error);
                saveBtn.textContent = '❌ Save Failed';
                setTimeout(() => {
                    saveBtn.textContent = originalText;
                    saveBtn.disabled = false;
                }, 2000);
            });
        }
    }
    
    // Auto-save with AJAX
    function startAutoSave() {
        const form = document.querySelector('form');
        if (!form) return;
        
        let autoSaveTimer;
        const indicator = document.getElementById('auto-save-indicator');
        
        const showIndicator = (text, type = 'success') => {
            if (!indicator) return;
            
            indicator.textContent = text;
            indicator.className = 'auto-save-indicator show ' + type;
            
            if (type === 'success') {
                setTimeout(() => {
                    indicator.classList.remove('show');
                }, 2000);
            }
        };
        
        const saveData = () => {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            localStorage.setItem('blog_draft_' + <?= (int)$postId ?>, JSON.stringify(data));
            console.log('Draft auto-saved to localStorage');
            
            // Show saving indicator
            showIndicator('⏳ Saving...', 'saving');
            
            // Also save to server via AJAX
            const ajaxFormData = new FormData(form);
            ajaxFormData.set('status', 'draft');
            ajaxFormData.set('ajax_save', '1');
            ajaxFormData.set('auto_save', '1');
            
            fetch('/admin/blog.php?action=edit&id=<?= (int)$postId ?>', {
                method: 'POST',
                body: ajaxFormData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('Auto-save to server successful');
                    showIndicator('✅ Auto-saved', 'success');
                    
                    // Update last updated time subtly
                    const lastUpdated = document.querySelector('.editor-header span[style*="color: #64748b"]');
                    if (lastUpdated && !lastUpdated.dataset.autoUpdated) {
                        lastUpdated.textContent = 'Last updated: Just now';
                        lastUpdated.dataset.autoUpdated = 'true';
                        setTimeout(() => {
                            delete lastUpdated.dataset.autoUpdated;
                        }, 5000);
                    }
                } else {
                    throw new Error(data.message || 'Auto-save failed');
                }
            })
            .catch(error => {
                console.error('Auto-save error:', error);
                showIndicator('❌ Save failed', 'error');
            });
        };
        
        form.addEventListener('input', () => {
            clearTimeout(autoSaveTimer);
            autoSaveTimer = setTimeout(saveData, 3000); // Save after 3 seconds of inactivity
        });
        
        // Load draft on page load
        const savedDraft = localStorage.getItem('blog_draft_' + <?= (int)$postId ?>);
        if (savedDraft) {
            const data = JSON.parse(savedDraft);
            console.log('Draft found in localStorage');
            showIndicator('📝 Draft restored', 'success');
        }
    }
    
    // Test function to verify JavaScript is working
    window.testFunction = function() {
        console.log('JavaScript is working!');
        alert('JavaScript is working!');
    }
    
    // Tab switching
    window.switchTab = function(tabName, buttonElement) {
        document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
        
        // Activate the clicked button (or use event.target if buttonElement not provided)
        const activeBtn = buttonElement || event.target;
        activeBtn.classList.add('active');
        document.getElementById(tabName + '-tab').classList.add('active');
        
        if (tabName === 'seo') {
            calculateSeoScore();
        }
    }
    
    // Preview function
    window.previewPost = function() {
        const form = document.querySelector('form');
        const formData = new FormData(form);
        
        // Create a new window with preview
        const previewWindow = window.open('', '_blank', 'width=800,height=600');
        
        // Generate preview HTML
        const title = formData.get('title') || 'Untitled Post';
        const content = formData.get('content') || '';
        const excerpt = formData.get('excerpt') || '';
        const featuredImage = formData.get('featured_image') || '';
        
        const previewHtml = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>Preview: ${title}</title>
                <style>
                    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 800px; margin: 0 auto; padding: 40px 20px; line-height: 1.6; }
                    h1 { color: #1f2937; margin-bottom: 20px; }
                    .meta { color: #64748b; margin-bottom: 30px; font-size: 14px; }
                    .featured-image { max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 30px; }
                    .excerpt { background: #f8fafc; padding: 20px; border-left: 4px solid #10b981; margin-bottom: 30px; font-style: italic; }
                    .content { color: #374151; }
                    .content p { margin-bottom: 20px; }
                </style>
            </head>
            <body>
                <h1>${title}</h1>
                <div class="meta">
                    Published on ${new Date().toLocaleDateString()} • Reading time: ${Math.ceil(str_word_count(content) / 200)} min read
                </div>
                ${featuredImage ? `<img src="${featuredImage}" alt="${title}" class="featured-image">` : ''}
                ${excerpt ? `<div class="excerpt">${excerpt}</div>` : ''}
                <div class="content">${content.replace(/\n/g, '<br>')}</div>
            </body>
            </html>
        `;
        
        previewWindow.document.write(previewHtml);
        previewWindow.document.close();
    }
    
    // Enhanced SEO score calculation
    function calculateSeoScore() {
        const title = document.querySelector('input[name="seo_title"]').value;
        const description = document.querySelector('textarea[name="meta_description"]').value;
        const focusKeyword = document.querySelector('input[name="focus_keyword"]').value;
        const content = document.querySelector('textarea[name="content"]').value;
        const postTitle = document.querySelector('input[name="title"]').value;
        
        let score = 0;
        let issues = [];
        let recommendations = [];
        
        // Title scoring (30 points)
        if (title.length > 0 && title.length <= 60) {
            score += 30;
        } else if (title.length > 60) {
            issues.push('Title too long');
        } else if (title.length === 0) {
            issues.push('SEO title missing');
            recommendations.push('Add a compelling SEO title');
        }
        
        // Description scoring (25 points)
        if (description.length > 0 && description.length <= 160) {
            score += 25;
        } else if (description.length > 160) {
            issues.push('Description too long');
        } else if (description.length === 0) {
            issues.push('Meta description missing');
            recommendations.push('Add a compelling meta description');
        }
        
        // Focus keyword scoring (20 points)
        if (focusKeyword.length > 0) {
            score += 20;
            if (content.toLowerCase().includes(focusKeyword.toLowerCase())) {
                score += 10;
            } else {
                issues.push('Focus keyword not in content');
                recommendations.push('Include focus keyword in your content');
            }
        } else {
            issues.push('No focus keyword');
            recommendations.push('Define a focus keyword for better SEO');
        }
        
        // Content length scoring (15 points)
        if (content.length > 300) {
            score += 15;
        } else {
            issues.push('Content too short');
            recommendations.push('Write at least 300 words for better SEO');
        }
        
        const scoreElement = document.getElementById('seo-score');
        const scoreText = document.getElementById('score-text');
        
        scoreElement.className = 'seo-score';
        if (score >= 80) {
            scoreElement.classList.add('seo-good');
            scoreText.innerHTML = `<strong>Excellent (${score}/100)</strong><br><small>Great job! Your post is well optimized.</small>`;
        } else if (score >= 60) {
            scoreElement.classList.add('seo-ok');
            scoreText.innerHTML = `<strong>Good (${score}/100)</strong><br><small>Issues: ${issues.join(', ')}</small>`;
        } else {
            scoreElement.classList.add('seo-bad');
            scoreText.innerHTML = `<strong>Needs Work (${score}/100)</strong><br><small>Issues: ${issues.join(', ')}</small>`;
        }
        
        // Show recommendations if any
        if (recommendations.length > 0) {
            const recommendationsHtml = recommendations.map(rec => `• ${rec}`).join('<br>');
            scoreText.innerHTML += `<br><br><strong>Recommendations:</strong><br>${recommendationsHtml}`;
        }
    }
    
    // Real-time calculation listeners
    document.addEventListener('DOMContentLoaded', () => {
        const seoInputs = [
            'input[name="seo_title"]',
            'textarea[name="meta_description"]',
            'input[name="focus_keyword"]',
            'textarea[name="content"]',
            'input[name="title"]'
        ];
        
        seoInputs.forEach(selector => {
            const el = document.querySelector(selector);
            if (el) {
                el.addEventListener('input', () => {
                    // Only calculate if the SEO tab is visible or if we want to update the background score
                    calculateSeoScore();
                });
            }
        });
    });
    
    // Save draft function
    window.saveDraft = function() {
        const form = document.querySelector('form');
        const formData = new FormData(form);
        
        // Update status to draft
        const statusSelect = document.querySelector('select[name="status"]');
        if (statusSelect) {
            statusSelect.value = 'draft';
        }
        
        // Show saving indicator
        const saveBtn = event.target;
        const originalText = saveBtn.textContent;
        saveBtn.textContent = '💾 Saving...';
        saveBtn.disabled = true;
        
        // Simulate save (in real implementation, this would be an AJAX call)
        setTimeout(() => {
            saveBtn.textContent = '✅ Saved!';
            setTimeout(() => {
                saveBtn.textContent = originalText;
                saveBtn.disabled = false;
            }, 1500);
        }, 1000);
    }
    
    // Preview function
    function previewPost() {
        const form = document.querySelector('form');
        const formData = new FormData(form);
        
        // Create a new window with preview
        const previewWindow = window.open('', '_blank', 'width=800,height=600');
        
        // Generate preview HTML
        const title = formData.get('title') || 'Untitled Post';
        const content = formData.get('content') || '';
        const excerpt = formData.get('excerpt') || '';
        const featuredImage = formData.get('featured_image') || '';
        
        const previewHtml = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>Preview: ${title}</title>
                <style>
                    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 800px; margin: 0 auto; padding: 40px 20px; line-height: 1.6; }
                    h1 { color: #1f2937; margin-bottom: 20px; }
                    .meta { color: #64748b; margin-bottom: 30px; font-size: 14px; }
                    .featured-image { max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 30px; }
                    .excerpt { background: #f8fafc; padding: 20px; border-left: 4px solid #10b981; margin-bottom: 30px; font-style: italic; }
                    .content { color: #374151; }
                    .content p { margin-bottom: 20px; }
                </style>
            </head>
            <body>
                <h1>${title}</h1>
                <div class="meta">
                    Published on ${new Date().toLocaleDateString()} • Reading time: ${Math.ceil(str_word_count(content) / 200)} min read
                </div>
                ${featuredImage ? `<img src="${featuredImage}" alt="${title}" class="featured-image">` : ''}
                ${excerpt ? `<div class="excerpt">${excerpt}</div>` : ''}
                <div class="content">${content.replace(/\n/g, '<br>')}</div>
            </body>
            </html>
        `;
        
        previewWindow.document.write(previewHtml);
        previewWindow.document.close();
    }
    
    // Setup floating publish button
    function setupFloatingPublish() {
        const floatingBtn = document.getElementById('floating-publish');
        const actionButtons = document.querySelector('.action-buttons');
        
        if (!floatingBtn || !actionButtons) return;
        
        // Show floating button when user scrolls past the action buttons
        window.addEventListener('scroll', () => {
            const actionButtonsRect = actionButtons.getBoundingClientRect();
            const actionButtonsBottom = actionButtonsRect.bottom;
            
            if (actionButtonsBottom < 0) {
                // Action buttons are above viewport, show floating button
                floatingBtn.classList.add('visible');
            } else {
                // Action buttons are visible, hide floating button
                floatingBtn.classList.remove('visible');
            }
        });
        
        // Handle floating button click
        const floatingSubmitBtn = floatingBtn.querySelector('button');
        if (floatingSubmitBtn) {
            floatingSubmitBtn.addEventListener('click', function() {
                // Show loading state
                this.textContent = '⏳ Publishing...';
                this.disabled = true;
                
                // The form will submit automatically due to form="blog-form" attribute
            });
        }
    }
    
    // Add event listeners for buttons
    function setupButtonListeners() {
        // Tab buttons
        document.querySelectorAll('.tab-button').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const tabName = this.getAttribute('onclick').match(/switchTab\('(.+?)'\)/)[1];
                switchTab(tabName, this);
            });
        });
        
        // Preview button
        const previewBtn = document.querySelector('button[onclick="previewPost()"]');
        if (previewBtn) {
            previewBtn.addEventListener('click', function(e) {
                e.preventDefault();
                previewPost();
            });
        }
        
        // Save draft button
        const saveBtn = document.querySelector('button[onclick="saveDraft()"]');
        if (saveBtn) {
            saveBtn.addEventListener('click', function(e) {
                e.preventDefault();
                saveDraft();
            });
        }
    }
    
    // Initialize everything when DOM is loaded
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize slug auto-generation
        setupSlugAutoGeneration();
        
        // Initialize floating publish button
        setupFloatingPublish();
        
        // Initialize button listeners
        setupButtonListeners();
        
        // Initialize auto-save
        startAutoSave();
        
        // Initialize character counters
        updateCharacterCount('textarea[name="excerpt"]', '#excerpt-count', 150);
        updateCharacterCount('textarea[name="content"]', '#content-count');
        updateCharacterCount('input[name="seo_title"]', '#seo-title-count', 60);
        updateCharacterCount('textarea[name="meta_description"]', '#meta-desc-count', 160);
        updateCharacterCount('input[name="og_title"]', '#og-title-count');
        updateCharacterCount('textarea[name="og_description"]', '#og-desc-count');
        updateCharacterCount('input[name="twitter_title"]', '#twitter-title-count', 70);
        updateCharacterCount('textarea[name="twitter_description"]', '#twitter-desc-count', 200);
        
        // Initialize live previews
        updatePreviews();
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+S to save draft
            if (e.ctrlKey && e.key === 's') {
                e.preventDefault();
                saveDraftAjax();
            }
            
            // Ctrl+P to preview
            if (e.ctrlKey && e.key === 'p') {
                e.preventDefault();
                previewPost();
            }
            
            // Ctrl+Shift+P to publish
            if (e.ctrlKey && e.shiftKey && e.key === 'P') {
                e.preventDefault();
                const submitBtn = document.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.click();
                }
            }
            
            // Ctrl+1/2/3 to switch tabs
            if (e.ctrlKey && e.key === '1') {
                e.preventDefault();
                switchTab('content', document.querySelector('.tab-button:nth-child(1)'));
            }
            if (e.ctrlKey && e.key === '2') {
                e.preventDefault();
                switchTab('seo', document.querySelector('.tab-button:nth-child(2)'));
            }
            if (e.ctrlKey && e.key === '3') {
                e.preventDefault();
                switchTab('social', document.querySelector('.tab-button:nth-child(3)'));
            }
        });
    });
    </script>
    
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}

// List posts
$stmt = $pdo->query("SELECT p.*, u.full_name as author_name FROM blog_posts p LEFT JOIN users u ON p.author_id = u.id ORDER BY p.created_at DESC");
$posts = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<style>
.blog-management { max-width: 1200px; margin: 0 auto; padding: 20px; }
.post-list { margin-top: 20px; }
.post-item { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 20px; margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center; }
.post-info h3 { margin: 0 0 8px 0; }
.post-info p { margin: 0; color: var(--muted); font-size: 14px; }
.post-actions { display: flex; gap: 8px; }
.status-badge { padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
.status-published { background: #f0fdf4; color: #16a34a; }
.status-draft { background: #fef3c7; color: #d97706; }
.status-archived { background: #f1f5f9; color: #64748b; }
</style>

<div class="blog-management">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h1>Blog Management</h1>
        <a href="/admin/blog.php?action=new" class="btn primary">New Post</a>
    </div>
    
    <div class="post-list">
        <?php foreach ($posts as $post): ?>
            <div class="post-item">
                <div class="post-info">
                    <h3><?=e($post['title'])?></h3>
                    <p>
                        By <?=e($post['author_name'])?> • 
                        <?=date('M j, Y', strtotime($post['created_at']))?> • 
                        Status: <span class="status-badge status-<?=e($post['status'])?>"><?=e($post['status'])?></span>
                    </p>
                </div>
                <div class="post-actions">
                    <a href="/admin/blog.php?action=edit&id=<?=e($post['id'])?>" class="btn secondary">Edit</a>
                    <a href="/admin/blog.php?action=delete&id=<?=e($post['id'])?>&_csrf=<?=csrf_token()?>" class="btn danger" onclick="return confirm('Delete this post?')">Delete</a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

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