<?php
session_start();
include_once("../config/db.php");

// Security: Ensure user is an admin before performing any action.
if(!isset($_SESSION['admin'])){
    header("Location: login.php");
    exit();
}

// All logic, including potential redirects, must be handled before any HTML is output.

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

if ($id <= 0) {
    header("Location: manage_blog.php");
    exit();
}

// Handle form submission for update
if(isset($_POST['update'])){
    $title = $_POST['title'];
    $category = $_POST['category'];
    $description = $_POST['description'];
    $current_image = $_POST['current_image'];
    $new_filename = $current_image;

    // Handle file upload if a new image is provided
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        $filename = $_FILES['image']['name'];
        $filetype = pathinfo($filename, PATHINFO_EXTENSION);

        if (in_array(strtolower($filetype), $allowed)) {
            $new_filename = uniqid('', true) . '.' . $filetype;
            $upload_path = "uploads/" . $new_filename;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                // Delete the old image if it exists
                if (!empty($current_image) && file_exists("uploads/" . $current_image)) {
                    unlink("uploads/" . $current_image);
                }
            } else {
                $message = "<div class='error'>Error: Could not move uploaded file.</div>";
                $new_filename = $current_image; // Revert to old image on failure
            }
        } else {
            $message = "<div class='error'>Error: Invalid file type. Only JPG, JPEG, PNG, GIF are allowed.</div>";
        }
    }

    if (empty($message)) {
        // Use prepared statements to prevent SQL injection
        $sql = "UPDATE blog SET title=?, category=?, description=?, image=? WHERE id=?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "ssssi", $title, $category, $description, $new_filename, $id);
        
        if (mysqli_stmt_execute($stmt)) {
            // Redirect on success to show the updated list
            header("Location: manage_blog.php");
            exit();
        } else {
            $message = "<div class='error'>Database error: Could not update post.</div>";
        }
    }
}

$stmt = mysqli_prepare($conn, "SELECT * FROM blog WHERE id=?");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);

// If no post is found after a potential update attempt, redirect.
if (!$row) {
    header("Location: manage_blog.php");
    exit();
}

include 'admin_header.php';
?>
<div class="page-header">
    <h1>Edit Blog Post</h1>
    <a href="manage_blog.php" class="btn">Back to Blog</a>
</div>

<div class="content-wrapper">
    <?php if(!empty($message)) echo $message; ?>

    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="current_image" value="<?php echo htmlspecialchars($row['image']); ?>">
        
        <div class="form-group">
            <label for="title">Post Title</label>
            <input type="text" id="title" name="title" value="<?php echo htmlspecialchars($row['title']); ?>" required>
        </div>

        <div class="form-group">
            <label for="category">Category</label>
            <input type="text" id="category" name="category" value="<?php echo htmlspecialchars($row['category']); ?>" required>
        </div>

        <div class="form-group">
            <label for="description">Description</label>
            <textarea id="description" name="description"><?php echo htmlspecialchars($row['description']); ?></textarea>
        </div>

        <div class="form-group">
            <label for="image">Featured Image (optional, leave blank to keep current)</label>
            <p>Current Image: <br><img src="uploads/<?php echo htmlspecialchars($row['image']); ?>" alt="Current Image" style="max-width: 200px; margin-top: 10px;"></p>
            <input type="file" id="image" name="image">
        </div>

        <button type="submit" name="update">Update Post</button>
    </form>
</div>
<?php include 'admin_footer.php'; ?>