<?php
session_start();
include '../config.php';

// Check admin authentication
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin-login.php');
    exit;
}

// Handle blog operations
$message = '';
$message_type = '';

if ($_POST) {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create':
                $title = mysqli_real_escape_string($conn, $_POST['title']);
                $custom_slug = mysqli_real_escape_string($conn, trim($_POST['slug']));
                
                // Use custom slug if provided, otherwise generate from title
                if (!empty($custom_slug)) {
                    $slug = strtolower(str_replace(' ', '-', preg_replace('/[^A-Za-z0-9\s\-]/', '', $custom_slug)));
                } else {
                    $slug = strtolower(str_replace(' ', '-', preg_replace('/[^A-Za-z0-9\s]/', '', $title)));
                }
                
                // Ensure slug is unique
                $base_slug = $slug;
                $counter = 1;
                while (true) {
                    $check_query = "SELECT id FROM blogs WHERE slug = '$slug'";
                    $check_result = mysqli_query($conn, $check_query);
                    if (mysqli_num_rows($check_result) == 0) {
                        break;
                    }
                    $slug = $base_slug . '-' . $counter;
                    $counter++;
                }
                
                $content = mysqli_real_escape_string($conn, $_POST['content']);
                $excerpt = mysqli_real_escape_string($conn, $_POST['excerpt']);
                $category = mysqli_real_escape_string($conn, $_POST['category']);
                $tags = mysqli_real_escape_string($conn, $_POST['tags']);
                $status = mysqli_real_escape_string($conn, $_POST['status']);
                $meta_title = mysqli_real_escape_string($conn, $_POST['meta_title']);
                $meta_description = mysqli_real_escape_string($conn, $_POST['meta_description']);
                
                // Handle file upload
                $featured_image = '';
                if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] == 0) {
                    $upload_dir = '../uploads/blog/';
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $file_extension = pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION);
                    $featured_image = 'blog_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
                    
                    if (move_uploaded_file($_FILES['featured_image']['tmp_name'], $upload_dir . $featured_image)) {
                        // File uploaded successfully
                    } else {
                        $featured_image = '';
                    }
                }
                
                $insert_query = "INSERT INTO blogs (title, slug, content, excerpt, featured_image, category, tags, status, meta_title, meta_description) 
                                VALUES ('$title', '$slug', '$content', '$excerpt', '$featured_image', '$category', '$tags', '$status', '$meta_title', '$meta_description')";
                
                if (mysqli_query($conn, $insert_query)) {
                    $message = "Blog post created successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error: " . mysqli_error($conn);
                    $message_type = "error";
                }
                break;
                
            case 'update':
                $id = (int)$_POST['id'];
                $title = mysqli_real_escape_string($conn, $_POST['title']);
                $custom_slug = mysqli_real_escape_string($conn, trim($_POST['slug']));
                
                // Use custom slug if provided, otherwise generate from title
                if (!empty($custom_slug)) {
                    $slug = strtolower(str_replace(' ', '-', preg_replace('/[^A-Za-z0-9\s\-]/', '', $custom_slug)));
                } else {
                    $slug = strtolower(str_replace(' ', '-', preg_replace('/[^A-Za-z0-9\s]/', '', $title)));
                }
                
                // Ensure slug is unique (excluding current post)
                $base_slug = $slug;
                $counter = 1;
                while (true) {
                    $check_query = "SELECT id FROM blogs WHERE slug = '$slug' AND id != $id";
                    $check_result = mysqli_query($conn, $check_query);
                    if (mysqli_num_rows($check_result) == 0) {
                        break;
                    }
                    $slug = $base_slug . '-' . $counter;
                    $counter++;
                }
                
                $content = mysqli_real_escape_string($conn, $_POST['content']);
                $excerpt = mysqli_real_escape_string($conn, $_POST['excerpt']);
                $category = mysqli_real_escape_string($conn, $_POST['category']);
                $tags = mysqli_real_escape_string($conn, $_POST['tags']);
                $status = mysqli_real_escape_string($conn, $_POST['status']);
                $meta_title = mysqli_real_escape_string($conn, $_POST['meta_title']);
                $meta_description = mysqli_real_escape_string($conn, $_POST['meta_description']);
                
                // Handle new image upload
                $image_update = '';
                if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] == 0) {
                    $upload_dir = '../uploads/blog/';
                    $file_extension = pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION);
                    $featured_image = 'blog_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
                    
                    if (move_uploaded_file($_FILES['featured_image']['tmp_name'], $upload_dir . $featured_image)) {
                        $image_update = ", featured_image = '$featured_image'";
                    }
                }
                
                $update_query = "UPDATE blogs SET 
                                title = '$title', 
                                slug = '$slug', 
                                content = '$content', 
                                excerpt = '$excerpt', 
                                category = '$category', 
                                tags = '$tags', 
                                status = '$status',
                                meta_title = '$meta_title',
                                meta_description = '$meta_description',
                                updated_at = NOW()
                                $image_update
                                WHERE id = $id";
                
                if (mysqli_query($conn, $update_query)) {
                    $message = "Blog post updated successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error: " . mysqli_error($conn);
                    $message_type = "error";
                }
                break;
                
            case 'delete':
                $id = (int)$_POST['id'];
                
                // Get image to delete
                $image_query = "SELECT featured_image FROM blogs WHERE id = $id";
                $image_result = mysqli_query($conn, $image_query);
                if ($image_result && mysqli_num_rows($image_result) > 0) {
                    $blog = mysqli_fetch_assoc($image_result);
                    if ($blog['featured_image']) {
                        $image_path = '../uploads/blog/' . $blog['featured_image'];
                        if (file_exists($image_path)) {
                            unlink($image_path);
                        }
                    }
                }
                
                $delete_query = "DELETE FROM blogs WHERE id = $id";
                if (mysqli_query($conn, $delete_query)) {
                    $message = "Blog post deleted successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error: " . mysqli_error($conn);
                    $message_type = "error";
                }
                break;
        }
    }
}

// Fetch all blog posts
$blogs_query = "SELECT * FROM blogs ORDER BY created_at DESC";
$blogs_result = mysqli_query($conn, $blogs_query);

// Get editing blog if ID provided
$editing_blog = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $edit_query = "SELECT * FROM blogs WHERE id = $edit_id";
    $edit_result = mysqli_query($conn, $edit_query);
    if ($edit_result && mysqli_num_rows($edit_result) > 0) {
        $editing_blog = mysqli_fetch_assoc($edit_result);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog Management - Shubank Admin</title>
    <link rel="stylesheet" href="admin.css">
    <style>
        .blog-form {
            background: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .form-group textarea {
            height: 200px;
            resize: vertical;
        }
        
        .content-editor {
            height: 300px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .blog-table {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .blog-table table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .blog-table th,
        .blog-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        .blog-table th {
            background: #f8f9fa;
            font-weight: bold;
            color: #333;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .status-published {
            background: #d4edda;
            color: #155724;
        }
        
        .status-draft {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-archived {
            background: #f8d7da;
            color: #721c24;
        }
        
        .actions {
            display: flex;
            gap: 5px;
        }
        
        .image-preview {
            max-width: 60px;
            max-height: 60px;
            border-radius: 5px;
        }
        
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .blog-table {
                overflow-x: auto;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <div class="admin-header">
            <h1>Blog Management</h1>
            <div class="admin-nav">
                <a href="admin-dashboard.php">Dashboard</a>
                <a href="#" class="active">Blog Management</a>
                <a href="admin-logout.php">Logout</a>
            </div>
        </div>
        
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <!-- Blog Form -->
        <div class="blog-form">
            <h2><?php echo $editing_blog ? 'Edit Blog Post' : 'Create New Blog Post'; ?></h2>
            
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="<?php echo $editing_blog ? 'update' : 'create'; ?>">
                <?php if ($editing_blog): ?>
                    <input type="hidden" name="id" value="<?php echo $editing_blog['id']; ?>">
                <?php endif; ?>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="title">Title *</label>
                        <input type="text" id="title" name="title" required 
                               value="<?php echo $editing_blog ? htmlspecialchars($editing_blog['title']) : ''; ?>"
                               onkeyup="generateSlug()">
                    </div>
                    
                    <div class="form-group">
                        <label for="slug">URL Slug *</label>
                        <input type="text" id="slug" name="slug" required 
                               value="<?php echo $editing_blog ? htmlspecialchars($editing_blog['slug']) : ''; ?>"
                               placeholder="url-friendly-slug">
                        <small style="color: #666;">URL will be: /blog/<span id="slug-preview"><?php echo $editing_blog ? htmlspecialchars($editing_blog['slug']) : 'your-slug-here'; ?></span></small>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="category">Category</label>
                        <select id="category" name="category">
                            <option value="tips" <?php echo ($editing_blog && $editing_blog['category'] == 'tips') ? 'selected' : ''; ?>>Tips & Strategies</option>
                            <option value="analysis" <?php echo ($editing_blog && $editing_blog['category'] == 'analysis') ? 'selected' : ''; ?>>Market Analysis</option>
                            <option value="platform" <?php echo ($editing_blog && $editing_blog['category'] == 'platform') ? 'selected' : ''; ?>>Platform Updates</option>
                            <option value="educational" <?php echo ($editing_blog && $editing_blog['category'] == 'educational') ? 'selected' : ''; ?>>Educational</option>
                            <option value="news" <?php echo ($editing_blog && $editing_blog['category'] == 'news') ? 'selected' : ''; ?>>News & Updates</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="excerpt">Excerpt</label>
                    <textarea id="excerpt" name="excerpt" rows="3" placeholder="Brief description of the blog post..."><?php echo $editing_blog ? htmlspecialchars($editing_blog['excerpt']) : ''; ?></textarea>
                </div>
                
                <div class="form-group">
                    <label for="content">Content *</label>
                    <textarea id="content" name="content" class="content-editor" required><?php echo $editing_blog ? htmlspecialchars($editing_blog['content']) : ''; ?></textarea>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="tags">Tags (comma separated)</label>
                        <input type="text" id="tags" name="tags" 
                               value="<?php echo $editing_blog ? htmlspecialchars($editing_blog['tags']) : ''; ?>"
                               placeholder="matka tips, strategies, gaming">
                    </div>
                    
                    <div class="form-group">
                        <label for="status">Status</label>
                        <select id="status" name="status">
                            <option value="draft" <?php echo ($editing_blog && $editing_blog['status'] == 'draft') ? 'selected' : ''; ?>>Draft</option>
                            <option value="published" <?php echo ($editing_blog && $editing_blog['status'] == 'published') ? 'selected' : ''; ?>>Published</option>
                            <option value="archived" <?php echo ($editing_blog && $editing_blog['status'] == 'archived') ? 'selected' : ''; ?>>Archived</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="featured_image">Featured Image</label>
                    <input type="file" id="featured_image" name="featured_image" accept="image/*">
                    <?php if ($editing_blog && $editing_blog['featured_image']): ?>
                        <p>Current image: <img src="../uploads/blog/<?php echo htmlspecialchars($editing_blog['featured_image']); ?>" class="image-preview" alt="Current featured image"></p>
                    <?php endif; ?>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="meta_title">Meta Title (SEO)</label>
                        <input type="text" id="meta_title" name="meta_title" 
                               value="<?php echo $editing_blog ? htmlspecialchars($editing_blog['meta_title']) : ''; ?>"
                               placeholder="SEO optimized title">
                    </div>
                    
                    <div class="form-group">
                        <label for="meta_description">Meta Description (SEO)</label>
                        <textarea id="meta_description" name="meta_description" rows="2" 
                                  placeholder="SEO description (150-160 characters)"><?php echo $editing_blog ? htmlspecialchars($editing_blog['meta_description']) : ''; ?></textarea>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <?php echo $editing_blog ? 'Update Post' : 'Create Post'; ?>
                    </button>
                    <?php if ($editing_blog): ?>
                        <a href="blog-management.php" class="btn btn-secondary">Cancel Edit</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
        
        <!-- Blog Posts Table -->
        <div class="blog-table">
            <table>
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Status</th>
                        <th>Views</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($blogs_result && mysqli_num_rows($blogs_result) > 0): ?>
                        <?php while ($blog = mysqli_fetch_assoc($blogs_result)): ?>
                            <tr>
                                <td>
                                    <?php if ($blog['featured_image']): ?>
                                        <img src="../uploads/blog/<?php echo htmlspecialchars($blog['featured_image']); ?>" 
                                             class="image-preview" alt="Blog image">
                                    <?php else: ?>
                                        <div style="width: 60px; height: 60px; background: #f0f0f0; border-radius: 5px; display: flex; align-items: center; justify-content: center;">No Image</div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($blog['title']); ?></strong>
                                    <br><small><?php echo substr(strip_tags($blog['content']), 0, 50) . '...'; ?></small>
                                </td>
                                <td><?php echo ucfirst($blog['category']); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $blog['status']; ?>">
                                        <?php echo ucfirst($blog['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo number_format($blog['views']); ?></td>
                                <td><?php echo date('M d, Y', strtotime($blog['created_at'])); ?></td>
                                <td>
                                    <div class="actions">
                                        <a href="?edit=<?php echo $blog['id']; ?>" class="btn btn-secondary" style="font-size: 12px; padding: 5px 10px;">Edit</a>
                                        <a href="../blog/<?php echo $blog['slug']; ?>" target="_blank" class="btn btn-success" style="font-size: 12px; padding: 5px 10px;">View</a>
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this blog post?');">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?php echo $blog['id']; ?>">
                                            <button type="submit" class="btn btn-danger" style="font-size: 12px; padding: 5px 10px;">Delete</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 50px;">No blog posts found. Create your first post above!</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <script>
    // Auto-generate slug from title
    function generateSlug() {
        const title = document.getElementById('title').value;
        const slug = title
            .toLowerCase()
            .replace(/[^a-z0-9\s-]/g, '') // Remove special characters
            .replace(/\s+/g, '-') // Replace spaces with hyphens
            .replace(/-+/g, '-') // Replace multiple hyphens with single
            .trim('-'); // Remove leading/trailing hyphens
        
        document.getElementById('slug').value = slug;
        updateSlugPreview();
    }
    
    // Update URL preview
    function updateSlugPreview() {
        const slug = document.getElementById('slug').value || 'your-slug-here';
        document.getElementById('slug-preview').textContent = slug;
    }
    
    // Initialize slug preview and add event listeners
    document.addEventListener('DOMContentLoaded', function() {
        updateSlugPreview();
        
        // Update preview when slug is manually edited
        document.getElementById('slug').addEventListener('input', updateSlugPreview);
        
        // Validate slug format
        document.getElementById('slug').addEventListener('blur', function() {
            let slug = this.value;
            // Clean up the slug
            slug = slug
                .toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '')
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-')
                .trim('-');
            
            this.value = slug;
            updateSlugPreview();
        });
        
        // Check slug availability (optional enhancement)
        let slugCheckTimeout;
        document.getElementById('slug').addEventListener('input', function() {
            clearTimeout(slugCheckTimeout);
            const slug = this.value;
            
            if (slug.length > 3) {
                slugCheckTimeout = setTimeout(() => {
                    checkSlugAvailability(slug);
                }, 500);
            }
        });
    });
    
    // Check if slug is available
    function checkSlugAvailability(slug) {
        // This would make an AJAX call to check slug availability
        // For now, we'll just update the preview
        updateSlugPreview();
    }
    </script>
</body>
</html>