<?php
/**
 * Admin - Edit Blog Post
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Edit Blog Post';
$post_id = intval($_GET['id'] ?? 0);
$post = null;
$errors = [];

// Get categories
$categories = [];
try {
    $stmt = db()->query("SELECT * FROM blog_categories WHERE status = 1 ORDER BY name");
    $categories = $stmt->fetchAll();
} catch (PDOException $e) {}

if ($post_id) {
    try {
        $stmt = db()->prepare("SELECT * FROM blog_posts WHERE id = ?");
        $stmt->execute([$post_id]);
        $post = $stmt->fetch();
    } catch (PDOException $e) {}
}

if (!$post) {
    redirect(BASE_URL . 'admin/blog-posts.php', 'error', 'Post not found');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $title = sanitize($_POST['title'] ?? '');
        $category_id = intval($_POST['category_id'] ?? 0);
        $content = $_POST['content'] ?? '';
        $excerpt = sanitize($_POST['excerpt'] ?? '');
        $meta_title = sanitize($_POST['meta_title'] ?? '');
        $meta_description = sanitize($_POST['meta_description'] ?? '');
        $status = sanitize($_POST['status'] ?? 'draft');
        $author_name = sanitize($_POST['author_name'] ?? 'Admin');
        
        if (empty($title)) $errors[] = 'Title is required';
        if (empty($content)) $errors[] = 'Content is required';
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("UPDATE blog_posts SET 
                    category_id = ?, title = ?, excerpt = ?, content = ?, 
                    author_name = ?, meta_title = ?, meta_description = ?, status = ?, updated_at = NOW()
                    WHERE id = ?");
                $stmt->execute([$category_id, $title, $excerpt, $content, $author_name, $meta_title, $meta_description, $status, $post_id]);
                
                $stmt = db()->prepare("SELECT * FROM blog_posts WHERE id = ?");
                $stmt->execute([$post_id]);
                $post = $stmt->fetch();
                
                $success = 'Post updated successfully';
            } catch (PDOException $e) {
                $errors[] = 'Failed to update post: ' . $e->getMessage();
            }
        }
    }
}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Edit Blog Post</h2>
    <a href="blog-posts.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-2"></i>Back</a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger"><?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?></div>
<?php endif; ?>
<?php if (isset($success)): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            <div class="row g-3">
                <div class="col-md-8">
                    <label class="form-label">Title <span class="text-danger">*</span></label>
                    <input type="text" name="title" class="form-control" value="<?php echo $post['title']; ?>" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Category</label>
                    <select name="category_id" class="form-select">
                        <option value="">Select Category</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo $post['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                            <?php echo $cat['name']; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Author Name</label>
                    <input type="text" name="author_name" class="form-control" value="<?php echo $post['author_name'] ?? 'Admin'; ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="draft" <?php echo $post['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                        <option value="published" <?php echo $post['status'] == 'published' ? 'selected' : ''; ?>>Published</option>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Excerpt</label>
                    <textarea name="excerpt" class="form-control" rows="2"><?php echo $post['excerpt']; ?></textarea>
                </div>
                <div class="col-12">
                    <label class="form-label">Content <span class="text-danger">*</span></label>
                    <textarea name="content" class="form-control" rows="10" required><?php echo $post['content']; ?></textarea>
                </div>
                
                <div class="col-md-6">
                    <label class="form-label">Meta Title</label>
                    <input type="text" name="meta_title" class="form-control" value="<?php echo $post['meta_title']; ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Meta Description</label>
                    <input type="text" name="meta_description" class="form-control" value="<?php echo $post['meta_description']; ?>">
                </div>
            </div>
            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="bi bi-save me-2"></i>Update Post</button>
                <a href="blog-posts.php" class="btn btn-outline-secondary ms-2">Cancel</a>
                <a href="<?php echo BASE_URL; ?>blog-post.php?slug=<?php echo $post['slug']; ?>" target="_blank" class="btn btn-outline-info ms-2"><i class="bi bi-eye me-2"></i>View Post</a>
            </div>
        </form>
    </div>
</div>

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