<?php
// print_packing_list.php - Eigene Seite für die Druckansicht einer Packliste

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

require_once 'db_connect.php';

$current_user_id = $_SESSION['user_id'];
$packing_list_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$packing_list = null;
$items_by_parent = [];
$message = '';

$total_weight_grams = 0;
$weight_by_category = [];
$total_consumable_weight = 0;

if ($packing_list_id > 0) {
    $stmt = $conn->prepare("SELECT id, name, description, user_id FROM packing_lists WHERE id = ?");
    if ($stmt) {
        $stmt->bind_param("i", $packing_list_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows == 1) {
            $packing_list = $result->fetch_assoc();
            // Permission check logic could be expanded here
        } else {
            $message = 'Packliste nicht gefunden.';
        }
        $stmt->close();
    }
} else {
    $message = 'Keine ID.';
}

if ($packing_list) {
    // Artikel abrufen - LEFT JOIN für Container
    // WICHTIG: LEFT JOIN users für Trägernamen
    $sql = "SELECT 
                pli.id AS packing_list_item_id, pli.article_id, pli.quantity, pli.parent_packing_list_item_id, 
                pli.carrier_user_id, pli.backpack_id, pli.backpack_compartment_id,
                COALESCE(a.name, pli.name, bp.name, bpc.name, 'Unbekannt') AS name,
                a.weight_grams, c.name AS category_name, a.consumable, a.image_url,
                u.username AS carrier_name
            FROM packing_list_items pli 
            LEFT JOIN articles a ON pli.article_id = a.id 
            LEFT JOIN categories c ON a.category_id = c.id 
            LEFT JOIN backpacks bp ON pli.backpack_id = bp.id
            LEFT JOIN backpack_compartments bpc ON pli.backpack_compartment_id = bpc.id
            LEFT JOIN users u ON pli.carrier_user_id = u.id
            WHERE pli.packing_list_id = ? 
            ORDER BY pli.order_index ASC";
            
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("i", $packing_list_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $raw_items = [];
        while ($row = $result->fetch_assoc()) {
            // Fix Name for Backpacks if needed
            if ($row['backpack_id'] && empty($row['name'])) $row['name'] = "Rucksack";
            
            $raw_items[] = $row;
            
            // Stats
            $w = ($row['weight_grams'] ?? 0) * $row['quantity'];
            $total_weight_grams += $w;
            if ($row['consumable']) $total_consumable_weight += $w;
            $cat = $row['category_name'] ?: 'Sonstiges';
            if (!isset($weight_by_category[$cat])) $weight_by_category[$cat] = 0;
            $weight_by_category[$cat] += $w;
        }
        $stmt->close();

        // Build Tree
        $items_by_id = [];
        foreach ($raw_items as $item) {
            $item['children'] = [];
            $items_by_id[$item['packing_list_item_id']] = $item;
        }
        foreach ($items_by_id as $id => &$item) {
            $pid = $item['parent_packing_list_item_id'];
            if ($pid && isset($items_by_id[$pid])) {
                $items_by_id[$pid]['children'][] = &$item;
            }
        }
        unset($item);
        
        foreach ($items_by_id as $item) {
            if (!$item['parent_packing_list_item_id']) {
                $items_by_parent[] = $item; // Root items
            }
        }
    }
}
$conn->close();
$total_weight_without_consumables = $total_weight_grams - $total_consumable_weight;

// Recursive Render Function for Table Rows
function render_rows_recursive($items, $level = 0) {
    foreach ($items as $item) {
        $is_container = !empty($item['backpack_id']) || !empty($item['backpack_compartment_id']);
        $indent = $level * 20; // px
        
        $row_style = "";
        $name_style = "";
        if (!empty($item['backpack_id'])) {
            $row_style = "font-weight:bold; background-color:#f0f0f0; border-top: 2px solid #000;";
            $name_style = "text-transform:uppercase;";
        } elseif (!empty($item['backpack_compartment_id'])) {
            $row_style = "font-weight:bold; background-color:#fafafa; border-bottom:1px solid #ccc;";
            $name_style = "font-style:italic;";
        }

        echo '<tr style="' . $row_style . '">';
        
        // Checkbox
        echo '<td class="print-checkbox-cell"><div class="print-checkbox" style="' . ($is_container ? 'visibility:hidden;' : '') . '"></div></td>';
        
        // Name
        echo '<td style="padding-left: ' . $indent . 'px;">';
        if ($level > 0 && !$is_container) echo '<span style="color:#ccc; margin-right:5px;">↳</span>';
        echo '<span style="' . $name_style . '">' . htmlspecialchars($item['name']) . '</span>';
        echo '</td>';
        
        // Qty
        echo '<td class="text-center">' . ($is_container ? '' : $item['quantity']) . '</td>';
        
        // Weight
        echo '<td class="text-end">' . ($item['weight_grams'] > 0 ? number_format($item['weight_grams'], 0, ',', '.') . ' g' : '') . '</td>';
        
        echo '</tr>';

        if (!empty($item['children'])) {
            render_rows_recursive($item['children'], $level + 1);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($packing_list['name'] ?? 'Druckansicht'); ?></title>
    <!-- Updated Version Force -->
    <style>
        @media print {
            @page { size: A4; margin: 1.5cm; }
            body { font-family: sans-serif; font-size: 10pt; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
            .no-print { display: none; }
        }
        body { font-family: sans-serif; color: #000; max-width: 900px; margin: 0 auto; padding: 20px; }
        h1 { text-align: center; margin-bottom: 5px; }
        p.desc { text-align: center; color: #666; margin-bottom: 30px; }
        
        .carrier-section { margin-bottom: 30px; page-break-inside: avoid; }
        .carrier-title { font-size: 14pt; border-bottom: 2px solid #000; margin-bottom: 10px; padding-bottom: 5px; }
        
        table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }
        th { text-align: left; border-bottom: 1px solid #000; padding: 5px; font-size: 9pt; }
        td { padding: 4px 5px; border-bottom: 1px solid #eee; vertical-align: top; }
        
        .text-center { text-align: center; }
        .text-end { text-align: right; }
        
        .print-checkbox { width: 12px; height: 12px; border: 1px solid #000; display: inline-block; }
        .print-checkbox-cell { width: 20px; }
        
        .stats { margin-top: 40px; border-top: 2px solid #000; padding-top: 10px; display: flex; flex-wrap: wrap; gap: 20px; }
        .stat-item { width: 45%; margin-bottom: 5px; border-bottom: 1px dotted #ccc; display: flex; justify-content: space-between; }
    </style>
</head>
<body>
    <?php if ($packing_list): ?>
        <h1><?php echo htmlspecialchars($packing_list['name']); ?></h1>
        <p class="desc"><?php echo htmlspecialchars($packing_list['description'] ?? ''); ?></p>

        <?php
        if (empty($items_by_parent)) {
            echo '<p style="text-align:center;">Keine Artikel.</p>';
        } else {
            // Group by Carrier
            $items_by_carrier = [];
            foreach ($items_by_parent as $root) {
                $c_name = $root['carrier_name'] ?: 'Sonstiges';
                $items_by_carrier[$c_name][] = $root;
            }
            
            foreach ($items_by_carrier as $carrier => $roots) {
                echo '<div class="carrier-section">';
                echo '<div class="carrier-title">' . htmlspecialchars($carrier) . '</div>';
                echo '<table>';
                echo '<thead><tr><th style="width:20px;"></th><th>Artikel / Container</th><th class="text-center" style="width:50px;">Anz.</th><th class="text-end" style="width:80px;">Gewicht</th></tr></thead>';
                echo '<tbody>';
                render_rows_recursive($roots);
                echo '</tbody>';
                echo '</table>';
                echo '</div>';
            }
        }
        ?>

        <div class="stats">
            <div class="stat-item"><strong>Gesamtgewicht:</strong> <span><?php echo number_format($total_weight_grams, 0, ',', '.'); ?> g</span></div>
            <div class="stat-item"><strong>Basisgewicht (ohne Verbrauch):</strong> <span><?php echo number_format($total_weight_without_consumables, 0, ',', '.'); ?> g</span></div>
            <?php arsort($weight_by_category); foreach($weight_by_category as $cat => $w): ?>
                <div class="stat-item"><span><?php echo htmlspecialchars($cat); ?>:</span> <span><?php echo number_format($w, 0, ',', '.'); ?> g</span></div>
            <?php endforeach; ?>
        </div>

        <script>window.print();</script>
    <?php else: ?>
        <p style="color:red; text-align:center;"><?php echo htmlspecialchars($message); ?></p>
    <?php endif; ?>
</body>
</html>
