<?php
// add_article.php - Formular zum Hinzufügen eines neuen Artikels
// FINALE, VOLLSTÄNDIGE VERSION mit Bilder-Bibliothek Modal

$page_title = "Neuen Artikel hinzufügen";

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 = '';

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

// Lade Haushalts-ID und Mitglieder-IDs
$stmt_household = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_household->bind_param("i", $current_user_id);
$stmt_household->execute();
$household_id_for_user = $stmt_household->get_result()->fetch_assoc()['household_id'];
$stmt_household->close();

$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));

// Lade Kategorien
$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();

// Lade Hersteller
$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();

// Lade Lagerorte
$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();

// Lade Eltern-Artikel
$all_parent_params = array_merge($household_member_ids, [$household_id_for_user]);
$all_parent_types = $types . 'i';
$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 ORDER BY a.name ASC");
$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();

// Lade ALLE Bilder (für Auswahl im Modal) - Limit auf 500 für Performance, aber scrollbar
$stmt_imgs = $conn->prepare("SELECT DISTINCT image_url FROM articles WHERE user_id IN ($placeholders) AND image_url IS NOT NULL AND image_url != '' AND image_url != '0' ORDER BY created_at DESC LIMIT 500");
$stmt_imgs->bind_param($types, ...$household_member_ids);
$stmt_imgs->execute();
$all_images = $stmt_imgs->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_imgs->close();

// Strukturierung Lagerorte
$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; } }

$upload_dir = 'uploads/images/';
if (!is_dir($upload_dir)) { @mkdir($upload_dir, 0777, true); }

function save_image_from_url($url, $upload_dir) {
    $context_options = ["http" => ["header" => "User-Agent: Mozilla/5.0\r\n", "timeout" => 10]];
    $context = stream_context_create($context_options);
    $image_data = @file_get_contents($url, false, $context);
    if ($image_data === false) return [false, "Bild-Download fehlgeschlagen."];
    $image_info = @getimagesizefromstring($image_data);
    if ($image_info === false) return [false, "Ungültiges Bild."];
    $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($image_info['mime'], $allowed)) return [false, "Format nicht unterstützt."];
    $ext = image_type_to_extension($image_info[2], false);
    $name = uniqid('img_url_', true) . '.' . $ext;
    if (file_put_contents($upload_dir . $name, $image_data)) return [true, $upload_dir . $name];
    return [false, "Speicherfehler."];
}

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, "Format nicht unterstützt."];
        $data = base64_decode($data);
        if ($data === false) return [false, "Dekodierfehler."];
        $name = uniqid('img_paste_', true) . '.' . $type;
        if (file_put_contents($upload_dir . $name, $data)) return [true, $upload_dir . $name];
    }
    return [false, "Ungültiges Base64."];
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $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']);
    $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;
    $image_url_from_input = trim($_POST['image_url']);
    $product_url = trim($_POST['product_url']);
    $product_designation = trim($_POST['product_designation']);
    $pasted_image_data = $_POST['pasted_image_data'] ?? '';
    $selected_existing_image = trim($_POST['selected_existing_image'] ?? '');

    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 = !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 = !empty($_POST['category_id']) ? intval($_POST['category_id']) : NULL; }
    
    $image_url_for_db = NULL;
    $image_error = '';

    if (!empty($pasted_image_data)) {
        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) {
        $unique_file_name = uniqid('img_', true) . '.' . strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
        $destination = $upload_dir . $unique_file_name;
        if (move_uploaded_file($_FILES['image_file']['tmp_name'], $destination)) {
            $image_url_for_db = $destination;
        } else { $image_error = "Fehler beim Verschieben der hochgeladenen Datei."; }
    }
    elseif (!empty($selected_existing_image)) {
        // User chose an existing image
        $image_url_for_db = $selected_existing_image;
    }
    elseif (!empty($image_url_from_input)) {
        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 ohne Bild gespeichert.</div>';
    }

    $product_url_for_db = !empty($product_url) ? $product_url : NULL;
    $product_designation_for_db = !empty($product_designation) ? $product_designation : NULL;
    
    if (empty($name) || $weight_grams < 0) {
        $message = '<div class="alert alert-danger" role="alert">Bitte geben Sie einen Namen und ein gültiges, nicht-negatives Gewicht an.</div>';
    } else {
        $stmt_insert_article = $conn->prepare("INSERT INTO articles (user_id, household_id, name, weight_grams, quantity_owned, category_id, consumable, image_url, product_url, manufacturer_id, product_designation, storage_location_id, parent_article_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt_insert_article) {
            $stmt_insert_article->bind_param("iisiiisssisii", $current_user_id, $is_household_item, $name, $weight_grams, $quantity_owned, $category_id, $consumable, $image_url_for_db, $product_url_for_db, $manufacturer_id, $product_designation_for_db, $storage_location_id, $parent_article_id);
            if ($stmt_insert_article->execute()) {
                if ($household_id_for_user) {
                    $log_message = htmlspecialchars($_SESSION['username']) . " hat den Artikel '" . htmlspecialchars($name) . "' hinzugefügt.";
                    log_household_action($conn, $household_id_for_user, $current_user_id, $log_message);
                }
                $message .= '<div class="alert alert-success" role="alert">Artikel "' . htmlspecialchars($name) . '" erfolgreich hinzugefügt! <a href="articles.php" class="alert-link">Zurück zur Übersicht</a>.</div>';
                $name = $weight_grams = $image_url = $product_url = $product_designation = '';
                $consumable = 0; $quantity_owned = 1; $category_id = $manufacturer_id = $storage_location_id = $parent_article_id = null;
            } else {
                $message = '<div class="alert alert-danger" role="alert">Fehler beim Hinzufügen des Artikels: ' . $stmt_insert_article->error . '</div>';
            }
            $stmt_insert_article->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>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0"><i class="fas fa-plus-circle me-2"></i>Neuen Artikel erstellen</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; ?>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
             <input type="hidden" name="pasted_image_data" id="pasted_image_data">
             <input type="hidden" name="selected_existing_image" id="selected_existing_image">
            <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 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 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"></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 --</option><option value="new">-- Neue hinzufügen --</option><?php foreach ($categories as $cat): ?><option value="<?php echo htmlspecialchars($cat['id']); ?>"><?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 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"><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"><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>
                            
                            <!-- New: Button to open modal -->
                            <?php if(!empty($all_images)): ?>
                                <div class="mb-3">
                                    <button type="button" class="btn btn-outline-secondary w-100" data-bs-toggle="modal" data-bs-target="#imageLibraryModal">
                                        <i class="fas fa-images me-2"></i>Aus vorhandenen Bildern wählen
                                    </button>
                                </div>
                            <?php endif; ?>

                            <div class="mb-3"><label for="image_file" class="form-label">1. 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 Bild-URL angeben</label><input type="url" class="form-control" id="image_url" name="image_url" 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="assets/images/keinbild.png" class="mb-2"></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-plus-circle me-2"></i>Artikel erstellen</button>
                <a href="articles.php" class="btn btn-secondary">Abbrechen</a>
            </div>
        </form>
    </div>
</div>

<!-- Image Library Modal -->
<div class="modal fade" id="imageLibraryModal" tabindex="-1" aria-labelledby="imageLibraryModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="imageLibraryModalLabel">Bildbibliothek</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>
      <div class="modal-body bg-light">
        <p class="small text-muted mb-2">Wähle ein Bild aus deinem bisherigen Bestand:</p>
        <div class="d-flex flex-wrap gap-2 justify-content-center">
            <?php if(!empty($all_images)): ?>
                <?php foreach($all_images as $img): ?>
                    <div class="library-image-container" onclick="selectLibraryImage('<?php echo htmlspecialchars($img['image_url']); ?>')">
                        <img src="<?php echo htmlspecialchars($img['image_url']); ?>" loading="lazy">
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="text-muted">Keine Bilder gefunden.</p>
            <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<style>
.library-image-container {
    width: 100px;
    height: 100px;
    border: 2px solid transparent;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    background: white;
    transition: transform 0.1s, border-color 0.1s;
}
.library-image-container:hover {
    border-color: var(--color-primary);
    transform: scale(1.05);
    z-index: 10;
}
.library-image-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</style>

<script>
// Global function for onclick event in modal
function selectLibraryImage(url) {
    const imagePreview = document.getElementById('imagePreview');
    const selectedExistingInput = document.getElementById('selected_existing_image');
    const imageFileInput = document.getElementById('image_file');
    const imageUrlInput = document.getElementById('image_url');
    const pastedImageDataInput = document.getElementById('pasted_image_data');
    
    // Update Preview & Input
    imagePreview.src = url;
    selectedExistingInput.value = url;
    
    // Clear other inputs
    imageFileInput.value = '';
    imageUrlInput.value = '';
    pastedImageDataInput.value = '';
    
    // Close Modal
    const modalEl = document.getElementById('imageLibraryModal');
    const modal = bootstrap.Modal.getInstance(modalEl);
    modal.hide();
}

document.addEventListener('DOMContentLoaded', function() {
    function setupAddNewOption(selectId, containerId) {
        const select = document.getElementById(selectId);
        const container = document.getElementById(containerId);
        if (!select || !container) return;
        
        function toggle() {
            const isNew = select.value === 'new';
            container.style.display = isNew ? 'block' : 'none';
            const input = container.querySelector('input');
            if (input) input.required = isNew;
            if (!isNew && input) { input.value = ''; }
        }
        select.addEventListener('change', toggle);
        toggle();
        return toggle;
    }
    const toggleMan = setupAddNewOption('manufacturer_id', 'new_manufacturer_container');
    const toggleCat = 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 selectedExistingInput = document.getElementById('selected_existing_image');

    function clearOtherImageInputs(source) {
        if (source !== 'file') imageFileInput.value = '';
        if (source !== 'url') imageUrlInput.value = '';
        if (source !== 'paste') pastedImageDataInput.value = '';
        if (source !== 'existing') selectedExistingInput.value = '';
    }

    if(imageFileInput) {
        imageFileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(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 = function(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'); });
        pasteArea.setAttribute('tabindex', '0');
        pasteArea.addEventListener('click', () => pasteArea.focus());
    }
    
    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 tsOptionsBase = {
        create: false,
        sortField: { field: "text", direction: "asc" }
    };
    
    if(document.getElementById('manufacturer_id')) {
        new TomSelect('#manufacturer_id', {
            ...tsOptionsBase,
            onChange: function(value) { if(toggleMan) toggleMan(); }
        });
    }
    if(document.getElementById('category_id')) {
         new TomSelect('#category_id', {
            ...tsOptionsBase,
            onChange: function(value) { if(toggleCat) toggleCat(); }
        });
    }
    if(document.getElementById('parent_article_id')) new TomSelect('#parent_article_id', tsOptionsBase);
    if(document.getElementById('storage_location_id')) new TomSelect('#storage_location_id', tsOptionsBase);
});
</script>
<?php require_once 'footer.php'; ?>