<?php
// Check for POST size limit exceeded immediately
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0) {
    $max_size = ini_get('post_max_size');
    die("Fehler: Die hochgeladene Datei überschreitet das Server-Limit von $max_size. Bitte wählen Sie ein kleineres Bild.");
}

// edit_backpack.php - Erstellen und Bearbeiten von Rucksäcken und Fächern
$page_title = "Rucksack bearbeiten";
require_once 'db_connect.php';

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

$user_id = $_SESSION['user_id'];
$backpack_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$backpack = null;
$compartments = [];
$message = '';
$image_url = '';
$product_url = '';

// AUTO-MIGRATION: Check columns
$check_col = $conn->query("SHOW COLUMNS FROM backpacks LIKE 'product_url'");
if ($check_col && $check_col->num_rows == 0) {
    $conn->query("ALTER TABLE backpacks ADD COLUMN product_url VARCHAR(255) DEFAULT NULL AFTER image_url");
}
$check_col_cat = $conn->query("SHOW COLUMNS FROM backpacks LIKE 'category_id'");
if ($check_col_cat && $check_col_cat->num_rows == 0) {
    $conn->query("ALTER TABLE backpacks ADD COLUMN category_id INT DEFAULT NULL");
    $conn->query("ALTER TABLE backpacks ADD CONSTRAINT fk_bp_category FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL");
}
$check_col_c = $conn->query("SHOW COLUMNS FROM backpack_compartments LIKE 'linked_article_id'");
if ($check_col_c && $check_col_c->num_rows == 0) {
    $conn->query("ALTER TABLE backpack_compartments ADD COLUMN linked_article_id INT DEFAULT NULL");
    $conn->query("ALTER TABLE backpack_compartments ADD CONSTRAINT fk_bc_article FOREIGN KEY (linked_article_id) REFERENCES articles(id) ON DELETE SET NULL");
}

// Check Household
$household_id = null;
$stmt_hh = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_hh->bind_param("i", $user_id);
$stmt_hh->execute();
$res_hh = $stmt_hh->get_result();
if ($row = $res_hh->fetch_assoc()) {
    $household_id = $row['household_id'];
}

// Image Upload Config
$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('bp_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('bp_paste_', true) . '.' . $type;
        if (file_put_contents($upload_dir . $name, $data)) return [true, $upload_dir . $name];
    }
    return [false, "Ungültiges Base64."];
}

// Load existing data
if ($backpack_id > 0) {
    $stmt = $conn->prepare("SELECT * FROM backpacks WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $backpack_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $backpack = $result->fetch_assoc();
        $image_url = $backpack['image_url'];
        $product_url = $backpack['product_url'] ?? '';
        
        // Load Compartments
        $stmt_c = $conn->prepare("SELECT * FROM backpack_compartments WHERE backpack_id = ? ORDER BY sort_order ASC");
        $stmt_c->bind_param("i", $backpack_id);
        $stmt_c->execute();
        $res_c = $stmt_c->get_result();
        while ($row = $res_c->fetch_assoc()) {
            $compartments[] = $row;
        }
    } else {
        $message = '<div class="alert alert-danger">Rucksack nicht gefunden oder keine Berechtigung.</div>';
        $backpack_id = 0; // Reset to create mode
    }
}

// Load Manufacturers & Categories
$hh_ids = [$user_id];
if ($household_id) {
    $stmt_hhm = $conn->prepare("SELECT id FROM users WHERE household_id = ?");
    $stmt_hhm->bind_param("i", $household_id);
    $stmt_hhm->execute();
    $res_hhm = $stmt_hhm->get_result();
    while($r = $res_hhm->fetch_assoc()) $hh_ids[] = $r['id'];
}
$placeholders = implode(',', array_fill(0, count($hh_ids), '?'));
$types_hh = str_repeat('i', count($hh_ids));

// Manufacturers
$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_hh, ...$hh_ids);
$stmt_man_load->execute();
$manufacturers = $stmt_man_load->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_man_load->close();

// Categories
$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_hh, ...$hh_ids);
$stmt_cat_load->execute();
$categories = $stmt_cat_load->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_cat_load->close();

// Load Articles for Linked Compartments
$stmt_arts = $conn->prepare("SELECT id, name, weight_grams, image_url FROM articles WHERE user_id IN ($placeholders) OR household_id = ? ORDER BY name ASC");
$params_arts = array_merge($hh_ids, [$household_id ?: 0]); 
$types_arts = $types_hh . 'i';
$stmt_arts->bind_param($types_arts, ...$params_arts);
$stmt_arts->execute();
$all_articles = $stmt_arts->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_arts->close();


// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = trim($_POST['name']);
    
    // Manufacturer Logic
    $manufacturer = '';
    if (isset($_POST['manufacturer_select'])) {
        if ($_POST['manufacturer_select'] === 'new') {
            $new_man = trim($_POST['new_manufacturer_name']);
            if (!empty($new_man)) {
                $stmt_check_man = $conn->prepare("SELECT id, name FROM manufacturers WHERE user_id = ? AND name = ?");
                $stmt_check_man->bind_param("is", $user_id, $new_man);
                $stmt_check_man->execute();
                $res_check = $stmt_check_man->get_result();
                
                if ($res_check->num_rows > 0) {
                    $manufacturer = $res_check->fetch_assoc()['name'];
                } else {
                    $stmt_new_man = $conn->prepare("INSERT INTO manufacturers (name, user_id) VALUES (?, ?)");
                    $stmt_new_man->bind_param("si", $new_man, $user_id);
                    $stmt_new_man->execute();
                    $manufacturer = $new_man;
                }
            }
        } else {
            $man_id = intval($_POST['manufacturer_select']);
            foreach ($manufacturers as $m) {
                if ($m['id'] == $man_id) {
                    $manufacturer = $m['name'];
                    break;
                }
            }
        }
    }

    $model = trim($_POST['model']);
    $weight = intval($_POST['weight_grams']);
    $volume = intval($_POST['volume_liters']);
    $share_household = isset($_POST['share_household']) ? 1 : 0;
    $product_url_input = trim($_POST['product_url'] ?? '');
    $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : NULL;
    
    $image_url_for_db = $image_url;
    $pasted_image = $_POST['pasted_image_data'] ?? '';
    $url_image = trim($_POST['image_url_input'] ?? '');
    
    if (!empty($pasted_image)) {
        list($ok, $res) = save_image_from_base64($pasted_image, $upload_dir);
        if ($ok) $image_url_for_db = $res;
    } elseif (isset($_FILES['image_file']) && $_FILES['image_file']['error'] == UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (in_array($ext, $allowed_exts)) {
            $name_file = uniqid('bp_img_', true) . '.' . $ext;
            if (move_uploaded_file($_FILES['image_file']['tmp_name'], $upload_dir . $name_file)) {
                $image_url_for_db = $upload_dir . $name_file;
            }
        }
    } elseif (!empty($url_image)) {
        list($ok, $res) = save_image_from_url($url_image, $upload_dir);
        if ($ok) $image_url_for_db = $res;
    }

    $final_household_id = ($share_household && $household_id) ? $household_id : NULL;

    if ($backpack_id > 0) {
        $stmt = $conn->prepare("UPDATE backpacks SET name=?, manufacturer=?, model=?, weight_grams=?, volume_liters=?, household_id=?, image_url=?, product_url=?, category_id=? WHERE id=? AND user_id=?");
        $stmt->bind_param("sssiisssiii", $name, $manufacturer, $model, $weight, $volume, $final_household_id, $image_url_for_db, $product_url_input, $category_id, $backpack_id, $user_id);
        $stmt->execute();
    } else {
        $stmt = $conn->prepare("INSERT INTO backpacks (user_id, household_id, name, manufacturer, model, weight_grams, volume_liters, image_url, product_url, category_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("iisssiissi", $user_id, $final_household_id, $name, $manufacturer, $model, $weight, $volume, $image_url_for_db, $product_url_input, $category_id);
        $stmt->execute();
        $backpack_id = $stmt->insert_id;
    }

    // Handle Compartments
    if (isset($_POST['comp_types'])) {
        $types = $_POST['comp_types'];
        $ids = $_POST['comp_ids'] ?? [];
        $names = $_POST['comp_names'] ?? [];
        $articles = $_POST['comp_articles'] ?? [];
        
        $existing_ids = [];
        if($backpack_id > 0){
             $stmt_check = $conn->prepare("SELECT id FROM backpack_compartments WHERE backpack_id = ?");
             $stmt_check->bind_param("i", $backpack_id);
             $stmt_check->execute();
             $res_check = $stmt_check->get_result();
             while($row = $res_check->fetch_assoc()) $existing_ids[] = $row['id'];
        }
        
        $kept_ids = [];

        for ($i = 0; $i < count($types); $i++) {
            $c_id = intval($ids[$i] ?? 0);
            $c_type = $types[$i];
            $c_name = '';
            $c_article_id = NULL;

            if ($c_type === 'article') {
                $c_article_id = intval($articles[$i] ?? 0);
                if ($c_article_id <= 0) continue; 
                foreach($all_articles as $art) {
                    if ($art['id'] == $c_article_id) {
                        $c_name = $art['name'];
                        break;
                    }
                }
            } else {
                $c_name = trim($names[$i] ?? '');
                if (empty($c_name)) continue;
            }

            if ($c_id > 0 && in_array($c_id, $existing_ids)) {
                $stmt_up = $conn->prepare("UPDATE backpack_compartments SET name = ?, sort_order = ?, linked_article_id = ? WHERE id = ?");
                $stmt_up->bind_param("siii", $c_name, $i, $c_article_id, $c_id);
                $stmt_up->execute();
                $kept_ids[] = $c_id;
            } else {
                $stmt_in = $conn->prepare("INSERT INTO backpack_compartments (backpack_id, name, sort_order, linked_article_id) VALUES (?, ?, ?, ?)");
                $stmt_in->bind_param("isii", $backpack_id, $c_name, $i, $c_article_id);
                $stmt_in->execute();
            }
        }

        foreach ($existing_ids as $ex_id) {
            if (!in_array($ex_id, $kept_ids)) {
                $conn->query("DELETE FROM backpack_compartments WHERE id = $ex_id");
            }
        }
    }

    header("Location: backpacks.php");
    exit;
}

require_once 'header.php';
?>

<!-- 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="container mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h3 class="h5 mb-0"><?php echo $backpack_id > 0 ? 'Rucksack bearbeiten' : 'Neuen Rucksack anlegen'; ?></h3>
                </div>
                <div class="card-body">
                    <?php echo $message; ?>
                    
                    <form method="post" id="backpackForm" enctype="multipart/form-data">
                        <input type="hidden" name="pasted_image_data" id="pasted_image_data">
                        
                        <div class="row g-3 mb-4">
                            <div class="col-md-8">
                                <div class="row g-3">
                                    <div class="col-md-12">
                                        <label class="form-label">Bezeichnung (Spitzname)</label>
                                        <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($backpack['name'] ?? ''); ?>" placeholder="z.B. Mein großer Trekker">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Hersteller</label>
                                        <select class="form-select" id="manufacturer_select" name="manufacturer_select">
                                            <option value="">-- Auswählen --</option>
                                            <option value="new">-- Neuen anlegen --</option>
                                            <?php 
                                            $current_man = $backpack['manufacturer'] ?? '';
                                            foreach ($manufacturers as $man): 
                                                $selected = ($man['name'] === $current_man) ? 'selected' : '';
                                            ?>
                                                <option value="<?php echo $man['id']; ?>" <?php 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" name="new_manufacturer_name" class="form-control form-control-sm" placeholder="Name des neuen Herstellers">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Kategorie</label>
                                        <select class="form-select" id="category_id" name="category_id">
                                            <option value="">-- Keine (Sonstiges) --</option>
                                            <?php 
                                            $current_cat = $backpack['category_id'] ?? 0;
                                            foreach ($categories as $cat): 
                                                $selected = ($cat['id'] == $current_cat) ? 'selected' : '';
                                            ?>
                                                <option value="<?php echo $cat['id']; ?>" <?php echo $selected; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Modell</label>
                                        <input type="text" name="model" class="form-control" value="<?php echo htmlspecialchars($backpack['model'] ?? ''); ?>">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Basis-Leergewicht (g)</label>
                                        <input type="number" name="weight_grams" class="form-control" value="<?php echo htmlspecialchars($backpack['weight_grams'] ?? 0); ?>" required>
                                        <div class="form-text small">Ohne Zusatztaschen.</div>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Volumen (Liter)</label>
                                        <input type="number" name="volume_liters" class="form-control" value="<?php echo htmlspecialchars($backpack['volume_liters'] ?? 0); ?>">
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Hersteller-Link (Produktseite)</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="fas fa-link"></i></span>
                                            <input type="url" name="product_url" class="form-control" value="<?php echo htmlspecialchars($product_url); ?>" placeholder="https://...">
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="share_household" name="share_household" <?php echo (!empty($backpack['household_id']) || $backpack_id == 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="share_household">Mit Haushalt teilen</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Bild</label>
                                <div class="card bg-light mb-2">
                                    <div class="card-body text-center p-2">
                                        <img id="imagePreview" src="<?php echo !empty($image_url) ? htmlspecialchars($image_url) : 'assets/images/keinbild.png'; ?>" class="img-fluid" style="max-height:150px; object-fit:contain;">
                                    </div>
                                </div>
                                <input type="file" name="image_file" id="image_file" class="form-control form-control-sm mb-2" accept="image/*">
                                <input type="text" name="image_url_input" id="image_url_input" class="form-control form-control-sm mb-2" placeholder="oder Bild-URL">
                                <div id="pasteArea" class="paste-area small py-2" style="border: 2px dashed #ccc; text-align:center; cursor:pointer;">Bild einfügen (Strg+V)</div>
                            </div>
                        </div>

                        <h5 class="border-bottom pb-2 mb-3">Fächer & Zusatztaschen</h5>
                        <div class="alert alert-light small">
                            Definiere hier die Bereiche deines Rucksacks. Du kannst einfache Text-Fächer (z.B. "Deckelfach") oder echte Artikel als Zusatztaschen (z.B. "Hüftgurttasche") hinzufügen. Das Gewicht von Zusatztaschen wird zum Rucksackgewicht addiert.
                        </div>

                        <div id="compartments-container">
                            <?php if (empty($compartments)): ?>
                                <!-- Defaults -->
                                <div class="compartment-row card mb-2">
                                    <div class="card-body p-2">
                                        <div class="input-group">
                                            <span class="input-group-text handle cursor-grab"><i class="fas fa-grip-lines text-muted"></i></span>
                                            <select class="form-select type-select" name="comp_types[]" style="max-width: 130px;">
                                                <option value="text">Standardfach</option>
                                                <option value="article">Zusatztasche</option>
                                            </select>
                                            
                                            <!-- Text Input -->
                                            <input type="text" name="comp_names[]" class="form-control name-input" value="Hauptfach" placeholder="Fachname">
                                            
                                            <!-- Article Select -->
                                            <div class="flex-grow-1 article-select-wrapper" style="display:none;">
                                                <select name="comp_articles[]" class="form-select article-select tom-select-init">
                                                    <option value="">Artikel wählen...</option>
                                                    <?php foreach($all_articles as $art): ?>
                                                        <option value="<?php echo $art['id']; ?>" data-src="<?php echo !empty($art['image_url']) ? htmlspecialchars($art['image_url']) : ''; ?>"><?php echo htmlspecialchars($art['name']); ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <input type="hidden" name="comp_ids[]" value="0">
                                            <button type="button" class="btn btn-outline-danger btn-remove-comp"><i class="fas fa-times"></i></button>
                                        </div>
                                    </div>
                                </div>
                            <?php else: ?>
                                <?php foreach ($compartments as $comp):
                                    $is_article = !empty($comp['linked_article_id']);
                                ?>
                                    <div class="compartment-row card mb-2">
                                        <div class="card-body p-2">
                                            <div class="input-group">
                                                <span class="input-group-text handle cursor-grab"><i class="fas fa-grip-lines text-muted"></i></span>
                                                <select class="form-select type-select" name="comp_types[]" style="max-width: 130px;">
                                                    <option value="text" <?php echo !$is_article ? 'selected' : ''; ?>>Standardfach</option>
                                                    <option value="article" <?php echo $is_article ? 'selected' : ''; ?>>Zusatztasche</option>
                                                </select>
                                                
                                                <input type="text" name="comp_names[]" class="form-control name-input" value="<?php echo htmlspecialchars($comp['name']); ?>" style="<?php echo $is_article ? 'display:none;' : ''; ?>">
                                                
                                                <div class="flex-grow-1 article-select-wrapper" style="<?php echo !$is_article ? 'display:none;' : ''; ?>">
                                                    <select name="comp_articles[]" class="form-select article-select">
                                                        <option value="">Artikel wählen...</option>
                                                        <?php foreach($all_articles as $art): 
                                                            $sel = ($is_article && $art['id'] == $comp['linked_article_id']) ? 'selected' : '';
                                                        ?>
                                                            <option value="<?php echo $art['id']; ?>" <?php echo $sel; ?> data-src="<?php echo !empty($art['image_url']) ? htmlspecialchars($art['image_url']) : ''; ?>"><?php echo htmlspecialchars($art['name']); ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>

                                                <input type="hidden" name="comp_ids[]" value="<?php echo $comp['id']; ?>">
                                                <button type="button" class="btn btn-outline-danger btn-remove-comp"><i class="fas fa-times"></i></button>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        
                        <button type="button" class="btn btn-sm btn-outline-success mb-4" id="add-compartment"><i class="fas fa-plus"></i> Fach / Tasche hinzufügen</button>

                        <div class="d-flex justify-content-between border-top pt-3">
                            <a href="backpacks.php" class="btn btn-secondary">Abbrechen</a>
                            <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Speichern</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const manSelect = document.getElementById('manufacturer_select');
    const manContainer = document.getElementById('new_manufacturer_container');
    
    function toggleManContainer(val) {
        if (val === 'new') {
            manContainer.style.display = 'block';
            const input = manContainer.querySelector('input');
            if(input) input.required = true;
        } else {
            manContainer.style.display = 'none';
            const input = manContainer.querySelector('input');
            if(input) input.required = false;
        }
    }

    if (manSelect) {
        toggleManContainer(manSelect.value);
        manSelect.addEventListener('change', function() { toggleManContainer(this.value); });
        new TomSelect(manSelect, { create: false, sortField: { field: "text", direction: "asc" }, onChange: function(value) { toggleManContainer(value); } });
    }
    
    // New: Category Select
    if (document.getElementById('category_id')) {
        new TomSelect('#category_id', { create: false, sortField: { field: "text", direction: "asc" } });
    }

    const container = document.getElementById('compartments-container');
    
    new Sortable(container, {
        handle: '.handle',
        animation: 150
    });

    // Template for new row (with placeholders)
    const rowTemplate = `
        <div class="compartment-row card mb-2">
            <div class="card-body p-2">
                <div class="input-group">
                    <span class="input-group-text handle cursor-grab"><i class="fas fa-grip-lines text-muted"></i></span>
                    <select class="form-select type-select" name="comp_types[]" style="max-width: 130px;">
                        <option value="text">Standardfach</option>
                        <option value="article">Zusatztasche</option>
                    </select>
                    
                    <input type="text" name="comp_names[]" class="form-control name-input" placeholder="Fachname">
                    
                    <div class="flex-grow-1 article-select-wrapper" style="display:none;">
                        <select name="comp_articles[]" class="form-select article-select tom-select-init">
                            <option value="">Artikel wählen...</option>
                            <?php foreach($all_articles as $art): ?>
                                <option value="<?php echo $art['id']; ?>" data-src="<?php echo !empty($art['image_url']) ? htmlspecialchars($art['image_url']) : ''; ?>"><?php echo htmlspecialchars($art['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <input type="hidden" name="comp_ids[]" value="0">
                    <button type="button" class="btn btn-outline-danger btn-remove-comp"><i class="fas fa-times"></i></button>
                </div>
            </div>
        </div>
    `;

    document.getElementById('add-compartment').addEventListener('click', function() {
        container.insertAdjacentHTML('beforeend', rowTemplate);
        const newRow = container.lastElementChild;
        initRowLogic(newRow);
    });

    function initTomSelect(select) {
        if (select.tomselect) return;
        new TomSelect(select, { 
            create: false, 
            sortField: { field: "text", direction: "asc" },
            dropdownParent: 'body',
            render: {
                option: function(data, escape) {
                    let src = data.src || '';
                    return `<div>
                        ${src ? `<img src="${src}" style="width:24px;height:24px;object-fit:cover;margin-right:8px;vertical-align:middle;">` : ''}
                        <span>${escape(data.text)}</span>
                    </div>`;
                },
                item: function(data, escape) {
                    let src = data.src || '';
                    return `<div>
                        ${src ? `<img src="${src}" style="width:20px;height:20px;object-fit:cover;margin-right:6px;vertical-align:middle;">` : ''}
                        <span>${escape(data.text)}</span>
                    </div>`;
                }
            }
        });
    }

    function initRowLogic(row) {
        const typeSelect = row.querySelector('.type-select');
        const nameInput = row.querySelector('.name-input');
        const artWrapper = row.querySelector('.article-select-wrapper');
        const artSelect = row.querySelector('.article-select');
        
        typeSelect.addEventListener('change', function() {
            if (this.value === 'article') {
                nameInput.style.display = 'none';
                artWrapper.style.display = 'block';
                if (artSelect.classList.contains('tom-select-init') && !artSelect.tomselect) {
                    initTomSelect(artSelect);
                    artSelect.classList.remove('tom-select-init');
                } else if (artSelect && !artSelect.tomselect) {
                    initTomSelect(artSelect);
                }
            } else {
                nameInput.style.display = 'block';
                artWrapper.style.display = 'none';
            }
        });

        // Init if already visible (editing mode)
        if (artSelect && !artSelect.tomselect && artWrapper.style.display !== 'none') {
             initTomSelect(artSelect);
        }
    }

    // Init existing rows
    container.querySelectorAll('.compartment-row').forEach(initRowLogic);

    container.addEventListener('click', function(e) {
        if (e.target.closest('.btn-remove-comp')) {
            e.target.closest('.compartment-row').remove();
        }
    });

    // Image Handling Logic
    const imageFileInput = document.getElementById('image_file');
    const imagePreview = document.getElementById('imagePreview');
    const pasteArea = document.getElementById('pasteArea');
    const pastedImageDataInput = document.getElementById('pasted_image_data');

    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]);
            }
        });
    }

    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;
                        pasteArea.innerText = "Bild eingefügt!";
                        pasteArea.style.borderColor = "green";
                    };
                    reader.readAsDataURL(blob);
                }
            }
        });
        pasteArea.setAttribute('tabindex', '0'); 
        pasteArea.addEventListener('click', () => pasteArea.focus());
    }
});
</script>

<?php require_once 'footer.php'; ?>