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

<?php
include 'db.php';

if (isset($_POST['submit'])) {
    $image = $_FILES['image']['name'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $target_dir = "../images/";

    if (!empty($image)) {
        $new_filename = basename($image);
        $target_path = $target_dir . $new_filename;

        if (move_uploaded_file($tmp_name, $target_path)) {
            $sql = "INSERT INTO gallery (image) VALUES ('$new_filename')";
            if (mysqli_query($conn, $sql)) {
                echo "<script>
                  Swal.fire({
                    icon: 'success',
                    title: 'Uploaded!',
                    text: 'Image uploaded successfully',
                    confirmButtonText: 'OK'
                  }).then(() => {
                    window.location.href = 'gallery.php'; 
                  });
                </script>";
            } else {
                echo "<script>
                  Swal.fire('Error', 'Database error occurred!', 'error');
                </script>";
            }
        } else {
            echo "<script>
              Swal.fire('Error', 'Failed to upload image!', 'error');
            </script>";
        }
    } else {
        echo "<script>
          Swal.fire('Error', 'Please select an image!', 'warning');
        </script>";
    }
}
?>

</body>
</html>