<?php
// backpack_utils.php - Shared functions for backpack management

function sync_backpack_items($conn, $list_id, $user_id, $backpack_id) {
    // 1. Get Backpack Info
    $bp = $conn->query("SELECT name FROM backpacks WHERE id = $backpack_id")->fetch_assoc();
    
    // 2. Check/Create Root Item
    $root_id = 0;
    $stmt = $conn->prepare("SELECT id FROM packing_list_items WHERE packing_list_id = ? AND carrier_user_id = ? AND backpack_id = ?");
    $stmt->bind_param("iii", $list_id, $user_id, $backpack_id);
    $stmt->execute();
    $res = $stmt->get_result();
    
    if ($row = $res->fetch_assoc()) {
        $root_id = $row['id'];
    } else {
        // Create Root
        $name = "Rucksack: " . $bp['name'];
        // Use correct column count and NULLs
        $stmt_ins = $conn->prepare("INSERT INTO packing_list_items (packing_list_id, carrier_user_id, name, backpack_id, quantity, article_id, order_index, parent_packing_list_item_id) VALUES (?, ?, ?, ?, 1, NULL, 0, NULL)");
        $stmt_ins->bind_param("iisi", $list_id, $user_id, $name, $backpack_id);
        $stmt_ins->execute();
        $root_id = $stmt_ins->insert_id;
    }

    // 3. Sync Compartments
    // FIX: Fetch linked_article_id as well
    $comps = $conn->query("SELECT id, name, linked_article_id FROM backpack_compartments WHERE backpack_id = $backpack_id ORDER BY sort_order ASC");
    while ($comp = $comps->fetch_assoc()) {
        // Check if item exists for this compartment AND this user
        $stmt_c = $conn->prepare("SELECT id FROM packing_list_items WHERE packing_list_id = ? AND backpack_compartment_id = ? AND carrier_user_id = ?");
        $stmt_c->bind_param("iii", $list_id, $comp['id'], $user_id);
        $stmt_c->execute();
        if ($stmt_c->get_result()->num_rows == 0) {
            // Create Compartment Item
            $c_name = $comp['name'];
            $c_article_id = !empty($comp['linked_article_id']) ? $comp['linked_article_id'] : NULL;
            
            // FIX: Insert linked article_id if present
            $stmt_ins_c = $conn->prepare("INSERT INTO packing_list_items (packing_list_id, carrier_user_id, name, backpack_compartment_id, parent_packing_list_item_id, quantity, article_id, order_index) VALUES (?, ?, ?, ?, ?, 1, ?, 0)");
            $stmt_ins_c->bind_param("iisiii", $list_id, $user_id, $c_name, $comp['id'], $root_id, $c_article_id);
            $stmt_ins_c->execute();
        }
    }
}

// Helper to get backpacks for a specific user context
function get_available_backpacks_for_user($conn, $target_user_id, $household_id) {
    // Check connection
    if (!$conn || $conn->connect_errno) {
        // Reconnect or fail gracefully? 
        // For now, assume caller must keep it open.
        return []; 
    }
    
    $bps = [];
    $sql_bp = "SELECT id, name, user_id, image_url FROM backpacks WHERE user_id = ?";
    if ($household_id) {
        $sql_bp .= " OR household_id = ?";
        $stmt_bp = $conn->prepare($sql_bp);
        $stmt_bp->bind_param("ii", $target_user_id, $household_id);
    } else {
        $stmt_bp = $conn->prepare($sql_bp);
        $stmt_bp->bind_param("i", $target_user_id);
    }
    $stmt_bp->execute();
    $res_bp = $stmt_bp->get_result();
    while ($row = $res_bp->fetch_assoc()) {
        $bps[] = $row;
    }
    return $bps;
}

/**
 * Renders the HTML for the Backpack Selection Card (Small widget per user)
 */
function render_backpack_card_selector($user, $current_bp_id, $user_backpacks) {
    // Find current details
    $current_bp_details = null;
    foreach ($user_backpacks as $bp) {
        if ($bp['id'] == $current_bp_id) {
            $current_bp_details = $bp;
            break;
        }
    }
    
    ob_start();
    ?>
    <input type="hidden" name="backpacks[<?php echo $user['id']; ?>]" id="input_bp_<?php echo $user['id']; ?>" value="<?php echo $current_bp_id; ?>">
    
    <div class="d-flex align-items-center">
        <!-- Selected Backpack Display -->
        <div id="display_bp_<?php echo $user['id']; ?>" class="flex-grow-1 p-2 border rounded bg-white d-flex align-items-center" style="min-height: 60px;">
            <?php if ($current_bp_details): ?>
                <?php if(!empty($current_bp_details['image_url'])): ?>
                    <img src="<?php echo htmlspecialchars($current_bp_details['image_url']); ?>" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;" class="me-2">
                <?php else: ?>
                    <i class="fas fa-hiking fa-2x text-muted me-2"></i>
                <?php endif; ?>
                <div>
                    <div class="fw-bold small"><?php echo htmlspecialchars($current_bp_details['name']); ?></div>
                </div>
            <?php else: ?>
                <span class="text-muted small fst-italic">Kein Rucksack zugewiesen</span>
            <?php endif; ?>
        </div>
        <button type="button" class="btn btn-sm btn-outline-primary ms-2" onclick="openBackpackModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')">
            <i class="fas fa-exchange-alt"></i>
        </button>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Renders the Modal HTML and the JS needed to drive it.
 * Needs $user_backpacks_json and $all_assigned_backpack_ids to be populated.
 */
function render_backpack_modal_script($user_backpacks_json, $all_assigned_backpack_ids) {
    ob_start();
    ?>
    <!-- Generic Modal -->
    <div class="modal fade" id="genericBpModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="genericBpModalTitle">Rucksack wählen</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body bg-light" id="genericBpModalBody">
                    <!-- Content loaded via JS -->
                </div>
            </div>
        </div>
    </div>

    <script>
    const userBackpacksData = <?php echo json_encode($user_backpacks_json); ?>;
    const allAssignedIds = <?php echo json_encode($all_assigned_backpack_ids); ?>;

    function openBackpackModal(userId, username) {
        const data = userBackpacksData[userId];
        if (!data) return; // Should not happen
        
        const currentBpId = data.current_id;
        const titleEl = document.getElementById('genericBpModalTitle');
        const bodyEl = document.getElementById('genericBpModalBody');
        
        titleEl.textContent = 'Rucksack für ' + username + ' wählen';
        
        let html = '<div class="row g-3">';
        
        // Option: None
        html += `
            <div class="col-md-4 col-6">
                <div class="card h-100 text-center p-3 bp-select-card ${currentBpId == 0 ? 'border-primary bg-white' : ''}" onclick="selectBackpack(${userId}, 0)">
                    <div class="card-body">
                        <i class="fas fa-times-circle fa-2x text-muted mb-2"></i>
                        <div class="small fw-bold">Kein Rucksack</div>
                    </div>
                </div>
            </div>
        `;
        
        data.backpacks.forEach(bp => {
            // Filter logic: Show if NOT assigned OR if assigned to ME
            const isAssigned = allAssignedIds.some(id => String(id) === String(bp.id));
            // Display logic: Show if free OR if it is my current one
            if (isAssigned && String(bp.id) !== String(currentBpId)) return;

            const imgHtml = bp.image_url ? `<img src="${bp.image_url}" class="card-img-top" style="height: 100px; object-fit: contain; padding: 10px;">` : `<div class="text-center py-4"><i class="fas fa-hiking fa-3x text-muted"></i></div>`;
            const activeClass = (String(bp.id) === String(currentBpId)) ? 'border-primary bg-white' : '';
            // Escape name for HTML attribute
            const safeName = bp.name.replace(/"/g, '&quot;');
            
            html += `
                <div class="col-md-4 col-6">
                    <div class="card h-100 bp-select-card ${activeClass}" onclick='selectBackpack(${userId}, ${bp.id})'>
                        ${imgHtml}
                        <div class="card-body p-2 text-center">
                            <div class="small fw-bold text-truncate">${bp.name}</div>
                        </div>
                    </div>
                </div>
            `;
        });
        
        html += '</div>';
        bodyEl.innerHTML = html;
        
        new bootstrap.Modal(document.getElementById('genericBpModal')).show();
    }

    function selectBackpack(userId, bpId) {
        // Update Logic Data first
        const oldId = userBackpacksData[userId].current_id;
        userBackpacksData[userId].current_id = bpId;
        
        // Update Global Assigned List
        // 1. Remove old ID if it was > 0
        if (oldId > 0) {
            const index = allAssignedIds.indexOf(parseInt(oldId)); // Ensure type matching
            if (index > -1) {
                allAssignedIds.splice(index, 1);
            } else {
                // Try string matching if int failed
                const indexStr = allAssignedIds.indexOf(String(oldId));
                if (indexStr > -1) allAssignedIds.splice(indexStr, 1);
            }
        }
        
        // 2. Add new ID if > 0
        if (bpId > 0) {
            allAssignedIds.push(parseInt(bpId));
        }

        // Update Hidden Input
        document.getElementById('input_bp_' + userId).value = bpId;
        
        // Find BP Data for display
        let bpName = 'Kein Rucksack zugewiesen';
        let bpImage = null;
        
        if (bpId > 0 && userBackpacksData[userId]) {
            const data = userBackpacksData[userId];
            const bp = data.backpacks.find(b => String(b.id) === String(bpId));
            if (bp) {
                bpName = bp.name;
                bpImage = bp.image_url;
            }
        }
        
        // Update Display
        const displayDiv = document.getElementById('display_bp_' + userId);
        let html = '';
        if (bpId == 0) {
            html = '<span class="text-muted small fst-italic">Kein Rucksack zugewiesen</span>';
        } else {
            if (bpImage) {
                html += '<img src="' + bpImage + '" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;" class="me-2">';
            } else {
                html += '<i class="fas fa-hiking fa-2x text-muted me-2"></i>';
            }
            html += '<div><div class="fw-bold small">' + bpName + '</div></div>';
        }
        displayDiv.innerHTML = html;
        
        // Close Modal
        const modalEl = document.getElementById('genericBpModal');
        const modal = bootstrap.Modal.getInstance(modalEl);
        modal.hide();
    }
    </script>

    <style>
    .bp-select-card { cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; border: 1px solid rgba(0,0,0,0.1); }
    .bp-select-card:hover { transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); border-color: var(--color-primary); }
    </style>
    <?php
    return ob_get_clean();
}
?>