<?php
// packing_lists.php - Übersicht über alle Haushalts-Packlisten und Vorlagen

$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'];

// AUTO-MIGRATION: Check columns to prevent SQL errors
$check_col = $conn->query("SHOW COLUMNS FROM packing_lists LIKE 'is_template'");
if ($check_col && $check_col->num_rows == 0) {
    // Add column if missing
    $conn->query("ALTER TABLE packing_lists ADD COLUMN is_template TINYINT(1) NOT NULL DEFAULT 0 AFTER share_token");
}

$view = isset($_GET['view']) && $_GET['view'] === 'templates' ? 'templates' : 'lists';
$is_template_view = ($view === 'templates');

$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();

$packing_lists = [];
$is_template_val = $is_template_view ? 1 : 0;

$sql = "SELECT
            pl.id, pl.name, pl.description, pl.user_id, pl.household_id, pl.is_template,
            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 = ?) AND pl.is_template = ?
        GROUP BY pl.id, pl.name, pl.description, pl.user_id, u.username, pl.household_id, pl.is_template
        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 {
    // Falls household_id NULL ist, nutzen wir 0 (da ID immer > 0)
    $h_id = $current_user_household_id ?: 0;
    $stmt->bind_param("iii", $current_user_id, $h_id, $is_template_val);
    $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">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2 class="h4 mb-0"><?php echo $is_template_view ? 'Meine Vorlagen' : '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>

        <ul class="nav nav-tabs card-header-tabs">
            <li class="nav-item">
                <a class="nav-link <?php echo !$is_template_view ? 'active' : ''; ?>" href="packing_lists.php?view=lists">
                    <i class="fas fa-list me-2"></i>Packlisten
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $is_template_view ? 'active' : ''; ?>" href="packing_lists.php?view=templates">
                    <i class="fas fa-copy me-2"></i>Vorlagen
                </a>
            </li>
        </ul>
    </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">
                <?php if ($is_template_view): ?>
                    Du hast noch keine Vorlagen. Erstelle eine Packliste und speichere sie als Vorlage.
                <?php else: ?>
                    Du hast noch keine Packlisten angelegt. <a href="add_packing_list.php" class="alert-link">Erstelle jetzt deine erste!</a>
                <?php endif; ?>
            </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 <?php echo $is_template_view ? 'border-info' : ''; ?>">
                            <div class="card-body d-flex flex-column">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <img src="assets/images/rucksack_icon.png" alt="Packliste" class="card-icon" style="opacity: <?php echo $is_template_view ? '0.7' : '1'; ?>;">
                                    <?php if ($is_template_view): ?>
                                        <span class="badge bg-info text-dark">VORLAGE</span>
                                    <?php endif; ?>
                                </div>
                                
                                <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> <?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>
                                    <?php 
                                        $is_owner = ($list['user_id'] == $current_user_id);
                                        $can_edit_household_list = (!empty($list['household_id']) && $list['household_id'] == $current_user_household_id);
                                        
                                        // Actions für Vorlagen und Listen unterscheiden
                                        if ($is_template_view) {
                                            // VORLAGEN ACTIONS
                                            ?>
                                            <form action="add_packing_list.php" method="POST" class="d-inline">
                                            </form>
                                            
                                            <?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="Inhalt bearbeiten"><i class="fas fa-boxes"></i></a>
                                            <?php endif; ?>
                                            
                                            <?php
                                        } else {
                                            // LIST ACTIONS (Standard)
                                            ?>
                                            <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 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']; ?>&phase=1" class="btn btn-sm btn-outline-info" title="Phase 1: Artikel aufsammeln (Lager -> Tisch)"><i class="fas fa-hand-pointer"></i> 1. Aufsammeln</a>
                                                <a href="manage_packing_list_items.php?id=<?php echo $list['id']; ?>&phase=2" class="btn btn-sm btn-outline-success" title="Phase 2: Rucksack packen (Tisch -> Rucksack)"><i class="fas fa-backpack"></i> 2. Packen</a>
                                                <a href="manage_packing_list_items.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-secondary" title="Alle 3 Spalten anzeigen"><i class="fas fa-columns"></i></a>
                                            <?php endif; ?>
                                            
                                            <?php if ($is_owner): ?>
                                                <!-- Save As Template -->
                                                <a href="save_as_template.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-outline-warning" title="Als Vorlage speichern"><i class="fas fa-save"></i></a>
                                            <?php endif; ?>
                                            
                                            <?php
                                        }
                                    ?>

                                    <?php if ($is_owner): ?>
                                        <?php if (!$is_template_view): ?>
                                            <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>
                                        <?php endif; ?>
                                        <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 <?php echo $is_template_view ? 'Vorlage' : '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'; ?>