<?php
include('../dbconnect.php'); // Check correct path

if (!$con) {
    die("Database connection failed: " . mysqli_connect_error());
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = mysqli_real_escape_string($con, $_POST['name']);

    // File Upload Handling
    $target_dir = "../uploads/"; // Ensure 'uploads' folder exists
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $target_file = $target_dir . basename($_FILES["photo"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];

    // Check if valid image
    if (!in_array($imageFileType, $allowed_types)) {
        echo "<script>alert('Only JPG, JPEG, PNG & GIF files are allowed.'); window.history.back();</script>";
        $uploadOk = 0;
    }

    if ($uploadOk && move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file)) {
        // Insert into Database
        $query = "INSERT INTO photos (name, photo) VALUES ('$name', '$target_file')";
        if (mysqli_query($con, $query)) {
            echo "<script>alert('Photo uploaded successfully!'); window.location.href='gallery.php';</script>";
        } else {
            echo "Error: " . mysqli_error($con);
        }
    } else {
        echo "<script>alert('Error uploading file.'); window.history.back();</script>";
    }
}
?>
