<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="fas fa-utensils me-2"></i>Menu Lokali</h2>
            <p class="text-muted">Zarządzaj pozycjami menu dostępnymi w lokalach</p>
        </div>
        <a href="/samanta_crm/menu/items/create" class="btn btn-primary">
            <i class="fas fa-plus me-2"></i>Dodaj Pozycję
        </a>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle me-2"></i><?= $_SESSION['success']; unset($_SESSION['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle me-2"></i><?= $_SESSION['error']; unset($_SESSION['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Szukaj</label>
                    <input type="text" name="search" class="form-control" placeholder="Nazwa, kod..." value="<?= htmlspecialchars($search) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Kategoria</label>
                    <select name="category" class="form-select">
                        <option value="">Wszystkie</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>" <?= $selectedCategory == $cat['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cat['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Lokalizacja</label>
                    <select name="location" class="form-select">
                        <option value="">Wszystkie</option>
                        <?php foreach ($locations as $loc): ?>
                            <option value="<?= $loc['id'] ?>" <?= $selectedLocation == $loc['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($loc['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="hide_no_location" id="hideNoLocation" value="1" <?= isset($_GET['hide_no_location']) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="hideNoLocation">
                            Ukryj bez lokalizacji
                        </label>
                    </div>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                    <button type="submit" class="btn btn-primary flex-fill">
                        <i class="fas fa-search me-1"></i>Filtruj
                    </button>
                    <a href="/samanta_crm/menu/items" class="btn btn-secondary">
                        <i class="fas fa-redo"></i>
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="d-flex gap-2 mb-3">
        <a href="/samanta_crm/menu/locations" class="btn btn-outline-primary btn-sm">
            <i class="fas fa-map-marker-alt me-1"></i>Zarządzaj Lokalizacjami
        </a>
        <a href="/samanta_crm/menu/categories" class="btn btn-outline-secondary btn-sm">
            <i class="fas fa-tags me-1"></i>Zarządzaj Kategoriami
        </a>
        <button type="button" class="btn btn-outline-info btn-sm" id="expandAll">
            <i class="fas fa-expand-alt me-1"></i>Rozwiń wszystkie
        </button>
        <button type="button" class="btn btn-outline-info btn-sm" id="collapseAll">
            <i class="fas fa-compress-alt me-1"></i>Zwiń wszystkie
        </button>
        <button type="button" class="btn btn-outline-success btn-sm" id="toggleLocations">
            <i class="fas fa-map-marked-alt me-1"></i>Show locations
        </button>
        <div class="btn-group">
            <button type="button" class="btn btn-outline-warning btn-sm dropdown-toggle" data-bs-toggle="dropdown">
                <i class="fas fa-eye me-1"></i>Podgląd Menu
            </button>
            <ul class="dropdown-menu">
                <?php foreach ($locations as $loc): ?>
                    <li>
                        <a class="dropdown-item" href="/samanta_crm/menu/preview/<?= $loc['id'] ?>" target="_blank">
                            <i class="fas fa-map-marker-alt me-1"></i><?= htmlspecialchars($loc['name']) ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>

    <!-- Grouped Menu Items -->
    <?php if (empty($groupedItems)): ?>
        <div class="card">
            <div class="card-body text-center py-5 text-muted">
                <i class="fas fa-inbox fa-3x mb-3 d-block"></i>
                <p class="mb-0">Brak pozycji menu</p>
            </div>
        </div>
    <?php else: ?>
        <div id="categories-container">
            <?php foreach ($groupedItems as $group): ?>
                <div class="card mb-3 category-group" data-category-id="<?= $group['id'] ?>">
                    <div class="card-header d-flex justify-content-between align-items-center category-header">
                        <div class="d-flex align-items-center gap-2">
                            <i class="fas fa-grip-vertical text-muted category-drag-handle"></i>
                            <h5 class="mb-0">
                                <i class="fas fa-chevron-down toggle-icon"></i>
                                <?= htmlspecialchars($group['name']) ?>
                                <span class="badge bg-secondary ms-2"><?= count($group['items']) ?></span>
                            </h5>
                        </div>
                        <small class="text-muted">Przeciągnij aby zmienić kolejność</small>
                    </div>
                    <div class="card-body category-items">
                        <div class="items-container" data-category-id="<?= $group['id'] ?>">
                            <?php foreach ($group['items'] as $item): ?>
                                <div class="card mb-2 menu-item" data-item-id="<?= $item['id'] ?>">
                                    <div class="card-body p-3">
                                        <div class="row align-items-center">
                                            <div class="col-auto">
                                                <i class="fas fa-grip-vertical text-muted item-drag-handle"></i>
                                            </div>
                                            <div class="col-md-4">
                                                <h4><?= htmlspecialchars($item['name_pl']) ?></h4>
                                                <?php if ($item['name_en']): ?>
                                                    <div class="text-muted small"><?= htmlspecialchars($item['name_en']) ?></div>
                                                <?php endif; ?>
                                                <?php if ($item['code']): ?>
                                                    <span class="badge bg-light text-dark"><?= htmlspecialchars($item['code']) ?></span>
                                                <?php endif; ?>
                                            </div>
                                            <div class="col-md-2">
                                                <?php if ($item['price_1']): ?>
                                                    <div><?= htmlspecialchars($item['price_1_prefix_pl'] ?? '') ?> <?= $item['price_1'] ?> zł</div>
                                                <?php endif; ?>
                                                <?php if ($item['price_2']): ?>
                                                    <div class="small text-muted"><?= htmlspecialchars($item['price_2_prefix_pl'] ?? '') ?> <?= $item['price_2'] ?> zł</div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="col-auto">
                                                <?php if (!empty($item['image_url'])): ?>
                                                    <img src="<?= htmlspecialchars($item['image_url']) ?>" 
                                                         alt="<?= htmlspecialchars($item['name_pl']) ?>" 
                                                         class="img-thumbnail" 
                                                         style="width: 60px; height: 60px; object-fit: cover;">
                                                <?php endif; ?>
                                            </div>
                                            <div class="col-md-2">
                                                <small class="text-muted">
                                                    <i class="fas fa-map-marker-alt me-1"></i>
                                                    <?= $item['location_names'] ?: 'Brak lokalizacji' ?>
                                                </small>
                                            </div>
                                            <div class="col-auto ms-auto">
                                                <a href="/samanta_crm/menu/items/<?= $item['id'] ?>/edit" class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form method="POST" action="/samanta_crm/menu/items/<?= $item['id'] ?>/delete" class="d-inline" onsubmit="return confirm('Czy na pewno chcesz usunąć tę pozycję?')">
                                                    <button class="btn btn-sm btn-outline-danger">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                        <!-- Location Toggles (hidden by default) -->
                                        <div class="location-toggles mt-3 pt-3 border-top" style="display: none;">
                                            <div class="row">
                                                <div class="col-12">
                                                    <strong class="text-muted small">Dostępność w lokalizacjach:</strong>
                                                    <div class="mt-2">
                                                        <?php 
                                                        $itemLocationIds = !empty($item['location_ids']) ? explode(',', $item['location_ids']) : [];
                                                        foreach ($locations as $loc): 
                                                            $isChecked = in_array($loc['id'], $itemLocationIds);
                                                        ?>
                                                            <div class="form-check form-check-inline">
                                                                <input class="form-check-input location-toggle" 
                                                                       type="checkbox" 
                                                                       data-item-id="<?= $item['id'] ?>"
                                                                       data-location-id="<?= $loc['id'] ?>"
                                                                       id="loc_<?= $item['id'] ?>_<?= $loc['id'] ?>"
                                                                       <?= $isChecked ? 'checked' : '' ?>>
                                                                <label class="form-check-label" for="loc_<?= $item['id'] ?>_<?= $loc['id'] ?>">
                                                                    <?= htmlspecialchars($loc['name']) ?>
                                                                </label>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Toggle locations visibility
    document.getElementById('toggleLocations')?.addEventListener('click', function() {
        const locationToggles = document.querySelectorAll('.location-toggles');
        const isVisible = locationToggles[0]?.style.display !== 'none';
        
        locationToggles.forEach(toggle => {
            toggle.style.display = isVisible ? 'none' : 'block';
        });
        
        this.innerHTML = isVisible 
            ? '<i class="fas fa-map-marked-alt me-1"></i>Show locations'
            : '<i class="fas fa-eye-slash me-1"></i>Hide locations';
    });
    
    // Handle location checkbox changes
    document.querySelectorAll('.location-toggle').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const itemId = this.dataset.itemId;
            const locationId = this.dataset.locationId;
            const enabled = this.checked;
            
            fetch('/samanta_crm/menu/items/toggle-location', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    item_id: itemId,
                    location_id: locationId,
                    enabled: enabled
                })
            })
            .then(r => r.json())
            .then(data => {
                if (!data.success) {
                    alert('Błąd: ' + (data.error || 'Nieznany błąd'));
                    this.checked = !enabled; // Revert checkbox
                } else {
                    // Optionally show success feedback
                    console.log('Location updated successfully');
                }
            })
            .catch(err => {
                console.error('Error:', err);
                alert('Błąd zapisywania');
                this.checked = !enabled; // Revert checkbox
            });
        });
    });
    
    // Category collapse state management
    const STORAGE_KEY = 'menuCategoryCollapseState';
    
    function loadCategoryStates() {
        try {
            const saved = localStorage.getItem(STORAGE_KEY);
            return saved ? JSON.parse(saved) : {};
        } catch (e) {
            return {};
        }
    }
    
    function saveCategoryState(categoryId, isCollapsed) {
        try {
            const states = loadCategoryStates();
            states[categoryId] = isCollapsed;
            localStorage.setItem(STORAGE_KEY, JSON.stringify(states));
        } catch (e) {
            console.error('Failed to save category state:', e);
        }
    }
    
    function applyCategoryStates() {
        const states = loadCategoryStates();
        document.querySelectorAll('.category-header').forEach(header => {
            const categoryGroup = header.closest('.category-group');
            const categoryId = categoryGroup?.dataset.categoryId;
            const body = header.nextElementSibling;
            const icon = header.querySelector('.toggle-icon');
            
            if (categoryId && states[categoryId] === true) {
                // Collapsed
                body.style.display = 'none';
                icon?.classList.remove('fa-chevron-down');
                icon?.classList.add('fa-chevron-right');
            } else {
                // Expanded (default)
                body.style.display = 'block';
                icon?.classList.remove('fa-chevron-right');
                icon?.classList.add('fa-chevron-down');
            }
        });
    }
    
    // Toggle category collapse
    document.querySelectorAll('.category-header').forEach(header => {
        header.addEventListener('click', function(e) {
            if (e.target.closest('.category-drag-handle')) return;
            
            const icon = this.querySelector('.toggle-icon');
            const body = this.nextElementSibling;
            const categoryGroup = this.closest('.category-group');
            const categoryId = categoryGroup?.dataset.categoryId;
            
            if (body.style.display === 'none') {
                body.style.display = 'block';
                icon.classList.remove('fa-chevron-right');
                icon.classList.add('fa-chevron-down');
                if (categoryId) saveCategoryState(categoryId, false);
            } else {
                body.style.display = 'none';
                icon.classList.remove('fa-chevron-down');
                icon.classList.add('fa-chevron-right');
                if (categoryId) saveCategoryState(categoryId, true);
            }
        });
    });
    
    // Load saved states on page load
    applyCategoryStates();
    
    // Expand/Collapse all
    document.getElementById('expandAll')?.addEventListener('click', function() {
        const states = {};
        document.querySelectorAll('.category-items').forEach(body => {
            body.style.display = 'block';
            const icon = body.previousElementSibling.querySelector('.toggle-icon');
            icon?.classList.remove('fa-chevron-right');
            icon?.classList.add('fa-chevron-down');
            
            const categoryGroup = body.closest('.category-group');
            const categoryId = categoryGroup?.dataset.categoryId;
            if (categoryId) states[categoryId] = false;
        });
        localStorage.setItem(STORAGE_KEY, JSON.stringify(states));
    });
    
    document.getElementById('collapseAll')?.addEventListener('click', function() {
        const states = {};
        document.querySelectorAll('.category-items').forEach(body => {
            body.style.display = 'none';
            const icon = body.previousElementSibling.querySelector('.toggle-icon');
            icon?.classList.remove('fa-chevron-down');
            icon?.classList.add('fa-chevron-right');
            
            const categoryGroup = body.closest('.category-group');
            const categoryId = categoryGroup?.dataset.categoryId;
            if (categoryId) states[categoryId] = true;
        });
        localStorage.setItem(STORAGE_KEY, JSON.stringify(states));
    });
    
    // Sortable categories
    const categoriesContainer = document.getElementById('categories-container');
    if (categoriesContainer) {
        new Sortable(categoriesContainer, {
            handle: '.category-drag-handle',
            animation: 150,
            ghostClass: 'sortable-ghost',
            onEnd: function(evt) {
                const categoryIds = Array.from(categoriesContainer.querySelectorAll('.category-group')).map(el => el.dataset.categoryId);
                
                fetch('/samanta_crm/menu/categories/reorder', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ order: categoryIds })
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        alert('Błąd: ' + (data.error || 'Nieznany błąd'));
                        location.reload();
                    }
                })
                .catch(err => {
                    console.error('Error:', err);
                    alert('Błąd zapisywania');
                    location.reload();
                });
            }
        });
    }
    
    // Sortable items within categories
    document.querySelectorAll('.items-container').forEach(container => {
        new Sortable(container, {
            handle: '.item-drag-handle',
            group: 'items',
            animation: 150,
            ghostClass: 'sortable-ghost',
            onEnd: function(evt) {
                const categoryId = evt.to.dataset.categoryId;
                const itemIds = Array.from(evt.to.querySelectorAll('.menu-item')).map(el => el.dataset.itemId);
                
                fetch('/samanta_crm/menu/items/reorder', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        category_id: categoryId,
                        order: itemIds 
                    })
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        alert('Błąd: ' + (data.error || 'Nieznany błąd'));
                        location.reload();
                    }
                })
                .catch(err => {
                    console.error('Error:', err);
                    alert('Błąd zapisywania');
                    location.reload();
                });
            }
        });
    });
});
</script>

<style>
.category-drag-handle, .item-drag-handle {
    cursor: grab !important;
}
.category-drag-handle:active, .item-drag-handle:active {
    cursor: grabbing !important;
}
.category-header {
    cursor: pointer;
    user-select: none;
}
.toggle-icon {
    transition: transform 0.2s;
    margin-right: 8px;
}
.sortable-ghost {
    opacity: 0.4;
    background: #f8f9fa;
}
</style>
