<?php
// edit_blog_post.php - Edit Blog Post
// File location: /bidwheels.net/admin/edit_blog_post.php

require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once 'includes/admin_header.php';

requireAdmin();

$post_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($post_id <= 0) {
    redirect('/admin/blog_posts.php');
}

$post = fetchOne("SELECT * FROM blog_posts WHERE id = $post_id");
if (!$post) {
    redirect('/admin/blog_posts.php');
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = sanitize($_POST['title']);
    $content = $_POST['content'];
    $category = sanitize($_POST['category']);
    $tags = sanitize($_POST['tags']);
    
    if (empty($title) || empty($content)) {
        $error = 'Title and content are required.';
    } else {
        $featured_image = $post['featured_image'];
        
        // Handle new featured image upload
        if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] == 0) {
            $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/bidwheels/uploads/blog/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Delete old image
            if ($featured_image && file_exists($upload_dir . $featured_image)) {
                unlink($upload_dir . $featured_image);
            }
            
            $ext = pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION);
            $filename = 'blog_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            $filepath = $upload_dir . $filename;
            
            if (move_uploaded_file($_FILES['featured_image']['tmp_name'], $filepath)) {
                $featured_image = $filename;
            }
        }
        
        update('blog_posts', [
            'title' => $title,
            'content' => $content,
            'featured_image' => $featured_image,
            'category' => $category,
            'tags' => $tags
        ], "id = $post_id");
        
        $success = 'Blog post updated successfully!';
        
        // Refresh post data
        $post = fetchOne("SELECT * FROM blog_posts WHERE id = $post_id");
    }
}
?>

<div class="admin-page">
    <h1 class="page-title">Edit Blog Post</h1>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?> <a href="../blog/post.php?id=<?php echo $post_id; ?>">View Post</a></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <form method="POST" action="" enctype="multipart/form-data" class="admin-form">
        <div class="form-group">
            <label>Post Title *</label>
            <input type="text" name="title" value="<?php echo htmlspecialchars($post['title']); ?>" class="form-control" required>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label>Category</label>
                <input type="text" name="category" value="<?php echo htmlspecialchars($post['category']); ?>" class="form-control" placeholder="e.g., Car Reviews, Buying Tips">
            </div>
            <div class="form-group">
                <label>Tags (comma separated)</label>
                <input type="text" name="tags" value="<?php echo htmlspecialchars($post['tags']); ?>" class="form-control" placeholder="cars, auctions, tips">
            </div>
        </div>
        
        <div class="form-group">
            <label>Current Featured Image</label>
            <?php if ($post['featured_image']): ?>
                <div>
                    <img src="<?php echo SITE_URL; ?>/uploads/blog/<?php echo $post['featured_image']; ?>" style="max-width: 200px; margin-bottom: 10px;">
                    <br>
                    <small>Upload a new image to replace this one</small>
                </div>
            <?php else: ?>
                <p>No featured image set.</p>
            <?php endif; ?>
            <input type="file" name="featured_image" accept="image/*" class="form-control">
        </div>
        
        <div class="form-group">
            <label>Post Content *</label>
            <textarea name="content" rows="15" class="form-control" id="editor" required><?php echo htmlspecialchars($post['content']); ?></textarea>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">Save Changes</button>
            <a href="blog_posts.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</div>

<?php require_once 'includes/admin_footer.php'; ?>