<?php
// src/packing_list_utils.php - Hilfsfunktionen für Packlisten

/**
 * Kopiert den gesamten Inhalt einer Packliste (Items, Träger, Hierarchie) in eine neue Liste.
 * 
 * @param int $sourceId ID der Quell-Packliste
 * @param int $targetId ID der Ziel-Packliste
 * @param mysqli $conn Datenbankverbindung
 * @throws Exception Bei Datenbankfehlern
 */
function copyPackingListContent($sourceId, $targetId, $conn) {
    // 1. Träger kopieren (packing_list_carriers)
    $stmt_carriers = $conn->prepare("SELECT user_id, backpack_id FROM packing_list_carriers WHERE packing_list_id = ?");
    if (!$stmt_carriers) throw new Exception("Prepare failed for carriers select: " . $conn->error);
    
    $stmt_carriers->bind_param("i", $sourceId);
    $stmt_carriers->execute();
    $result_carriers = $stmt_carriers->get_result();
    
    $stmt_insert_carrier = $conn->prepare("INSERT INTO packing_list_carriers (packing_list_id, user_id, backpack_id) VALUES (?, ?, ?)");
    if (!$stmt_insert_carrier) throw new Exception("Prepare failed for carriers insert: " . $conn->error);

    while ($row = $result_carriers->fetch_assoc()) {
        $stmt_insert_carrier->bind_param("iii", $targetId, $row['user_id'], $row['backpack_id']);
        if (!$stmt_insert_carrier->execute()) throw new Exception("Error inserting carrier: " . $stmt_insert_carrier->error);
    }
    $stmt_carriers->close();
    $stmt_insert_carrier->close();

    // 2. Items kopieren (packing_list_items)
    // Alle Items inklusive Rucksack/Fach-Info holen
    $sql_items = "SELECT id, article_id, quantity, parent_packing_list_item_id, carrier_user_id, backpack_id, backpack_compartment_id, name, order_index 
                  FROM packing_list_items WHERE packing_list_id = ?";
    $stmt_items = $conn->prepare($sql_items);
    if (!$stmt_items) throw new Exception("Prepare failed for items select: " . $conn->error);
    
    $stmt_items->bind_param("i", $sourceId);
    $stmt_items->execute();
    $result_items = $stmt_items->get_result();
    
    $original_items = [];
    while ($row = $result_items->fetch_assoc()) {
        $original_items[] = $row;
    }
    $stmt_items->close();

    if (!empty($original_items)) {
        $old_to_new_id_map = []; // Mapping: alte_ID => neue_ID

        // 2a. Items einfügen (zunächst ohne Parent-Referenz)
        $sql_insert = "INSERT INTO packing_list_items 
                       (packing_list_id, article_id, quantity, carrier_user_id, backpack_id, backpack_compartment_id, name, order_index) 
                       VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt_insert_item = $conn->prepare($sql_insert);
        if (!$stmt_insert_item) throw new Exception("Prepare failed for item insert: " . $conn->error);
        
        foreach ($original_items as $item) {
            $stmt_insert_item->bind_param(
                "iiiisiis", 
                $targetId, 
                $item['article_id'], 
                $item['quantity'], 
                $item['carrier_user_id'], 
                $item['backpack_id'], 
                $item['backpack_compartment_id'], 
                $item['name'], 
                $item['order_index']
            );
            
            if (!$stmt_insert_item->execute()) {
                throw new Exception("Error copying item ID " . $item['article_id'] . ": " . $stmt_insert_item->error);
            }
            $old_to_new_id_map[$item['id']] = $conn->insert_id;
        }
        $stmt_insert_item->close();

        // 2b. Parent-Referenzen aktualisieren (Hierarchie wiederherstellen)
        $stmt_update_parent = $conn->prepare("UPDATE packing_list_items SET parent_packing_list_item_id = ? WHERE id = ?");
        if (!$stmt_update_parent) throw new Exception("Prepare failed for parent update: " . $conn->error);

        foreach ($original_items as $item) {
            if (!empty($item['parent_packing_list_item_id'])) {
                $old_parent_id = $item['parent_packing_list_item_id'];
                
                // Prüfen, ob der Parent auch kopiert wurde (sollte immer so sein)
                if (isset($old_to_new_id_map[$old_parent_id])) {
                    $new_parent_id = $old_to_new_id_map[$old_parent_id];
                    $new_child_id = $old_to_new_id_map[$item['id']];

                    $stmt_update_parent->bind_param("ii", $new_parent_id, $new_child_id);
                    if (!$stmt_update_parent->execute()) {
                         throw new Exception("Error updating parent hierarchy: " . $stmt_update_parent->error);
                    }
                }
            }
        }
        $stmt_update_parent->close();
    }
}
?>
