<?php
// edit_article.php - Formular zum Bearbeiten eines vorhandenen Artikels
// FINALE KORREKTUR: Alle besprochenen Fehler behoben und Komponente-Logik korrekt implementiert.
// KORREKTUR 2: SSL-Verifizierung und @-Fehlerunterdrückung korrigiert.

$page_title = "Artikel bearbeiten";

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

require_once 'db_connect.php';
require_once 'household_actions.php';
require_once 'header.php';

$current_user_id = $_SESSION['user_id'];
$message = '';
$article_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$article_data = null;
$can_edit = false;

$name = ''; $weight_grams = ''; $category_id = null; $consumable = 0; $quantity_owned = 1;
$product_url = ''; $manufacturer_id = null; $product_designation = '';
$storage_location_id = null;
$parent_article_id = null;

$display_current_image_path = 'assets/images/keinbild.png';
$display_image_url_in_input = '';
$is_local_uploaded_image = false;
$upload_dir = 'uploads/images/';
if (!is_dir($upload_dir)) { @mkdir($upload_dir, 0777, true); }

function save_image_from_url($url, $upload_dir) {
    // KORREKTUR: Unsichere SSL-Optionen entfernt, @-Operator entfernt
    $context_options = ["http" => ["header" => "User-Agent: Mozilla/5.0\r\n", "timeout" => 10]];
    $context = stream_context_create($context_options);

    // Fehlerbehandlung für file_get_contents
    $image_data = file_get_contents($url, false, $context);
    if ($image_data === false) { 
        return [false, "Bild konnte von der URL nicht heruntergeladen werden. Überprüfen Sie den Link und die Erreichbarkeit."]; 
    }

    // Fehlerbehandlung für getimagesizefromstring
    $image_info = getimagesizefromstring($image_data);
    if ($image_info === false) { 
        return [false, "Die angegebene URL führt nicht zu einem gültigen Bild."]; 
    }
    
    $allowed_mime_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($image_info['mime'], $allowed_mime_types)) { 
        return [false, "Nicht unterstützter Bildtyp: " . htmlspecialchars($image_info['mime'])]; 
    }

    $extension = image_type_to_extension($image_info[2], false);
    $unique_file_name = uniqid('img_url_', true) . '.' . $extension;
    $destination = $upload_dir . $unique_file_name;

    if (file_put_contents($destination, $image_data)) { 
        return [true, $destination]; 
    }

    return [false, "Bild konnte nicht auf dem Server gespeichert werden."];
}

function save_image_from_base64($base64_string, $upload_dir) {
    if (preg_match('/^data:image\/(\w+);base64,/', $base64_string, $type)) {
        $data = substr($base64_string, strpos($base64_string, ',') + 1);
        $type = strtolower($type[1]);
        if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) { return [false, "Nicht unterstützter Bildtyp."]; }
        $data = base64_decode($data);
        if ($data === false) { return [false, "Base64-Dekodierung fehlgeschlagen."]; }
    } else { return [false, "Ungültiger Base64-String."]; }
    $unique_file_name = uniqid('img_paste_', true) . '.' . $type;
    $destination = $upload_dir . $unique_file_name;
    if (file_put_contents($destination, $data)) { return [true, $destination]; }
    return [false, "Bild konnte nicht gespeichert werden."];
}

$stmt_household_check = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_household_check->bind_param("i", $current_user_id);
$stmt_household_check->execute();
$household_id_for_user = $stmt_household_check->get_result()->fetch_assoc()['household_id'];
$stmt_household_check->close();

if ($article_id > 0) {
    $stmt_load_article = $conn->prepare("SELECT * FROM articles WHERE id = ?");
    if ($stmt_load_article) {
        $stmt_load_article->bind_param("i", $article_id);
        $stmt_load_article->execute();
        $result = $stmt_load_article->get_result();
        if ($result->num_rows == 1) {
            $article_data = $result->fetch_assoc();
            
            $is_owner = ($article_data['user_id'] == $current_user_id);
            $is_household_article = !empty($article_data['household_id']);
            $is_in_same_household = ($is_household_article && $article_data['household_id'] == $household_id_for_user);

            if ($is_owner || $is_in_same_household) {
                $can_edit = true;
            } else {
                $message = '<div class="alert alert-danger" role="alert">Sie sind nicht berechtigt, diesen Artikel zu bearbeiten.</div>';
                $article_data = null;
            }
        } else { $message = '<div class="alert alert-warning" role="alert">Artikel nicht gefunden.</div>'; }
        $stmt_load_article->close();
    }
}

if ($can_edit) {
    $name = $article_data['name'];
    $weight_grams = $article_data['weight_grams'];
    $quantity_owned = $article_data['quantity_owned'];
    $category_id = $article_data['category_id'];
    $consumable = $article_data['consumable'];
    $product_url = $article_data['product_url'] ?? '';
    $manufacturer_id = $article_data['manufacturer_id'];
    $product_designation = $article_data['product_designation'] ?? '';
    $storage_location_id = $article_data['storage_location_id'];
    $parent_article_id = $article_data['parent_article_id'];
    if (!empty($article_data['image_url'])) {
        $display_current_image_path = htmlspecialchars($article_data['image_url']);
        if (strpos($article_data['image_url'], $upload_dir) === 0) {
            $is_local_uploaded_image = true;
        } else {
            $display_image_url_in_input = htmlspecialchars($article_data['image_url']);
        }
    }

    $household_member_ids = [$current_user_id];
    if ($household_id_for_user) {
        $stmt_members = $conn->prepare("SELECT id FROM users WHERE household_id = ?");
        $stmt_members->bind_param("i", $household_id_for_user);
        $stmt_members->execute();
        $result_members = $stmt_members->get_result();
        while ($row = $result_members->fetch_assoc()) {
            if (!in_array($row['id'], $household_member_ids)) { $household_member_ids[] = $row['id']; }
        }
        $stmt_members->close();
    }
    $placeholders = implode(',', array_fill(0, count($household_member_ids), '?'));
    $types = str_repeat('i', count($household_member_ids));
    $stmt_cat_load = $conn->prepare("SELECT id, name FROM categories WHERE user_id IN ($placeholders) ORDER BY name ASC");
    $stmt_cat_load->bind_param($types, ...$household_member_ids);
    $stmt_cat_load->execute();
    $categories = $stmt_cat_load->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_cat_load->close();
    $stmt_man_load = $conn->prepare("SELECT id, name FROM manufacturers WHERE user_id IN ($placeholders) ORDER BY name ASC");
    $stmt_man_load->bind_param($types, ...$household_member_ids);
    $stmt_man_load->execute();
    $manufacturers = $stmt_man_load->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_man_load->close();
    $stmt_loc_load = $conn->prepare("SELECT id, name, parent_id FROM storage_locations WHERE user_id IN ($placeholders) ORDER BY parent_id, name");
    $stmt_loc_load->bind_param($types, ...$household_member_ids);
    $stmt_loc_load->execute();
    $all_locations = $stmt_loc_load->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_loc_load->close();
    $storage_locations_structured = [];
    foreach ($all_locations as $loc) { if ($loc['parent_id'] === NULL) { if (!isset($storage_locations_structured[$loc['id']])) { $storage_locations_structured[$loc['id']] = ['name' => $loc['name'], 'children' => []]; } } }
    foreach ($all_locations as $loc) { if ($loc['parent_id'] !== NULL && isset($storage_locations_structured[$loc['parent_id']])) { $storage_locations_structured[$loc['parent_id']]['children'][] = $loc; } }
    
    $stmt_parent_articles = $conn->prepare("SELECT a.id, a.name, m.name as manufacturer_name, a.product_designation FROM articles a LEFT JOIN manufacturers m ON a.manufacturer_id = m.id WHERE (a.user_id IN ($placeholders) OR a.household_id = ?) AND a.parent_article_id IS NULL AND a.id != ? ORDER BY a.name ASC");
    $all_parent_params = array_merge($household_member_ids, [$household_id_for_user, $article_id]);
    $all_parent_types = $types . 'ii';
    $stmt_parent_articles->bind_param($all_parent_types, ...$all_parent_params);
    $stmt_parent_articles->execute();
    $parent_articles = $stmt_parent_articles->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_parent_articles->close();
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && $can_edit) {
    $name = trim($_POST['name']);
    $weight_grams = intval($_POST['weight_grams']);
    $consumable = isset($_POST['consumable']) ? 1 : 0;
    $quantity_owned = ($consumable == 1) ? 1 : intval($_POST['quantity_owned']);
    $product_url_for_db = !empty(trim($_POST['product_url'])) ? trim($_POST['product_url']) : NULL;
    $product_designation_for_db = !empty(trim($_POST['product_designation'])) ? trim($_POST['product_designation']) : NULL;
    $pasted_image_data = $_POST['pasted_image_data'] ?? '';
    $image_url_from_input = trim($_POST['image_url']);
    $is_household_item = isset($_POST['is_household_item']) && $household_id_for_user ? $household_id_for_user : NULL;
    $storage_location_id = !empty($_POST['storage_location_id']) ? intval($_POST['storage_location_id']) : NULL;
    $parent_article_id = !empty($_POST['parent_article_id']) ? intval($_POST['parent_article_id']) : NULL;

    if (isset($_POST['manufacturer_id']) && $_POST['manufacturer_id'] === 'new') {
        $new_manufacturer_name = trim($_POST['new_manufacturer_name']);
        if (!empty($new_manufacturer_name)) {
            $stmt_man = $conn->prepare("INSERT INTO manufacturers (name, user_id) VALUES (?, ?)");
            $stmt_man->bind_param("si", $new_manufacturer_name, $current_user_id);
            if ($stmt_man->execute()) { $manufacturer_id = $conn->insert_id; }
            $stmt_man->close();
        } else { $manufacturer_id = NULL; }
    } else { $manufacturer_id = !empty($_POST['manufacturer_id']) ? intval($_POST['manufacturer_id']) : NULL; }
    
    if (isset($_POST['category_id']) && $_POST['category_id'] === 'new') {
        $new_category_name = trim($_POST['new_category_name']);
        if (!empty($new_category_name)) {
            $stmt_cat = $conn->prepare("INSERT INTO categories (name, user_id) VALUES (?, ?)");
            $stmt_cat->bind_param("si", $new_category_name, $current_user_id);
            if($stmt_cat->execute()){ $category_id = $conn->insert_id; }
            $stmt_cat->close();
        } else { $category_id = NULL; }
    } else { $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : NULL; }
    
    $image_url_for_db = $article_data['image_url'];
    $image_error = '';
    function delete_old_image_if_local($article_data, $upload_dir) {
        if (!empty($article_data['image_url']) && strpos($article_data['image_url'], $upload_dir) === 0 && file_exists($article_data['image_url'])) {
            @unlink($article_data['image_url']);
        }
    }
    if (isset($_POST['delete_image_checkbox'])) {
        delete_old_image_if_local($article_data, $upload_dir);
        $image_url_for_db = NULL;
    }
    elseif (!empty($pasted_image_data)) {
        delete_old_image_if_local($article_data, $upload_dir);
        list($success, $result) = save_image_from_base64($pasted_image_data, $upload_dir);
        if ($success) { $image_url_for_db = $result; } else { $image_error = $result; }
    }
    elseif (isset($_FILES['image_file']) && $_FILES['image_file']['error'] == UPLOAD_ERR_OK) {
        delete_old_image_if_local($article_data, $upload_dir);
        $unique_file_name = uniqid('img_', true) . '.' . strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
        $destination_path = $upload_dir . $unique_file_name;
        if (move_uploaded_file($_FILES['image_file']['tmp_name'], $destination_path)) {
            $image_url_for_db = $destination_path;
        } else { $image_error = "Fehler beim Verschieben der hochgeladenen Datei."; }
    }
    elseif (!empty($image_url_from_input) && $image_url_from_input !== $display_image_url_in_input) {
        delete_old_image_if_local($article_data, $upload_dir);
        list($success, $result) = save_image_from_url($image_url_from_input, $upload_dir);
        if ($success) { $image_url_for_db = $result; } else { $image_error = $result; }
    }
    if (!empty($image_error)) {
        $message .= '<div class="alert alert-warning" role="alert">Bild-Fehler: ' . htmlspecialchars($image_error) . ' Der Artikel wurde trotzdem aktualisiert.</div>';
    }
    if (empty($name) || $weight_grams < 0) {
        $message .= '<div class="alert alert-danger" role="alert">Name und Gewicht sind Pflichtfelder und das Gewicht muss positiv sein.</div>';
    } else {
        $stmt_update = $conn->prepare("UPDATE articles SET name = ?, weight_grams = ?, quantity_owned = ?, category_id = ?, consumable = ?, image_url = ?, product_url = ?, manufacturer_id = ?, product_designation = ?, household_id = ?, storage_location_id = ?, parent_article_id = ? WHERE id = ?");
        if ($stmt_update) {
            $stmt_update->bind_param("siiisssisiiii", $name, $weight_grams, $quantity_owned, $category_id, $consumable, $image_url_for_db, $product_url_for_db, $manufacturer_id, $product_designation_for_db, $is_household_item, $storage_location_id, $parent_article_id, $article_id);
            if ($stmt_update->execute()) {
                if ($household_id_for_user) {
                    $log_message = htmlspecialchars($_SESSION['username']) . " hat den Artikel '" . htmlspecialchars($name) . "' bearbeitet.";
                    log_household_action($conn, $household_id_for_user, $current_user_id, $log_message);
                }
                $message .= '<div class="alert alert-success" role="alert">Artikel erfolgreich aktualisiert!</div>';
                echo "<script>setTimeout(() => window.location.href = 'edit_article.php?id=$article_id', 1000);</script>";
            } else {
                $message .= '<div class="alert alert-danger" role="alert">Fehler beim Aktualisieren: ' . $stmt_update->error . '</div>';
            }
            $stmt_update->close();
        }
    }
}
$conn->close();
?>

<!-- Tom Select CSS/JS -->
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.bootstrap5.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>

<!-- Tom Select CSS/JS -->
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.bootstrap5.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0"><i class="fas fa-edit me-2"></i>Artikel bearbeiten</h2>
        <a href="articles.php" class="btn btn-sm btn-outline-light"><i class="fas fa-arrow-left me-2"></i>Zur Übersicht</a>
    </div>
    <div class="card-body p-4">
        <?php if(!empty($message)) echo $message; ?>
        <?php if ($article_data): ?>
        <form action="edit_article.php?id=<?php echo htmlspecialchars($article_id); ?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="pasted_image_data" id="pasted_image_data">
            <div class="row g-4">
                <div class="col-lg-7 d-flex flex-column">
                    <div class="card section-card mb-4">
                        <div class="card-header"><h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Stammdaten</h5></div>
                        <div class="card-body">
                            <div class="mb-3"><label for="name" class="form-label">Artikelname*</label><input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($name); ?>" required></div>
                            <div class="row">
                                <div class="col-md-6 mb-3"><label for="manufacturer_id" class="form-label">Hersteller</label><select class="form-select" id="manufacturer_id" name="manufacturer_id"><option value="">-- Kein Hersteller --</option><option value="new">-- Neuen Hersteller hinzufügen --</option><?php foreach ($manufacturers as $man): ?><option value="<?php echo htmlspecialchars($man['id']); ?>" <?php if ($manufacturer_id == $man['id']) echo 'selected'; ?>><?php echo htmlspecialchars($man['name']); ?></option><?php endforeach; ?></select><div id="new_manufacturer_container" class="mt-2" style="display: none;"><input type="text" class="form-control" name="new_manufacturer_name" placeholder="Name des neuen Herstellers"></div></div>
                                <div class="col-md-6 mb-3"><label for="product_designation" class="form-label">Produktbezeichnung / Modell</label><input type="text" class="form-control" id="product_designation" name="product_designation" value="<?php echo htmlspecialchars($product_designation); ?>" placeholder="z.B. Forclaz MT500"></div>
                            </div>
                            <div class="mb-3">
                                <label for="parent_article_id" class="form-label">Ist Komponente von (optional)</label>
                                <select class="form-select" id="parent_article_id" name="parent_article_id">
                                    <option value="">-- Kein Hauptartikel --</option>
                                    <?php foreach ($parent_articles as $parent): 
                                        $parent_details = $parent['manufacturer_name'] ? htmlspecialchars($parent['manufacturer_name']) . ' - ' : '';
                                        $parent_details .= htmlspecialchars($parent['product_designation'] ?? '');
                                    ?>
                                        <option value="<?php echo $parent['id']; ?>" <?php if($parent_article_id == $parent['id']) echo 'selected'; ?>><?php echo htmlspecialchars($parent['name'] . ' (' . $parent_details . ')'); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="card section-card">
                         <div class="card-header"><h5 class="mb-0"><i class="fas fa-cogs me-2"></i>Eigenschaften & Ort</h5></div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3"><label for="weight_grams" class="form-label">Gewicht*</label><div class="input-group"><span class="input-group-text"><i class="fas fa-weight-hanging"></i></span><input type="number" class="form-control" id="weight_grams" name="weight_grams" value="<?php echo htmlspecialchars($weight_grams); ?>" required min="0"><span class="input-group-text">g</span></div></div>
                                <div class="col-md-6 mb-3"><label for="quantity_owned" class="form-label">Anzahl im Besitz</label><input type="number" class="form-control" id="quantity_owned" name="quantity_owned" value="<?php echo htmlspecialchars($quantity_owned); ?>" min="1" <?php if($consumable) echo 'disabled'; ?>></div>
                                <div class="col-12 mb-3"><label for="category_id" class="form-label">Kategorie</label><select class="form-select" id="category_id" name="category_id"><option value="">-- Keine Kategorie --</option><option value="new">-- Neue Kategorie hinzufügen --</option><?php foreach ($categories as $cat): ?><option value="<?php echo htmlspecialchars($cat['id']); ?>" <?php if ($category_id == $cat['id']) echo 'selected'; ?>><?php echo htmlspecialchars($cat['name']); ?></option><?php endforeach; ?></select><div id="new_category_container" class="mt-2" style="display: none;"><input type="text" class="form-control" name="new_category_name" placeholder="Name der neuen Kategorie"></div></div>
                                <div class="col-12 mb-3"><label for="storage_location_id" class="form-label">Lagerort</label><select class="form-select" id="storage_location_id" name="storage_location_id"><option value="">-- Kein fester Ort --</option><?php foreach ($storage_locations_structured as $loc1_id => $loc1_data): ?><optgroup label="<?php echo htmlspecialchars($loc1_data['name']); ?>"><?php foreach ($loc1_data['children'] as $loc2): ?><option value="<?php echo $loc2['id']; ?>" <?php if ($storage_location_id == $loc2['id']) echo 'selected'; ?>><?php echo htmlspecialchars($loc2['name']); ?></option><?php endforeach; ?></optgroup><?php endforeach; ?></select></div>
                            </div>
                            <hr class="my-3">
                            <div class="form-check form-switch mb-2"><input class="form-check-input" type="checkbox" role="switch" id="consumable" name="consumable" value="1" <?php echo $consumable ? 'checked' : ''; ?>><label class="form-check-label" for="consumable">Verbrauchsartikel (unbegrenzte Anzahl)</label></div>
                            <?php if ($household_id_for_user): ?>
                            <div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" id="is_household_item" name="is_household_item" value="1" <?php echo !empty($article_data['household_id']) ? 'checked' : ''; ?>><label class="form-check-label" for="is_household_item">Für den gesamten Haushalt freigeben</label></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="col-lg-5">
                    <div class="card section-card h-100">
                        <div class="card-header"><h5 class="mb-0"><i class="fas fa-image me-2"></i>Bild & Produktseite</h5></div>
                        <div class="card-body d-flex flex-column">
                            <div class="mb-3"><label for="product_url" class="form-label">Produktseite (URL)</label><input type="url" class="form-control" id="product_url" name="product_url" value="<?php echo htmlspecialchars($product_url); ?>" placeholder="https://..."></div>
                            <div class="mb-3"><label for="image_file" class="form-label">1. Neues Bild hochladen</label><input class="form-control" type="file" id="image_file" name="image_file" accept="image/*"></div>
                            <div class="mb-3"><label for="image_url" class="form-label">2. ODER neue Bild-URL</label><input type="url" class="form-control" id="image_url" name="image_url" value="<?php echo $display_image_url_in_input; ?>" placeholder="https://..."></div>
                            <div class="mb-3"><label class="form-label">3. ODER Bild einfügen (Strg+V)</label><div id="pasteArea" class="paste-area"><i class="fas fa-paste"></i> Hier klicken & einfügen</div></div>
                            <div class="text-center mt-auto">
                                <label class="form-label d-block">Vorschau</label>
                                <img id="imagePreview" src="<?php echo $display_current_image_path; ?>" alt="Vorschau" class="mb-2">
                                <?php if (!empty($article_data['image_url'])): ?>
                                <div class="form-check"><input type="checkbox" class="form-check-input" id="deleteImageCheckbox" name="delete_image_checkbox" value="1"><label class="form-check-label text-danger" for="deleteImageCheckbox">Aktuelles Bild löschen</label></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="d-flex justify-content-start align-items-center mt-4 border-top pt-4">
                <button type="submit" class="btn btn-primary me-3"><i class="fas fa-save me-2"></i>Änderungen speichern</button>
                <a href="articles.php" class="btn btn-secondary">Abbrechen</a>
            </div>
        </form>
        <?php elseif(empty($message)): ?>
             <div class="alert alert-warning">Artikel konnte nicht geladen werden.</div>
        <?php endif; ?>
    </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    function setupAddNewOption(selectId, containerId) {
        const select = document.getElementById(selectId);
        const container = document.getElementById(containerId);
        if (!select || !container) return;
        const input = container.querySelector('input');
        function toggle() {
            const isNew = select.value === 'new';
            container.style.display = isNew ? 'block' : 'none';
            if (input) input.required = isNew;
            if (!isNew && input) { input.value = ''; }
        }
        select.addEventListener('change', toggle);
        toggle();
    }
    setupAddNewOption('manufacturer_id', 'new_manufacturer_container');
    setupAddNewOption('category_id', 'new_category_container');
    const imageFileInput = document.getElementById('image_file');
    const imageUrlInput = document.getElementById('image_url');
    const imagePreview = document.getElementById('imagePreview');
    const pasteArea = document.getElementById('pasteArea');
    const pastedImageDataInput = document.getElementById('pasted_image_data');
    const deleteCheckbox = document.getElementById('deleteImageCheckbox');
    const originalImageSrc = imagePreview.src;
    function clearOtherImageInputs(source) {
        if (source !== 'file' && imageFileInput) imageFileInput.value = '';
        if (source !== 'url' && imageUrlInput) imageUrlInput.value = '';
        if (source !== 'paste' && pastedImageDataInput) pastedImageDataInput.value = '';
        if (deleteCheckbox) deleteCheckbox.checked = false;
    }
    if(imageFileInput) {
        imageFileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = (e) => { imagePreview.src = e.target.result; };
                reader.readAsDataURL(this.files[0]);
                clearOtherImageInputs('file');
            }
        });
    }
    if (pasteArea) {
        pasteArea.addEventListener('paste', function(e) {
            e.preventDefault();
            const items = (e.clipboardData || window.clipboardData).items;
            for (const item of items) {
                if (item.type.indexOf('image') === 0) {
                    const blob = item.getAsFile();
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        imagePreview.src = event.target.result;
                        pastedImageDataInput.value = event.target.result;
                        clearOtherImageInputs('paste');
                    };
                    reader.readAsDataURL(blob);
                }
            }
        });
        pasteArea.addEventListener('dragover', (e) => { e.preventDefault(); pasteArea.classList.add('hover'); });
        pasteArea.addEventListener('dragleave', () => pasteArea.classList.remove('hover'));
        pasteArea.addEventListener('drop', (e) => { e.preventDefault(); pasteArea.classList.remove('hover'); });
    }
    if(deleteCheckbox) {
        deleteCheckbox.addEventListener('change', function() {
            if(this.checked) {
                imagePreview.src = 'assets/images/keinbild.png';
                clearOtherImageInputs('delete');
            } else {
                imagePreview.src = originalImageSrc;
            }
        });
    }
    const consumableCheckbox = document.getElementById('consumable');
    const quantityOwnedInput = document.getElementById('quantity_owned');
    consumableCheckbox.addEventListener('change', function() {
        if (this.checked) {
            quantityOwnedInput.disabled = true;
            quantityOwnedInput.value = 1;
        } else {
            quantityOwnedInput.disabled = false;
        }
    });

    // Initialize Tom Select
    const tsOptions = {
        create: false,
        sortField: { field: "text", direction: "asc" },
        onChange: function(value) {
            const event = new Event('change');
            this.input.dispatchEvent(event);
        }
    };
    
    if(document.getElementById('manufacturer_id')) new TomSelect('#manufacturer_id', tsOptions);
    if(document.getElementById('category_id')) new TomSelect('#category_id', tsOptions);
    if(document.getElementById('parent_article_id')) new TomSelect('#parent_article_id', tsOptions);
    if(document.getElementById('storage_location_id')) new TomSelect('#storage_location_id', tsOptions);
});
</script>
<?php require_once 'footer.php'; ?>
