<?php
// public_list.php - Öffentliche, schreibgeschützte Ansicht einer geteilten Packliste
// FINALE VERSION: Vollständiges Layout mit Statistiken, Diagrammen und allen Funktionen.

require_once 'db_connect.php';

$token = $_GET['token'] ?? '';
$packing_list = null;
$all_items = [];
$items_by_carrier_hierarchical = [];
$sorted_items_by_carrier = [];

// Statistik-Variablen
$total_weight = 0;
$total_items_quantity = 0;
$weight_by_category = [];
$weight_by_carrier = [];
$weight_by_carrier_non_consumable = [];

// 1. Finde die Packliste, die zu diesem Token gehört
if (!empty($token)) {
    $stmt = $conn->prepare("SELECT * FROM packing_lists WHERE share_token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $packing_list = $result->fetch_assoc();
    }
    $stmt->close();
}

// 2. Wenn eine Packliste gefunden wurde, lade deren Inhalt
if ($packing_list) {
    $page_title = "Packliste: " . htmlspecialchars($packing_list['name']);
    $packing_list_id = $packing_list['id'];

    // SQL-Abfrage holt alle relevanten Daten
    $sql = "SELECT pli.id, pli.quantity, pli.parent_packing_list_item_id, a.name AS article_name, a.weight_grams, a.image_url, a.product_designation, a.consumable, a.product_url, c.name AS category_name, m.name AS manufacturer_name, u.username AS carrier_name FROM packing_list_items AS pli JOIN articles AS a ON pli.article_id = a.id LEFT JOIN categories AS c ON a.category_id = c.id LEFT JOIN manufacturers AS m ON a.manufacturer_id = m.id LEFT JOIN users AS u ON pli.carrier_user_id = u.id WHERE pli.packing_list_id = ?";
    $stmt_items = $conn->prepare($sql);
    $stmt_items->bind_param("i", $packing_list_id);
    $stmt_items->execute();
    $result_items = $stmt_items->get_result();
    while ($row = $result_items->fetch_assoc()) {
        $all_items[$row['id']] = $row;
        $item_total_weight = $row['quantity'] * $row['weight_grams'];
        $total_weight += $item_total_weight;
        $total_items_quantity += $row['quantity'];
        $category_name = $row['category_name'] ?: 'Ohne Kategorie';
        $carrier_name = $row['carrier_name'] ?: 'Sonstiges';
        if (!isset($weight_by_category[$category_name])) $weight_by_category[$category_name] = 0;
        $weight_by_category[$category_name] += $item_total_weight;
        if (!isset($weight_by_carrier[$carrier_name])) $weight_by_carrier[$carrier_name] = 0;
        $weight_by_carrier[$carrier_name] += $item_total_weight;
        if (!$row['consumable']) {
             if (!isset($weight_by_carrier_non_consumable[$carrier_name])) $weight_by_carrier_non_consumable[$carrier_name] = 0;
            $weight_by_carrier_non_consumable[$carrier_name] += $item_total_weight;
        }
    }
    $stmt_items->close();

    // Hierarchie aufbauen
    foreach($all_items as $item) {
        $carrier_name = $item['carrier_name'] ?: 'Sonstiges';
        $items_by_carrier_hierarchical[$carrier_name][$item['id']] = $item;
    }
    foreach($items_by_carrier_hierarchical as &$carrier_items) {
        $hierarchical_list = [];
        foreach ($carrier_items as $id => &$item) {
            if (empty($item['parent_packing_list_item_id']) || !isset($carrier_items[$item['parent_packing_list_item_id']])) {
                $hierarchical_list[$id] = &$item;
            } else {
                if (!isset($carrier_items[$item['parent_packing_list_item_id']]['children'])) {
                    $carrier_items[$item['parent_packing_list_item_id']]['children'] = [];
                }
                $carrier_items[$item['parent_packing_list_item_id']]['children'][] = &$item;
            }
        }
        $carrier_items = $hierarchical_list;
    }
    unset($carrier_items, $item);

    // Sortierung
    $sorted_items_by_carrier = $items_by_carrier_hierarchical;
    ksort($sorted_items_by_carrier);
    if(isset($sorted_items_by_carrier['Sonstiges'])) {
        $unassigned = $sorted_items_by_carrier['Sonstiges'];
        unset($sorted_items_by_carrier['Sonstiges']);
        $sorted_items_by_carrier['Sonstiges'] = $unassigned;
    }

} else {
    $page_title = "Ungültiger Link";
}
$conn->close();

// Render-Funktionen
function render_public_rows($items, $level = 0) {
    foreach ($items as $item) {
        $item_weight = $item['quantity'] * $item['weight_grams'];
        $has_children = !empty($item['children']);
        echo '<tr>';
        echo '<td><img src="' . (!empty($item['image_url']) ? htmlspecialchars($item['image_url']) : 'https://placehold.co/100x100/e0e0e0/555555?text=O') . '" alt="' . htmlspecialchars($item['article_name']) . '" class="item-image article-image-trigger" data-preview-url="' . htmlspecialchars($item['image_url'] ?? '') . '"></td>';
        echo '<td class="text-center">' . (!empty($item['product_url']) ? '<a href="'.htmlspecialchars($item['product_url']).'" target="_blank" class="btn btn-sm btn-outline-secondary" data-bs-toggle="tooltip" title="Produktseite öffnen"><i class="fas fa-external-link-alt"></i></a>' : '') . '</td>';
        echo '<td style="padding-left: ' . (10 + ($level * 30)) . 'px;">' . ($level > 0 ? '<i class="fas fa-level-up-alt fa-rotate-90 text-muted me-2"></i>' : '') . htmlspecialchars($item['article_name']) . '</td>';
        echo '<td class="text-center">' . ($item['consumable'] ? '<i class="fas fa-cookie-bite text-warning" data-bs-toggle="tooltip" title="Verbrauchsartikel"></i>' : '') . '</td>';
        echo '<td>' . htmlspecialchars($item['manufacturer_name'] ?: '---') . '</td>';
        echo '<td>' . htmlspecialchars($item['product_designation'] ?: '---') . '</td>';
        echo '<td>' . htmlspecialchars($item['category_name'] ?: '---') . '</td>';
        echo '<td class="text-center"><span class="badge bg-secondary rounded-pill">' . $item['quantity'] . 'x</span></td>';
        echo '<td class="text-end"><span class="badge bg-secondary rounded-pill">' . number_format($item['weight_grams'], 0, ',', '.') . ' g</span></td>';
        echo '<td class="text-end"><span class="badge bg-secondary rounded-pill">' . number_format($item_weight, 0, ',', '.') . ' g</span></td>';
        echo '</tr>';
        if ($has_children) render_public_rows($item['children'], $level + 1);
    }
}
function render_print_table_rows($items, $level = 0) {
    foreach($items as $item) {
        echo '<tr class="' . ($level > 0 ? 'print-child-item' : '') . '">';
        echo '<td class="print-checkbox-cell"><span class="print-checkbox"></span></td>';
        echo '<td><div style="padding-left: ' . ($level * 25) . 'px;">' . ($level > 0 ? '<span class="arrow-wrapper"></span>' : '') . htmlspecialchars($item['article_name']) . '</div></td>';
        echo '<td>' . htmlspecialchars($item['manufacturer_name'] ?: '---') . '</td>';
        echo '<td>' . htmlspecialchars($item['product_designation'] ?: '---') . '</td>';
        echo '<td class="text-center">' . $item['quantity'] . 'x</td>';
        echo '</tr>';
        if (!empty($item['children'])) render_print_table_rows($item['children'], $level + 1);
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@400;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root { --color-primary: #3B4A23; --color-accent: #2c3e50; }
        body { background-color: #f4f7f6; font-family: 'Nunito Sans', sans-serif; }
        .table th, .table td { vertical-align: middle; }
        .item-image { width: 40px; height: 40px; object-fit: cover; border-radius: .3rem; cursor: pointer; }
        .card-header { background-color: var(--color-primary); color: white; font-weight: 700; }
        .card-header-stats { background-color: var(--color-accent); color: white; }
        .carrier-header-row td { background-color: #f8f9fa; font-weight: bold; padding: 0.75rem 1.25rem; border-top: 5px solid #fff; border-bottom: 1px solid #dee2e6;}
        .stats-table-container { border: 1px solid #dee2e6; border-radius: .5rem; background-color: #f8f9fa; overflow: hidden; padding: 0.75rem; }
        .chart-container { position: relative; min-height: 220px; width: 100%; margin-bottom: 1rem; }
        .table th.consumable-col { width: 40px; text-align: center; }
        #image-preview-tooltip { display: none; position: absolute; border: 1px solid #ccc; background-color: #fff; padding: 5px; z-index: 1000; width: 200px; height: 200px; background-repeat: no-repeat; background-position: center center; background-size: contain; box-shadow: 0 4px 8px rgba(0,0,0,0.1); border-radius: 5px; pointer-events: none; }
        .print-view { display: none; }
        .app-footer { text-align: center; padding: 1.5rem; margin-top: 2rem; color: #888; font-size: 0.9em; }
        .app-footer a { color: #555; font-weight: bold; text-decoration: none; }
        .app-footer a:hover { text-decoration: underline; }
        @media print {
            body { background: none !important; } .screen-view, .print-hide, .app-footer { display: none !important; } .print-view { display: block !important; }
            @page { margin: 1.5cm; } .print-header h1 { font-size: 20pt; text-align: center; margin-bottom: 2rem; }
            .print-carrier-group { page-break-inside: avoid; margin-top: 1.5rem; } .print-carrier-header { font-size: 14pt; border-bottom: 2px solid #333; padding-bottom: 5px; margin-bottom: 1rem; }
            .print-table { width: 100%; border-collapse: collapse; font-size: 10pt; } .print-table th, .print-table td { text-align: left; padding: 6px; border-bottom: 1px solid #ccc; vertical-align: middle; }
            .print-table th { font-weight: bold; } .print-checkbox-cell { width: 30px; } .print-checkbox { display: inline-block; width: 16px; height: 16px; border: 1px solid #333; }
            .print-child-item .arrow-wrapper { position: relative; display: inline-block; width: 15px; height: 1.2em; vertical-align: middle; margin-right: 5px; }
            .print-child-item .arrow-wrapper::before { content: ''; position: absolute; left: 5px; top: 0; height: 100%; border-left: 1px solid #888;}
            .print-child-item .arrow-wrapper::after { content: ''; position: absolute; left: 5px; top: 50%; width: 10px; border-top: 1px solid #888;}
        }
    </style>
</head>
<body>
<div class="container my-4">
    <?php if ($packing_list): ?>
        <div class="screen-view">
             <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h1 class="h4 mb-0"><i class="fas fa-clipboard-list me-2"></i><?php echo htmlspecialchars($packing_list['name']); ?></h1>
                    <button onclick="window.print();" class="btn btn-light btn-sm print-hide"><i class="fas fa-print me-2"></i>Drucken</button>
                </div>
            </div>
            <div class="row">
                <div class="col-lg-8 mb-4 mb-lg-0">
                    <div class="card h-100">
                        <div class="card-header"><h5 class="mb-0"><i class="fas fa-box-open me-2"></i>Gepackte Artikel</h5></div>
                        <div class="card-body p-2"><div class="table-responsive">
                            <table class="table table-hover table-sm mb-0">
                                <thead><tr><th style="width:50px;">Bild</th><th style="width:40px;" title="Produktlink"><i class="fas fa-link"></i></th><th>Artikel</th><th class="consumable-col" title="Verbrauchsartikel"><i class="fas fa-cookie-bite"></i></th><th>Hersteller</th><th>Modell/Typ</th><th>Kategorie</th><th class="text-center">Menge</th><th class="text-end">Gewicht/Stk.</th><th class="text-end">G-Gewicht</th></tr></thead>
                                <tbody>
                                    <?php if(empty($sorted_items_by_carrier)): ?>
                                        <tr><td colspan="10" class="text-center p-4">Diese Packliste ist leer.</td></tr>
                                    <?php else: ?>
                                        <?php foreach($sorted_items_by_carrier as $carrier => $items): ?>
                                            <tr class="carrier-header-row"><td colspan="10"><h6><?php echo htmlspecialchars($carrier); ?></h6></td></tr>
                                            <?php render_public_rows($items); ?>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div></div>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="card h-100">
                        <div class="card-header card-header-stats"><h5 class="mb-0"><i class="fas fa-chart-bar me-2"></i>Statistiken</h5></div>
                        <div class="card-body">
                            <div class="stats-table-container mb-4">
                                <h6>Gewicht pro Träger</h6>
                                <ul class="list-group list-group-flush bg-transparent">
                                    <?php foreach ($weight_by_carrier as $carrier => $weight): ?>
                                        <li class="list-group-item px-1 py-2 bg-transparent"><strong><?php echo htmlspecialchars($carrier); ?></strong><div class="d-flex justify-content-between align-items-center text-muted small mt-1">Gesamt:<span class="badge bg-success rounded-pill"><?php echo number_format($weight, 0, ',', '.'); ?> g</span></div></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                            <div class="chart-container"><canvas id="categoryWeightChart"></canvas></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="print-view">
             <div class="print-header"><h1>Packliste: <?php echo htmlspecialchars($packing_list['name']); ?></h1></div>
            <?php foreach($sorted_items_by_carrier as $carrier => $items): ?>
                <div class="print-carrier-group">
                    <h2 class="print-carrier-header"><?php echo htmlspecialchars($carrier); ?></h2>
                    <table class="print-table">
                        <thead><tr><th class="print-checkbox-cell"></th><th>Artikel</th><th>Hersteller</th><th>Modell/Typ</th><th class="text-center">Menge</th></tr></thead>
                        <tbody><?php render_print_table_rows($items); ?></tbody>
                    </table>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="alert alert-danger text-center p-5"><h4>Ungültiger Link</h4><p class="lead">Der angegebene Freigabe-Link ist ungültig oder wurde deaktiviert.</p></div>
    <?php endif; ?>
</div>

<div id="image-preview-tooltip"></div>
<footer class="app-footer">
    Erstellt mit <a href="#" target="_blank">Trekking Packliste</a>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl) });

    const tooltip = document.getElementById('image-preview-tooltip');
    if (tooltip) {
        document.querySelectorAll('.article-image-trigger').forEach(trigger => {
            trigger.addEventListener('mouseover', e => {
                const url = e.target.getAttribute('data-preview-url');
                if (url && url !== '' && !url.includes('placehold.co')) {
                    tooltip.style.backgroundImage = `url('${url}')`;
                    tooltip.style.display = 'block';
                }
            });
            trigger.addEventListener('mousemove', e => { tooltip.style.left = e.pageX + 15 + 'px'; tooltip.style.top = e.pageY + 15 + 'px'; });
            trigger.addEventListener('mouseout', () => { tooltip.style.display = 'none'; });
        });
    }

    <?php if ($packing_list && !empty($weight_by_category)): ?>
    const catCtx = document.getElementById('categoryWeightChart');
    if (catCtx) {
        new Chart(catCtx, {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode(array_keys($weight_by_category)); ?>,
                datasets: [{ data: <?php echo json_encode(array_values($weight_by_category)); ?>, backgroundColor: ['#3B4A23', '#6B8E23', '#90A955', '#4F6F52', '#739072', '#8A9A5B', '#A9A9A9'], borderWidth: 2 }]
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: true, position: 'bottom' } } }
        });
    }
    <?php endif; ?>
});
</script>
</body>
</html>
