<?php
// Include the database configuration file
include 'config.php';

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Define the directory where you want to store the uploaded images
$targetFilePath = $_SERVER['DOCUMENT_ROOT'] . "/$itemImage";


// Check if the uploads directory exists, if not, create it
if (!file_exists($targetDirectory)) {
    mkdir($targetDirectory, 0755, true); // Recursive mkdir to create nested directories if necessary
}

// Retrieve form data
$itemName = $_POST['foodName'];
$itemPrice = $_POST['foodPrice'];

// Handle file upload
if ($_FILES["foodImage"]["error"] === UPLOAD_ERR_OK) {
    $itemImage = basename($_FILES["foodImage"]["name"]);
    $targetFilePath = $targetDirectory . $itemImage; // Constructing the full path

    // Move the uploaded file to the desired location
    if (move_uploaded_file($_FILES["foodImage"]["tmp_name"], $targetFilePath)) {
        // File successfully uploaded, now insert data into database
        $sql = "INSERT INTO menu_items (name, price, image) VALUES ('$itemName', '$itemPrice', '$itemImage')";
        if ($conn->query($sql) === TRUE) {
            echo "Food item uploaded and inserted into database successfully!";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    } else {
        echo "Error uploading file!";
    }
} else {
    // Handle file upload errors
    echo "Error uploading file: " . $_FILES["foodImage"]["error"];
}

$conn->close();
?>