<?php
/**
 * Bulk Actions Bar Component
 * Erscheint wenn Items ausgewählt sind
 */
?>

<style>
.bulk-actions-bar {
    position: fixed;
    top: 80px;
    left: 50%;
    transform: translateX(-50%);
    background: linear-gradient(135deg, #5f8aec 0%, #8b7bc4 100%);
    color: white;
    padding: 12px 25px;
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
    z-index: 1000;
    display: none;
    min-width: 700px;
    animation: slideDown 0.3s ease;
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateX(-50%) translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateX(-50%) translateY(0);
    }
}

.bulk-actions-bar.active {
    display: block;
}

.bulk-actions-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

.bulk-actions-count {
    font-size: 15px;
    font-weight: 600;
}

.bulk-actions-buttons {
    display: flex;
    gap: 6px;
    flex-wrap: nowrap;
    justify-content: center;
}

.bulk-btn {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    padding: 6px 12px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    white-space: nowrap;
}

.bulk-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-1px);
}

.bulk-btn.danger {
    background: rgba(231, 76, 60, 0.9);
    border-color: rgba(192, 57, 43, 0.5);
}

.bulk-btn.danger:hover {
    background: rgba(192, 57, 43, 1);
}

.bulk-btn.secondary {
    background: rgba(149, 165, 166, 0.2);
}

.bulk-btn.secondary:hover {
    background: rgba(149, 165, 166, 0.3);
}

/* Mobile Anpassung */
@media (max-width: 768px) {
    .bulk-actions-bar {
        min-width: auto;
        left: 10px;
        right: 10px;
        transform: none;
        padding: 12px 15px;
    }
    
    .bulk-actions-buttons {
        flex-direction: column;
    }
    
    .bulk-btn {
        width: 100%;
        justify-content: center;
    }
}
</style>

<!-- Bulk Actions Bar (hidden by default) -->
<div class="bulk-actions-bar" id="bulkActionsBar">
    <div class="bulk-actions-header">
        <div class="bulk-actions-count">
            <span id="selectedCount">0</span> <span id="selectedText">Einträge ausgewählt</span>
        </div>
    </div>
    
    <div class="bulk-actions-buttons">
        <button type="button" class="bulk-btn" id="bulkCategoryBtn">
            📦 Kategorie ändern
        </button>
        
        <button type="button" class="bulk-btn" id="bulkLocationBtn">
            📍 Ort ändern
        </button>
        
        <button type="button" class="bulk-btn" id="bulkHideBtn">
            👁️ Verbergen
        </button>
        
        <button type="button" class="bulk-btn" id="bulkUnhideBtn" style="display: none;">
            ✨ Wieder anzeigen
        </button>
        
        <button type="button" class="bulk-btn" id="bulkExportBtn">
            📤 Exportieren
        </button>
        
        <button type="button" class="bulk-btn danger" id="bulkDeleteBtn">
            🗑️ Löschen
        </button>
        
        <button type="button" class="bulk-btn secondary" id="bulkClearBtn">
            ✖ Auswahl aufheben
        </button>
    </div>
</div>

<script>
// Bulk Actions Manager
class BulkActionsManager {
    constructor() {
        this.selectedItems = new Set();
        this.bar = document.getElementById('bulkActionsBar');
        this.countElement = document.getElementById('selectedCount');
        this.selectAllCheckbox = document.getElementById('selectAll');
        this.init();
    }
    
    init() {
        // "Alle auswählen" Checkbox
        if (this.selectAllCheckbox) {
            this.selectAllCheckbox.addEventListener('change', (e) => {
                this.toggleAll(e.target.checked);
            });
        }
        
        // Einzelne Checkboxen
        document.querySelectorAll('.item-checkbox, .bulk-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                this.toggleItem(e.target.value, e.target.checked);
            });
        });
        
        // Button Events
        document.getElementById('bulkClearBtn')?.addEventListener('click', () => this.clearSelection());
        document.getElementById('bulkDeleteBtn')?.addEventListener('click', () => this.bulkDelete());
        document.getElementById('bulkCategoryBtn')?.addEventListener('click', () => this.bulkChangeCategory());
        document.getElementById('bulkLocationBtn')?.addEventListener('click', () => this.bulkChangeLocation());
        document.getElementById('bulkHideBtn')?.addEventListener('click', () => this.bulkHide());
        document.getElementById('bulkUnhideBtn')?.addEventListener('click', () => this.bulkUnhide());
        document.getElementById('bulkExportBtn')?.addEventListener('click', () => this.bulkExport());
    }
    
    toggleAll(checked) {
        document.querySelectorAll('.item-checkbox, .bulk-checkbox').forEach(checkbox => {
            checkbox.checked = checked;
            this.toggleItem(checkbox.value, checked);
        });
    }
    
    toggleItem(itemId, checked) {
        if (checked) {
            this.selectedItems.add(itemId);
        } else {
            this.selectedItems.delete(itemId);
            // "Alle auswählen" deaktivieren wenn nicht mehr alle ausgewählt
            if (this.selectAllCheckbox) {
                this.selectAllCheckbox.checked = false;
            }
        }
        this.updateUI();
    }
    
    updateUI() {
        const count = this.selectedItems.size;
        this.countElement.textContent = count;
        
        // Singular/Plural Text
        const textElement = document.getElementById('selectedText');
        if (textElement) {
            textElement.textContent = count === 1 ? 'Eintrag ausgewählt' : 'Einträge ausgewählt';
        }
        
        if (count > 0) {
            this.bar.classList.add('active');
            
            // Prüfe ob verborgene Items ausgewählt sind
            const hasHidden = this.hasHiddenItems();
            document.getElementById('bulkHideBtn').style.display = hasHidden ? 'none' : 'inline-flex';
            document.getElementById('bulkUnhideBtn').style.display = hasHidden ? 'inline-flex' : 'none';
        } else {
            this.bar.classList.remove('active');
        }
    }
    
    hasHiddenItems() {
        // Prüfe ob eines der ausgewählten Items das 👁️ Icon hat
        for (const id of this.selectedItems) {
            const checkbox = document.querySelector(`.item-checkbox[value="${id}"], .bulk-checkbox[value="${id}"]`);
            if (checkbox) {
                const row = checkbox.closest('tr');
                if (row && row.innerHTML.includes('👁️')) {
                    return true;
                }
            }
        }
        return false;
    }
    
    clearSelection() {
        this.selectedItems.clear();
        document.querySelectorAll('.item-checkbox, .bulk-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
        if (this.selectAllCheckbox) {
            this.selectAllCheckbox.checked = false;
        }
        this.updateUI();
    }
    
    getSelectedIds() {
        return Array.from(this.selectedItems);
    }
    
    bulkDelete() {
        const ids = this.getSelectedIds();
        if (ids.length === 0) return;
        
        if (!confirm(`Wirklich ${ids.length} Einträge löschen?`)) return;
        
        this.performBulkAction('bulk_delete.php', ids, 'Einträge gelöscht');
    }
    
    bulkChangeCategory() {
        const ids = this.getSelectedIds();
        if (ids.length === 0) return;
        
        // Modal öffnen
        const modal = document.getElementById('categoryModal');
        if (modal) {
            modal.classList.add('active');
            document.getElementById('categoryModalCount').textContent = ids.length;
        }
    }
    
    bulkChangeLocation() {
        const ids = this.getSelectedIds();
        if (ids.length === 0) return;
        
        // Modal öffnen
        const modal = document.getElementById('locationModal');
        if (modal) {
            modal.classList.add('active');
            document.getElementById('locationModalCount').textContent = ids.length;
        }
    }
    
    bulkHide() {
        const ids = this.getSelectedIds();
        if (ids.length === 0) return;
        
        if (!confirm(`${ids.length} Einträge verbergen?`)) return;
        
        this.performBulkAction('bulk_hide.php', ids, 'Einträge verborgen');
    }
    
    bulkUnhide() {
        const ids = this.getSelectedIds();
        if (ids.length === 0) return;
        
        if (!confirm(`${ids.length} Einträge wieder anzeigen?`)) return;
        
        // Mit hide=false Parameter
        fetch('bulk_hide.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ids: ids, hide: false })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert('Einträge wieder sichtbar: ' + data.affected);
                location.reload();
            } else {
                alert('Fehler: ' + (data.error || 'Unbekannt'));
            }
        })
        .catch(err => alert('Fehler: ' + err.message));
    }
    
    bulkExport() {
        const ids = this.getSelectedIds();
        if (ids.length === 0) return;
        
        // CSV Export mit nur ausgewählten Items
        window.location.href = 'export_csv.php?ids=' + ids.join(',');
    }
    
    performBulkAction(url, ids, successMessage) {
        fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ids: ids })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert(successMessage + ': ' + data.affected);
                location.reload();
            } else {
                alert('Fehler: ' + (data.error || 'Unbekannt'));
            }
        })
        .catch(err => alert('Fehler: ' + err.message));
    }
}

// Initialisieren wenn DOM ready
document.addEventListener('DOMContentLoaded', function() {
    window.bulkActions = new BulkActionsManager();
});
</script>

<!-- Category Change Modal -->
<div class="bulk-modal" id="categoryModal">
    <div class="bulk-modal-overlay" onclick="closeCategoryModal()"></div>
    <div class="bulk-modal-content">
        <div class="bulk-modal-header">
            <h3>📦 Kategorie ändern</h3>
            <button class="bulk-modal-close" onclick="closeCategoryModal()">✕</button>
        </div>
        
        <div class="bulk-modal-body">
            <p class="bulk-modal-info">
                <strong id="categoryModalCount">0</strong> Gegenstände ausgewählt
            </p>
            
            <div class="form-group">
                <label for="newCategory">Neue Kategorie:</label>
                <select id="newCategory" class="form-control" required>
                    <option value="">-- Kategorie wählen --</option>
                    <?php
                    // Kategorien laden - nur wenn $db existiert
                    if (isset($db) && is_object($db)) {
                        try {
                            $kategorien = @$db->select("SELECT id, name FROM kategorien ORDER BY name");
                            if (is_array($kategorien)) {
                                foreach ($kategorien as $kat) {
                                    echo '<option value="' . intval($kat['id']) . '">' . htmlspecialchars($kat['name']) . '</option>';
                                }
                            }
                        } catch (Exception $e) {
                            // Fehler ignorieren
                        }
                    }
                    ?>
                </select>
            </div>
        </div>
        
        <div class="bulk-modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeCategoryModal()">
                Abbrechen
            </button>
            <button type="button" class="btn btn-primary" onclick="submitCategoryChange()">
                Ändern
            </button>
        </div>
    </div>
</div>

<!-- Location Change Modal -->
<div class="bulk-modal" id="locationModal">
    <div class="bulk-modal-overlay" onclick="closeLocationModal()"></div>
    <div class="bulk-modal-content">
        <div class="bulk-modal-header">
            <h3>📍 Ort ändern</h3>
            <button class="bulk-modal-close" onclick="closeLocationModal()">✕</button>
        </div>
        
        <div class="bulk-modal-body">
            <p class="bulk-modal-info">
                <strong id="locationModalCount">0</strong> Gegenstände ausgewählt
            </p>
            
            <div class="form-group">
                <label for="newLocation">Neuer Ort:</label>
                <select id="newLocation" class="form-control" required>
                    <option value="">-- Ort wählen --</option>
                    <?php
                    // Orte laden - nur wenn $db existiert
                    if (isset($db) && is_object($db)) {
                        try {
                            $raeume = @$db->select("SELECT id, name FROM orte ORDER BY name");
                            if (is_array($raeume)) {
                                foreach ($raeume as $ort) {
                                    echo '<option value="' . intval($ort['id']) . '">' . htmlspecialchars($ort['name']) . '</option>';
                                }
                            }
                        } catch (Exception $e) {
                            // Fehler ignorieren
                        }
                    }
                    ?>
                </select>
            </div>
        </div>
        
        <div class="bulk-modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeLocationModal()">
                Abbrechen
            </button>
            <button type="button" class="btn btn-primary" onclick="submitLocationChange()">
                Ändern
            </button>
        </div>
    </div>
</div>

<style>
/* Modal Styling */
.bulk-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10000;
    animation: fadeIn 0.2s ease;
}

.bulk-modal.active {
    display: block;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.bulk-modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(4px);
}

.bulk-modal-content {
    position: relative;
    max-width: 500px;
    margin: 100px auto;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    animation: slideUp 0.3s ease;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.bulk-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 25px;
    border-bottom: 1px solid #e0e0e0;
}

.bulk-modal-header h3 {
    margin: 0;
    font-size: 20px;
    color: #333;
}

.bulk-modal-close {
    background: none;
    border: none;
    font-size: 28px;
    line-height: 1;
    color: #999;
    cursor: pointer;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    transition: all 0.2s;
}

.bulk-modal-close:hover {
    background: #f0f0f0;
    color: #333;
}

.bulk-modal-body {
    padding: 25px;
}

.bulk-modal-info {
    background: #f8f9ff;
    border-left: 4px solid #667eea;
    padding: 12px 15px;
    margin-bottom: 20px;
    border-radius: 4px;
    color: #555;
}

.bulk-modal-info strong {
    color: #667eea;
    font-size: 18px;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #333;
}

.form-control {
    width: 100%;
    padding: 10px 15px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 15px;
    transition: border-color 0.2s;
}

.form-control:focus {
    outline: none;
    border-color: #667eea;
}

.bulk-modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 20px 25px;
    border-top: 1px solid #e0e0e0;
    background: #f8f9fa;
    border-radius: 0 0 16px 16px;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-secondary {
    background: #e0e0e0;
    color: #666;
}

.btn-secondary:hover {
    background: #d0d0d0;
}

.btn-primary {
    background: #667eea;
    color: white;
}

.btn-primary:hover {
    background: #5568d3;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* Mobile Anpassung */
@media (max-width: 768px) {
    .bulk-modal-content {
        margin: 20px;
        max-width: none;
    }
}
</style>

<script>
// Modal Functions
function closeCategoryModal() {
    document.getElementById('categoryModal').classList.remove('active');
    document.getElementById('newCategory').value = '';
}

function closeLocationModal() {
    document.getElementById('locationModal').classList.remove('active');
    document.getElementById('newLocation').value = '';
}

function submitCategoryChange() {
    const categoryId = document.getElementById('newCategory').value;
    if (!categoryId) {
        alert('Bitte wähle eine Kategorie aus!');
        return;
    }
    
    const ids = window.bulkActions.getSelectedIds();
    
    // Via bulk_update.php senden
    fetch('bulk_update.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            action: 'change_category',
            ids: ids,
            category_id: categoryId
        })
    })
    .then(res => {
        // Prüfe Content-Type
        const contentType = res.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            return res.text().then(text => {
                throw new Error('Server returned non-JSON response: ' + text.substring(0, 200));
            });
        }
        return res.json();
    })
    .then(data => {
        if (data.success) {
            alert(`${data.affected} Gegenstände aktualisiert!`);
            closeCategoryModal();
            location.reload();
        } else {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
        }
    })
    .catch(err => {
        console.error('Full error:', err);
        alert('Fehler: ' + err.message);
    });
}

function submitLocationChange() {
    const locationId = document.getElementById('newLocation').value;
    if (!locationId) {
        alert('Bitte wähle einen Ort aus!');
        return;
    }
    
    const ids = window.bulkActions.getSelectedIds();
    
    // Via bulk_update.php senden
    fetch('bulk_update.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            action: 'change_location',
            ids: ids,
            location_id: locationId
        })
    })
    .then(res => {
        // Prüfe Content-Type
        const contentType = res.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            return res.text().then(text => {
                throw new Error('Server returned non-JSON response: ' + text.substring(0, 200));
            });
        }
        return res.json();
    })
    .then(data => {
        if (data.success) {
            alert(`${data.affected} Gegenstände aktualisiert!`);
            closeLocationModal();
            location.reload();
        } else {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
        }
    })
    .catch(err => {
        console.error('Full error:', err);
        alert('Fehler: ' + err.message);
    });
}

// ESC zum Schließen
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        closeCategoryModal();
        closeLocationModal();
    }
});
</script>
