<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Blog</title>
    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
</head>
<body>

<?php
include "db.php";

if (isset($_POST['edit_id'])) {
    $id = intval($_POST['edit_id']);
    $title = mysqli_real_escape_string($conn, $_POST['edit_title']);
    $content = mysqli_real_escape_string($conn, $_POST['edit_content']);

    $getOld = mysqli_fetch_assoc(mysqli_query($conn, "SELECT image FROM blogs WHERE id = $id"));
    $image = $getOld['image'];

    if (!empty($_FILES['edit_image']['name'])) {
        $img_name = $_FILES['edit_image']['name'];
        $img_tmp = $_FILES['edit_image']['tmp_name'];
        $ext = pathinfo($img_name, PATHINFO_EXTENSION);
        $newName = time() . '.' . $ext;
        move_uploaded_file($img_tmp, "blogs/" . $newName);
        $image = $newName;
    }

    $update = "UPDATE blogs SET title='$title', content='$content', image='$image' WHERE id=$id";
    $run = mysqli_query($conn, $update);

    if ($run) {
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Blog Updated Successfully',
                showConfirmButton: false,
                timer: 1500
            }).then(() => {
                window.location.href = 'blog.php';
            });
        </script>";
    } else {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Failed to Update Blog'
            }).then(() => {
                window.location.href = 'blog.php';
            });
        </script>";
    }
}
?>

</body>
</html>