<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Image</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']);

    $query = "SELECT image FROM gallery WHERE id = $id";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);
    $old_image = $row['image'];

    if (!empty($_FILES['edit_image']['name'])) {
        $new_image = $_FILES['edit_image']['name'];
        $tmp_name = $_FILES['edit_image']['tmp_name'];
        $target_dir = "../images/";
        $target_path = $target_dir . basename($new_image);

        if (move_uploaded_file($tmp_name, $target_path)) {
          
            if (!empty($old_image) && file_exists("../images/" . $old_image)) {
                unlink("../images/" . $old_image);
            }

            $update_sql = "UPDATE gallery SET image = '$new_image' WHERE id = $id";
        } else {
         
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Upload Failed!',
                    text: 'Unable to upload the image.'
                }).then(() => {
                    window.history.back();
                });
            </script>";
            exit;
        }
    } else {
      
        $update_sql = "UPDATE gallery SET image = '$old_image' WHERE id = $id";
    }

    if (mysqli_query($conn, $update_sql)) {
       
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Updated!',
                text: 'Image updated successfully.'
            }).then(() => {
                window.location.href = 'gallery.php';
            });
        </script>";
    } else {
      
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Update Failed!',
                text: 'Database error occurred.'
            }).then(() => {
                window.history.back();
            });
        </script>";
    }
}
?>

</body>
</html>