<?php
// admin_posts.php - Final Working Version (No Editor)
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: admin.php');
    exit;
}
require_once 'config.php';

// Create uploads directory if not exists
$upload_dir = 'uploads/blog/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle Save Post
if (isset($_POST['save_post'])) {
    $title = $conn->real_escape_string($_POST['title']);
    $content = $conn->real_escape_string($_POST['content']);
    $excerpt = $conn->real_escape_string($_POST['excerpt']);
    $category_id = (int)$_POST['category_id'];
    $author = $conn->real_escape_string($_POST['author']);
    $status = $conn->real_escape_string($_POST['status']);
    $is_featured = isset($_POST['is_featured']) ? 1 : 0;
    $meta_title = $conn->real_escape_string($_POST['meta_title'] ?? '');
    $meta_description = $conn->real_escape_string($_POST['meta_description'] ?? '');
    $meta_keywords = $conn->real_escape_string($_POST['meta_keywords'] ?? '');
    
    // Generate slug
    $slug = !empty($_POST['slug']) ? $conn->real_escape_string(strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $_POST['slug'])))) 
            : strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
    $slug = preg_replace('/-+/', '-', $slug);
    
    // Handle image upload
    $featured_image = '';
    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] == 0 && $_FILES['featured_image']['size'] > 0) {
        $file_extension = strtolower(pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array($file_extension, $allowed)) {
            $new_filename = time() . '_' . rand(1000, 9999) . '.' . $file_extension;
            $target_file = $upload_dir . $new_filename;
            
            if (move_uploaded_file($_FILES['featured_image']['tmp_name'], $target_file)) {
                $featured_image = $target_file;
            }
        }
    }
    
    if (empty($featured_image) && isset($_POST['existing_image']) && !empty($_POST['existing_image'])) {
        $featured_image = $_POST['existing_image'];
    }
    
    // Publish date
    $published_at = !empty($_POST['published_at']) ? "'{$_POST['published_at']}'" : "NOW()";
    
    if (isset($_POST['post_id']) && $_POST['post_id'] > 0) {
        $id = (int)$_POST['post_id'];
        $sql = "UPDATE blog_posts SET 
                title='$title', slug='$slug', content='$content', excerpt='$excerpt',
                category_id=$category_id, author='$author', status='$status', 
                is_featured=$is_featured, featured_image='$featured_image',
                meta_title='$meta_title', meta_description='$meta_description', 
                meta_keywords='$meta_keywords', published_at=$published_at, updated_at=NOW()
                WHERE id=$id";
        $msg = "✅ Post updated!";
    } else {
        $sql = "INSERT INTO blog_posts (title, slug, content, excerpt, category_id, author, status, is_featured, featured_image, meta_title, meta_description, meta_keywords, published_at, created_at) 
                VALUES ('$title', '$slug', '$content', '$excerpt', $category_id, '$author', '$status', $is_featured, '$featured_image', '$meta_title', '$meta_description', '$meta_keywords', $published_at, NOW())";
        $msg = "✅ Post added!";
    }
    
    if ($conn->query($sql)) {
        $_SESSION['msg'] = $msg;
    } else {
        $_SESSION['msg'] = "❌ Error: " . $conn->error;
    }
    header('Location: admin_posts.php');
    exit;
}

// Delete Post
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $img = $conn->query("SELECT featured_image FROM blog_posts WHERE id=$id")->fetch_assoc();
    if ($img && $img['featured_image'] && file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $img['featured_image'])) {
        unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $img['featured_image']);
    }
    $conn->query("DELETE FROM blog_posts WHERE id=$id");
    $_SESSION['msg'] = "✅ Post deleted!";
    header('Location: admin_posts.php');
    exit;
}

// Edit Post - Get data
$edit_post = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $edit_post = $conn->query("SELECT * FROM blog_posts WHERE id=$edit_id")->fetch_assoc();
}

// Get all posts
$posts = $conn->query("SELECT p.*, c.name as category_name FROM blog_posts p LEFT JOIN blog_categories c ON p.category_id = c.id ORDER BY p.id DESC");
$categories = $conn->query("SELECT * FROM blog_categories ORDER BY display_order");
$msg = $_SESSION['msg'] ?? '';
unset($_SESSION['msg']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog Manager | Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body{background:#f0f2f5;padding:20px}
        .card{border-radius:15px;margin-bottom:20px}
        .card-header{background:#2d6a4f;color:#fff;border-radius:15px 15px 0 0;padding:15px 20px}
        .btn-success{background:#2d6a4f;border:none}
        .btn-success:hover{background:#1b4332}
        .table td{vertical-align:middle}
        .preview-img{width:60px;height:50px;object-fit:cover;border-radius:8px;border:1px solid #ddd}
        .featured-preview{max-width:100%;max-height:150px;border-radius:10px;margin-top:10px;border:1px solid #ddd}
        .content-editor{font-family:monospace;min-height:250px;width:100%;padding:10px}
        .form-label{font-weight:600}
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3><i class="fas fa-newspaper"></i> Blog Manager</h3>
        <div>
            <button class="btn btn-success" onclick="openAddForm()"><i class="fas fa-plus"></i> Add New Post</button>
            <a href="admin.php" class="btn btn-secondary ms-2"><i class="fas fa-arrow-left"></i> Back to Admin</a>
        </div>
    </div>
    
    <?php if($msg): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?=htmlspecialchars($msg)?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <!-- Add/Edit Post Form -->
        <div class="col-md-5">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-edit"></i> <?= $edit_post ? 'Edit Post' : 'Add New Post' ?>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data" id="postForm">
                        <?php if($edit_post): ?>
                            <input type="hidden" name="post_id" value="<?=$edit_post['id']?>">
                            <input type="hidden" name="existing_image" value="<?=$edit_post['featured_image']?>">
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Title *</label>
                            <input type="text" name="title" id="title" class="form-control" value="<?= $edit_post ? htmlspecialchars($edit_post['title']) : '' ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Slug (URL)</label>
                            <input type="text" name="slug" id="slug" class="form-control" value="<?= $edit_post ? htmlspecialchars($edit_post['slug']) : '' ?>" placeholder="auto-generated">
                            <small class="text-muted">Leave empty to auto-generate from title</small>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Excerpt (Short Description)</label>
                            <textarea name="excerpt" id="excerpt" class="form-control" rows="2"><?= $edit_post ? htmlspecialchars($edit_post['excerpt']) : '' ?></textarea>
                            <small class="text-muted">A short summary shown in blog listings</small>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Content *</label>
                            <textarea name="content" id="content" class="form-control content-editor" rows="8" required><?= $edit_post ? htmlspecialchars($edit_post['content']) : '' ?></textarea>
                            <small class="text-muted">Write your full article here. You can use HTML tags like &lt;b&gt;, &lt;i&gt;, &lt;ul&gt;, &lt;li&gt;, etc.</small>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Category</label>
                                    <select name="category_id" id="category_id" class="form-select">
                                        <option value="0">-- Select Category --</option>
                                        <?php $categories->data_seek(0); while($cat = $categories->fetch_assoc()): ?>
                                        <option value="<?=$cat['id']?>" <?= ($edit_post && $edit_post['category_id'] == $cat['id']) ? 'selected' : '' ?>>
                                            <?=htmlspecialchars($cat['name'])?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Author</label>
                                    <input type="text" name="author" id="author" class="form-control" value="<?= $edit_post ? htmlspecialchars($edit_post['author']) : 'Admin' ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Status</label>
                                    <select name="status" id="status" class="form-select">
                                        <option value="draft" <?= ($edit_post && $edit_post['status'] == 'draft') ? 'selected' : '' ?>>📝 Draft</option>
                                        <option value="published" <?= ($edit_post && $edit_post['status'] == 'published') ? 'selected' : '' ?>>🌍 Published</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Publish Date</label>
                                    <input type="datetime-local" name="published_at" id="published_at" class="form-control" value="<?= $edit_post && $edit_post['published_at'] ? date('Y-m-d\TH:i', strtotime($edit_post['published_at'])) : '' ?>">
                                    <small class="text-muted">Leave empty for current date/time</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Featured Image</label>
                                    <input type="file" name="featured_image" id="featured_image" class="form-control" accept="image/*" onchange="previewImage(this)">
                                    <div id="imagePreviewContainer" class="mt-2">
                                        <?php if($edit_post && $edit_post['featured_image'] && $edit_post['featured_image'] != '0'): ?>
                                            <?php $full_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $edit_post['featured_image']; ?>
                                            <?php if(file_exists($full_path)): ?>
                                                <img src="/<?=$edit_post['featured_image']?>" class="featured-preview" alt="Current Image">
                                                <p class="small text-muted mt-1">Current image</p>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3 form-check mt-4">
                                    <input type="checkbox" name="is_featured" id="is_featured" class="form-check-input" value="1" <?= ($edit_post && $edit_post['is_featured']) ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-bold">⭐ Feature this post (show on homepage)</label>
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        <h6><i class="fas fa-chart-line"></i> SEO Settings (Optional)</h6>
                        <div class="mb-3">
                            <label class="form-label">Meta Title</label>
                            <input type="text" name="meta_title" id="meta_title" class="form-control" value="<?= $edit_post ? htmlspecialchars($edit_post['meta_title']) : '' ?>" placeholder="SEO Title">
                            <small>Leave empty to use post title</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Meta Keywords</label>
                            <input type="text" name="meta_keywords" id="meta_keywords" class="form-control" value="<?= $edit_post ? htmlspecialchars($edit_post['meta_keywords']) : '' ?>" placeholder="keyword1, keyword2, keyword3">
                            <small>Comma separated keywords</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Meta Description</label>
                            <textarea name="meta_description" id="meta_description" class="form-control" rows="2" placeholder="SEO Description"><?= $edit_post ? htmlspecialchars($edit_post['meta_description']) : '' ?></textarea>
                            <small>Leave empty to use excerpt (150-160 characters recommended)</small>
                        </div>
                        
                        <button type="submit" name="save_post" class="btn btn-success w-100 mt-3">
                            <i class="fas fa-save"></i> <?= $edit_post ? 'Update Post' : 'Save Post' ?>
                        </button>
                        <?php if($edit_post): ?>
                            <a href="admin_posts.php" class="btn btn-secondary w-100 mt-2">Cancel Edit</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Posts List -->
        <div class="col-md-7">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-list"></i> All Posts
                    <span class="badge bg-light text-dark ms-2"><?=$posts->num_rows?> Total</span>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Image</th>
                                    <th>Title</th>
                                    <th>Category</th>
                                    <th>Status</th>
                                    <th>Views</th>
                                    <th>Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if($posts && $posts->num_rows > 0): ?>
                                <?php while($p = $posts->fetch_assoc()): ?>
                                <?php 
                                    $image_exists = false;
                                    if($p['featured_image'] && $p['featured_image'] != '0') {
                                        $full_image_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $p['featured_image'];
                                        $image_exists = file_exists($full_image_path);
                                    }
                                ?>
                                <tr>
                                    <td><?=$p['id']?></td>
                                    <td>
                                        <?php if($image_exists): ?>
                                            <img src="/<?=$p['featured_image']?>" class="preview-img" alt="img">
                                        <?php else: ?>
                                            <div class="preview-img bg-light d-flex align-items-center justify-content-center">
                                                <i class="fas fa-image text-muted"></i>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <strong><?=htmlspecialchars($p['title'])?></strong><br>
                                        <small class="text-muted"><?=htmlspecialchars(substr(strip_tags($p['excerpt']),0,60))?>...</small>
                                    </td>
                                    <td><?=htmlspecialchars($p['category_name'] ?? 'Uncategorized')?></td>
                                    <td>
                                        <span class="badge bg-<?=$p['status']=='published'?'success':'warning'?>">
                                            <?=ucfirst($p['status'])?>
                                        </span>
                                    </td>
                                    <td><?=number_format($p['views'])?></td>
                                    <td><?=date('d M Y', strtotime($p['created_at']))?></td>
                                    <td>
                                        <a href="?edit=<?=$p['id']?>" class="btn btn-sm btn-primary" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="?delete=<?=$p['id']?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this post?')" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                        <a href="single_post.php?id=<?=$p['id']?>" target="_blank" class="btn btn-sm btn-info" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center py-5">
                                        <i class="fas fa-newspaper fa-3x text-muted mb-3"></i>
                                        <h5>No posts yet</h5>
                                        <p>Click "Add New Post" to create your first blog post.</p>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Preview image before upload
function previewImage(input) {
    var previewContainer = document.getElementById('imagePreviewContainer');
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            previewContainer.innerHTML = '<img src="' + e.target.result + '" class="featured-preview" alt="Preview"><p class="small text-muted mt-1">New image preview</p>';
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// Open Add Form
function openAddForm() {
    window.location.href = 'admin_posts.php';
}

// Auto-generate slug from title
document.getElementById('title')?.addEventListener('blur', function() {
    var slugField = document.getElementById('slug');
    if (!slugField.value) {
        var slug = this.value.toLowerCase()
            .replace(/[^\w\s-]/g, '')
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-')
            .substring(0, 100);
        slugField.value = slug;
    }
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>