<?php
include_once 'shikanisha.kts.php';

// Initialize response array
$response = array();

// Get form data
$roomName = $_POST['roomName'];
$price = $_POST['price'];
$description = $_POST['description'];
$status = 'Vacant';

// Retrieve the uploaded file
$image = $_FILES['image'];
$fileName = $image['name'];
$fileTmpName = $image['tmp_name'];
$fileError = $image['error'];

// Read the image data
$imageData = file_get_contents($fileTmpName);

// Insert data into database
$query = "INSERT INTO rooms (room_name, price, description, image, status) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);

// Check if the statement preparation is successful
if (!$stmt) {
    $response['status'] = 'error';
    $response['message'] = 'Error in preparing the statement.';
} else {
    // Bind parameters
    $stmt->bind_param("sdsss", $roomName, $price, $description, $imageData, $status);

    // Execute the statement
    if ($stmt->execute()) {
        // If the insertion is successful, move the uploaded file to a desired location
        $destination = "../uploaded/" . $fileName;

        // Move the uploaded file to the destination
        if (move_uploaded_file($fileTmpName, $destination)) {
            $response['status'] = 'success';
            $response['message'] = 'Room added successfully.';
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Failed to move the uploaded file.';
        }
    } else {
        // If there's an error executing the SQL statement
        $response['status'] = 'error';
        $response['message'] = $stmt->error;
    }

    // Close the statement
    $stmt->close();
}

// Close the database connection
$conn->close();

// Return JSON response
echo json_encode($response);
?>
