<?php
// packing_lists.php - Übersicht über alle Haushalts-Packlisten
// KORREKTUR: Bearbeiten-Buttons werden nun auch für Haushaltsmitglieder bei geteilten Listen angezeigt.

$page_title = "Packlisten des Haushalts";

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 'header.php';

$current_user_id = $_SESSION['user_id'];
$message = '';

if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

// Lade die 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();
$current_user_household_id = $stmt_household->get_result()->fetch_assoc()['household_id'];
$stmt_household->close();

$household_member_ids = [$current_user_id];
if ($current_user_household_id) {
    $stmt_members = $conn->prepare("SELECT id FROM users WHERE household_id = ?");
    $stmt_members->bind_param("i", $current_user_household_id);
    $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();
}

$packing_lists = [];
// KORREKTUR: Die SQL-Abfrage wurde vereinfacht und korrigiert, um alle relevanten Listen anzuzeigen.
// Es werden alle Listen angezeigt, die entweder vom Nutzer erstellt wurden ODER mit seinem Haushalt geteilt sind.
$sql = "SELECT
            pl.id, pl.name, pl.description, pl.user_id, pl.household_id,
            u.username as creator_name,
            COUNT(DISTINCT COALESCE(pli.carrier_user_id, 'sonstiges')) AS carrier_count,
            SUM(pli.quantity * a.weight_grams) AS total_weight
        FROM packing_lists pl
        JOIN users u ON pl.user_id = u.id
        LEFT JOIN packing_list_items pli ON pl.id = pli.packing_list_id
        LEFT JOIN articles a ON pli.article_id = a.id
        WHERE pl.user_id = ? OR pl.household_id = ?
        GROUP BY pl.id, pl.name, pl.description, pl.user_id, u.username, pl.household_id
        ORDER BY pl.name ASC";

$stmt = $conn->prepare($sql);
if ($stmt === false) {
    $message .= '<div class="alert alert-danger" role="alert">SQL Prepare-Fehler: ' . $conn->error . '</div>';
} else {
    $stmt->bind_param("ii", $current_user_id, $current_user_household_id);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $packing_lists[] = $row;
    }
    $stmt->close();
}
$conn->close();
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0">Packlisten im Haushalt</h2>
        <a href="add_packing_list.php" class="btn btn-sm btn-outline-light"><i class="fas fa-plus-circle me-2"></i>Neue Packliste erstellen</a>
    </div>

    <div class="card-body">
        <?php if(!empty($message)) echo $message; ?>
        <?php if (empty($packing_lists)): ?>
            <div class="alert alert-info text-center" role="alert">
                Du hast noch keine Packlisten angelegt. <a href="add_packing_list.php" class="alert-link">Erstelle jetzt deine erste!</a>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($packing_lists as $list): ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="card h-100 shadow-sm packing-list-card">
                            <div class="card-body d-flex flex-column">
                                <img src="assets/images/rucksack_icon.png" alt="Packliste" class="card-icon">
                                <h5 class="card-title"><?php echo htmlspecialchars($list['name']); ?></h5>
                                <p class="card-text text-muted flex-grow-1 small"><?php echo htmlspecialchars($list['description'] ?: 'Keine Beschreibung vorhanden.'); ?></p>
                                <div class="mt-auto d-flex justify-content-between">
                                    <span class="badge bg-secondary creator-badge"><i class="fas fa-user-edit me-1"></i> Erstellt von <?php echo htmlspecialchars($list['creator_name']); ?></span>
                                    <?php if (!empty($list['household_id'])): ?>
                                        <span class="badge bg-success" data-bs-toggle="tooltip" title="Für den Haushalt freigegeben"><i class="fas fa-users"></i></span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary" data-bs-toggle="tooltip" title="Private Liste"><i class="fas fa-user"></i></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="card-footer d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center">
                                    <span class="me-3" data-bs-toggle="tooltip" title="Anzahl Träger"><i class="fas fa-users text-muted"></i> <span class="badge bg-primary rounded-pill ms-1"><?php echo $list['carrier_count']; ?></span></span>
                                    <span data-bs-toggle="tooltip" title="Gesamtgewicht"><i class="fas fa-weight-hanging text-muted"></i> <span class="badge bg-success rounded-pill ms-1"><?php echo number_format(($list['total_weight'] ?? 0) / 1000, 2, ',', '.'); ?> kg</span></span>
                                </div>
                                <div>
                                    <a href="packing_list_detail.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-success" title="Details ansehen"><i class="fas fa-eye"></i></a>
                                    <?php 
                                        $is_owner = ($list['user_id'] == $current_user_id);
                                        $can_edit_household_list = (!empty($list['household_id']) && $list['household_id'] == $current_user_household_id);
                                    ?>
                                    <?php if ($is_owner || $can_edit_household_list): ?>
                                        <a href="edit_packing_list_details.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-primary" title="Details bearbeiten"><i class="fas fa-pencil-alt"></i></a>
                                        <a href="manage_packing_list_items.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-secondary" title="Artikel verwalten"><i class="fas fa-boxes"></i></a>
                                    <?php endif; ?>
                                    <?php if ($is_owner): ?>
                                        <a href="share_packing_list.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-info" title="Teilen"><i class="fas fa-share-alt"></i></a>
                                        <a href="duplicate_packing_list.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-dark" title="Duplizieren" onclick="return confirm('Möchten Sie diese Packliste wirklich duplizieren?');"><i class="fas fa-copy"></i></a>
                                        <a href="delete_packing_list.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-danger ms-2" title="Löschen" onclick="return confirm('Sind Sie sicher, dass Sie diese Packliste löschen möchten?');"><i class="fas fa-trash"></i></a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

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