<?php
require_once '../db.php';

// Get ID from URL parameter
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$id) {
    http_response_code(400);
    echo json_encode(["success" => false, "error" => "Invalid item ID"]);
    exit;
}

$name = $_POST['name'] ?? '';
$price = $_POST['price'] ?? 0;
$description = $_POST['description'] ?? '';
$alt = $_POST['alt'] ?? $name; // Default alt to name if not provided
$category_id = $_POST['category_id'] ?? 0;

// Get current image if exists
$currentImage = '';
$result = $conn->query("SELECT image FROM menu_items WHERE id = $id");
if ($row = $result->fetch_assoc()) {
    $currentImage = $row['image'];
}
$image = $currentImage; // Keep existing image by default

// Handle new image upload
if (!empty($_FILES['image']['name'])) {
    $target_dir = "./uploads/menu/";
    if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
    
    $fileName = time() . '_' . basename($_FILES["image"]["name"]);
    $target_file = $target_dir . $fileName;
    
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        $image = "uploads/menu/" . $fileName;
    }
}

$stmt = $conn->prepare("UPDATE menu_items SET category_id=?, name=?, price=?, description=?, image=?, alt=? WHERE id=?");
$stmt->bind_param("isdsssi", $category_id, $name, $price, $description, $image, $alt, $id);
$success = $stmt->execute();

if ($success) {
    echo json_encode(["success" => true, "message" => "Item updated successfully"]);
} else {
    http_response_code(500);
    echo json_encode(["success" => false, "error" => "Failed to update item: " . $stmt->error]);
}

$stmt->close();
