<?php
// edit_packing_list_details.php - Bearbeiten von Details und Rucksack-Zuweisung
$page_title = "Packliste Details bearbeiten";

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 'household_actions.php';
require_once 'backpack_utils.php'; // Fix: Include utils
require_once 'header.php';

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

// --- 1. Permissions & Basic Data ---
if ($packing_list_id > 0) {
    $stmt_household_check = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
    $stmt_household_check->bind_param("i", $current_user_id);
    $stmt_household_check->execute();
    $current_user_household_id = $stmt_household_check->get_result()->fetch_assoc()['household_id'];
    $stmt_household_check->close();

    $stmt_list_check = $conn->prepare("SELECT id, name, description, user_id, household_id FROM packing_lists WHERE id = ?");
    $stmt_list_check->bind_param("i", $packing_list_id);
    $stmt_list_check->execute();
    $result = $stmt_list_check->get_result();
    if ($result->num_rows == 1) {
        $packing_list = $result->fetch_assoc();
        $is_owner = ($packing_list['user_id'] == $current_user_id);
        $is_household_list = !empty($packing_list['household_id']);
        $is_in_same_household = ($is_household_list && $packing_list['household_id'] == $current_user_household_id);

        if ($is_owner || $is_in_same_household) {
            $can_edit = true;
        } else {
            $message = '<div class="alert alert-danger">Keine Berechtigung.</div>';
            $packing_list = null;
        }
    } else {
        $message = '<div class="alert alert-warning">Packliste nicht gefunden.</div>';
    }
} else {
    $message = '<div class="alert alert-danger">Keine ID.</div>';
}

// --- 2. Fetch Data for Dropdowns ---
$available_users = [];
if ($can_edit) {
    // Owners: Creator + Household Members (if shared)
    if ($packing_list['household_id']) {
        $stmt = $conn->prepare("SELECT id, username FROM users WHERE household_id = ?");
        $stmt->bind_param("i", $packing_list['household_id']);
    } else {
        $stmt = $conn->prepare("SELECT id, username FROM users WHERE id = ?");
        $stmt->bind_param("i", $packing_list['user_id']);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $available_users[] = $row;
    }

    // Current Assignments
    $current_assignments = [];
    $stmt_ca = $conn->prepare("SELECT user_id, backpack_id FROM packing_list_carriers WHERE packing_list_id = ?");
    $stmt_ca->bind_param("i", $packing_list_id);
    $stmt_ca->execute();
    $res_ca = $stmt_ca->get_result();
    while ($row = $res_ca->fetch_assoc()) {
        $current_assignments[$row['user_id']] = $row['backpack_id'];
    }
}

// --- 3. Handle Form Submission ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && $can_edit) {
    // Update Basic Details
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $stmt_update = $conn->prepare("UPDATE packing_lists SET name = ?, description = ? WHERE id = ?");
    $stmt_update->bind_param("ssi", $name, $description, $packing_list_id);
    $stmt_update->execute();
    $packing_list['name'] = $name;
    $packing_list['description'] = $description;

    // Handle Backpack Assignments
    if (isset($_POST['backpacks'])) {
        foreach ($_POST['backpacks'] as $uid => $bid) {
            $uid = intval($uid);
            $bid = intval($bid);
            $bid = ($bid > 0) ? $bid : NULL;

            // Update Carrier Table
            // Check if exists
            $old_backpack_id = 0;
            $stmt_chk = $conn->prepare("SELECT id, backpack_id FROM packing_list_carriers WHERE packing_list_id = ? AND user_id = ?");
            $stmt_chk->bind_param("ii", $packing_list_id, $uid);
            $stmt_chk->execute();
            $res_chk = $stmt_chk->get_result();
            if ($row_chk = $res_chk->fetch_assoc()) {
                $old_backpack_id = $row_chk['backpack_id'];
                $stmt_up = $conn->prepare("UPDATE packing_list_carriers SET backpack_id = ? WHERE packing_list_id = ? AND user_id = ?");
                $stmt_up->bind_param("iii", $bid, $packing_list_id, $uid);
                $stmt_up->execute();
            } else {
                $stmt_in = $conn->prepare("INSERT INTO packing_list_carriers (packing_list_id, user_id, backpack_id) VALUES (?, ?, ?)");
                $stmt_in->bind_param("iii", $packing_list_id, $uid, $bid);
                $stmt_in->execute();
            }

            // CLEANUP LOGIC: If backpack changed or removed
            if ($old_backpack_id != $bid) {
                // 1. Unparent all items that are inside the old containers (so they don't get deleted)
                // Find all container items for this user
                $stmt_find_containers = $conn->prepare("SELECT id FROM packing_list_items WHERE packing_list_id = ? AND carrier_user_id = ? AND (backpack_id IS NOT NULL OR backpack_compartment_id IS NOT NULL)");
                $stmt_find_containers->bind_param("ii", $packing_list_id, $uid);
                $stmt_find_containers->execute();
                $res_cont = $stmt_find_containers->get_result();
                $container_ids = [];
                while ($r = $res_cont->fetch_assoc()) $container_ids[] = $r['id'];
                
                if (!empty($container_ids)) {
                    $ids_str = implode(',', $container_ids);
                    // Set parent to NULL for children of these containers
                    $conn->query("UPDATE packing_list_items SET parent_packing_list_item_id = NULL WHERE packing_list_id = $packing_list_id AND parent_packing_list_item_id IN ($ids_str)");
                    
                    // 2. Delete the containers
                    $conn->query("DELETE FROM packing_list_items WHERE id IN ($ids_str)");
                }
            }

            // SYNC LOGIC (Only if new backpack assigned)
            if ($bid && $old_backpack_id != $bid) {
                sync_backpack_items($conn, $packing_list_id, $uid, $bid);
            }
        }
    }
    
    $message = '<div class="alert alert-success">Änderungen gespeichert!</div>';
    // Refresh assignments
    $stmt_ca->execute();
    $res_ca = $stmt_ca->get_result();
    $current_assignments = [];
    while ($row = $res_ca->fetch_assoc()) {
        $current_assignments[$row['user_id']] = $row['backpack_id'];
    }
}

?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0">Details: <?php echo htmlspecialchars($packing_list['name'] ?? ''); ?></h2>
        <a href="packing_lists.php" class="btn btn-sm btn-outline-light"><i class="fas fa-arrow-left me-2"></i>Zurück</a>
    </div>
    <div class="card-body p-4">
        <?php echo $message; ?>

        <?php if ($packing_list): ?>
            <form method="post">
                <div class="row">
                    <div class="col-md-8">
                        <h5 class="mb-3">Basisdaten</h5>
                        <div class="mb-3">
                            <label class="form-label">Name</label>
                            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($packing_list['name']); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Beschreibung</label>
                            <textarea class="form-control" name="description" rows="3"><?php echo htmlspecialchars($packing_list['description'] ?: ''); ?></textarea>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <h5 class="mb-3">Rucksack-Zuweisung</h5>
                        <div class="card bg-light border-0">
                            <div class="card-body">
                                <p class="small text-muted">Wähle hier, wer welchen Rucksack trägt. Bereits vergebene Rucksäcke werden ausgeblendet.</p>
                                
                                <?php 
                                // Calculate used backpacks
                                $all_assigned_backpack_ids = array_values($current_assignments);
                                
                                // Prepare data for JS (still needed for the render helper)
                                $user_backpacks_json = [];
                                
                                foreach ($available_users as $user): 
                                    $user_backpacks = get_available_backpacks_for_user($conn, $user['id'], $packing_list['household_id']);
                                    $my_current_bp_id = $current_assignments[$user['id']] ?? 0;
                                    
                                    // Store for JS
                                    $user_backpacks_json[$user['id']] = [
                                        'current_id' => $my_current_bp_id,
                                        'backpacks' => $user_backpacks
                                    ];
                                    
                                    // Use helper to render the widget
                                    echo '<div class="mb-4 border-bottom pb-3">';
                                    echo '<label class="form-label fw-bold mb-2">' . htmlspecialchars($user['username']) . '</label>';
                                    echo render_backpack_card_selector($user, $my_current_bp_id, $user_backpacks);
                                    echo '</div>';
                                endforeach; 
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <hr class="my-4">

                <div class="d-flex justify-content-between">
                    <a href="manage_packing_list_items.php?id=<?php echo $packing_list_id; ?>" class="btn btn-info text-white"><i class="fas fa-boxes me-2"></i>Inhalt bearbeiten</a>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Speichern & Synchronisieren</button>
                </div>
            </form>
        <?php endif; ?>
    </div>
</div>

<!-- Render Modal JS -->
<?php echo render_backpack_modal_script($user_backpacks_json, $all_assigned_backpack_ids); ?>

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