<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🐱 UWU Cafe - Bestellverwaltung</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            display: flex;
            height: 90vh;
        }

        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 2px solid #e9ecef;
            padding: 20px;
            overflow-y: auto;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 5px;
        }

        .nav-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

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

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #e9ecef;
            color: #333;
        }

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

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .section-title {
            font-size: 18px;
            font-weight: 700;
            color: #333;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        .section {
            margin-bottom: 25px;
        }

        .item-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
            max-height: 200px;
            overflow-y: auto;
        }

        .item {
            padding: 10px;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .item:hover {
            background: #f8f9fa;
            border-color: #667eea;
            transform: translateX(5px);
        }

        .item.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .item-name {
            font-weight: 600;
            font-size: 14px;
        }

        .item-info {
            font-size: 12px;
            opacity: 0.7;
            margin-top: 3px;
        }

        .content-area {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .tabs {
            display: flex;
            gap: 5px;
            margin-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
            overflow-x: auto;
            padding-bottom: 10px;
        }

        .tab {
            padding: 10px 20px;
            background: #f8f9fa;
            border: none;
            border-radius: 8px 8px 0 0;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.2s;
            white-space: nowrap;
            position: relative;
        }

        .tab:hover {
            background: #e9ecef;
        }

        .tab.active {
            background: white;
            color: #667eea;
            border-bottom: 3px solid #667eea;
            margin-bottom: -2px;
        }

        .tab-close {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            cursor: pointer;
            font-size: 18px;
            color: #999;
        }

        .tab-close:hover {
            color: #dc3545;
        }

        .bestellung-details {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .bestellung-header {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
        }

        .info-box {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
        }

        .info-label {
            font-size: 12px;
            color: #666;
            font-weight: 600;
            text-transform: uppercase;
            margin-bottom: 5px;
        }

        .info-value {
            font-size: 18px;
            font-weight: 700;
            color: #333;
        }

        .artikel-liste {
            margin-bottom: 20px;
        }

        .artikel-item {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr auto;
            align-items: center;
            gap: 15px;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 6px;
            margin-bottom: 8px;
            border-left: 4px solid #667eea;
        }

        .artikel-name {
            font-weight: 600;
            color: #333;
        }

        .artikel-menge {
            text-align: center;
            color: #666;
        }

        .artikel-preis {
            text-align: right;
            font-weight: 600;
            color: #667eea;
            font-size: 18px;
        }

        .artikel-remove {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .artikel-remove:hover {
            background: #c82333;
        }

        .add-artikel-form {
            display: grid;
            grid-template-columns: 1fr 1fr auto;
            gap: 10px;
            margin-bottom: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .form-group label {
            font-size: 12px;
            font-weight: 600;
            color: #666;
            text-transform: uppercase;
        }

        .form-group input,
        .form-group select {
            padding: 10px;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .rabatt-section {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .rabatt-title {
            font-weight: 600;
            margin-bottom: 10px;
            color: #856404;
        }

        .rabatt-inputs {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 10px;
        }

        .status-select {
            padding: 10px;
            border: 2px solid #667eea;
            border-radius: 6px;
            font-weight: 600;
            cursor: pointer;
            font-size: 14px;
        }

        .status-neue_bestellung { color: #0d6efd; }
        .status-in_zubereitung { color: #ff8c00; }
        .status-fertig { color: #28a745; }
        .status-bezahlt { color: #6c757d; }

        .lager-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
        }

        .lager-card {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            transition: all 0.2s;
        }

        .lager-card:hover {
            border-color: #667eea;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .lager-card.low-stock {
            border-color: #dc3545;
            background: #fff5f5;
        }

        .lager-card-title {
            font-weight: 700;
            font-size: 16px;
            margin-bottom: 10px;
            color: #333;
        }

        .lager-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 14px;
        }

        .lager-label {
            color: #666;
        }

        .lager-value {
            font-weight: 600;
            color: #333;
        }

        .warning-badge {
            background: #dc3545;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            margin-top: 8px;
            display: inline-block;
        }

        .statistik-card {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .statistik-title {
            font-weight: 700;
            font-size: 16px;
            margin-bottom: 10px;
            color: #333;
        }

        .statistik-info {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            color: #666;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: 15px;
            padding: 30px;
            max-width: 500px;
            width: 90%;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        .modal-title {
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 20px;
            color: #333;
        }

        .modal-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .modal-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .loading {
            text-align: center;
            color: #999;
            padding: 40px;
            font-size: 16px;
        }

        .update-indicator {
            display: none;
            background: #28a745;
            color: white;
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 10px;
            animation: fadeOut 2s ease-in-out;
        }

        .update-indicator.show {
            display: block;
        }

        @keyframes fadeOut {
            0% { opacity: 1; }
            90% { opacity: 1; }
            100% { opacity: 0; }
        }

        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                height: auto;
            }

            .sidebar {
                width: 100%;
                max-height: 200px;
                overflow-x: auto;
            }

            .bestellung-header {
                grid-template-columns: 1fr;
            }

            .rabatt-inputs {
                grid-template-columns: 1fr;
            }

            .artikel-item {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Sidebar -->
        <div class="sidebar">
            <h2 style="color: #667eea; margin-bottom: 20px;">🐱 UWU Cafe</h2>

            <!-- Navigation -->
            <div class="section">
                <div class="nav-buttons">
                    <button class="btn btn-primary" onclick="switchView('bestellungen')">📋 Bestellungen</button>
                    <button class="btn btn-secondary" onclick="switchView('lager')">📦 Lager</button>
                    <button class="btn btn-secondary" onclick="switchView('statistiken')">📊 Statistiken</button>
                </div>
            </div>

            <!-- Bestellungen Liste -->
            <div class="section" id="bestellungen-sidebar" style="display: none;">
                <div class="section-title">Aktive Bestellungen</div>
                <div class="nav-buttons">
                    <button class="btn btn-success" onclick="openNewBestellungModal()">+ Neue Bestellung</button>
                </div>
                <div class="item-list" id="bestellungen-list"></div>
            </div>

            <!-- Lager Navigation -->
            <div class="section" id="lager-sidebar" style="display: none;">
                <div class="section-title">Lager</div>
                <div class="nav-buttons">
                    <button class="btn btn-success" onclick="openNewProduktModal()">+ Neues Produkt</button>
                </div>
                <div id="kategorien-list" class="item-list"></div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="main-content">
            <div class="header">
                <h1>🐱 UWU Cafe - Bestellverwaltung</h1>
                <p>Live Verwaltung für dein Cafe</p>
            </div>

            <div class="content-area">
                <div id="update-indicator" class="update-indicator">✓ Daten aktualisiert</div>

                <!-- Bestellungen View -->
                <div id="bestellungen-view">
                    <div class="nav-buttons">
                        <button class="btn btn-success" onclick="openNewBestellungModal()">+ Neue Bestellung</button>
                        <button class="btn btn-secondary" onclick="filterBestellungen('alle')">Alle</button>
                        <button class="btn btn-secondary" onclick="filterBestellungen('neue_bestellung')">Neu</button>
                        <button class="btn btn-secondary" onclick="filterBestellungen('in_zubereitung')">In Zubereitung</button>
                        <button class="btn btn-secondary" onclick="filterBestellungen('fertig')">Fertig</button>
                        <button class="btn btn-secondary" onclick="filterBestellungen('bezahlt')">Bezahlt</button>
                    </div>

                    <div class="tabs" id="tabs-container"></div>

                    <div id="bestellung-content"></div>
                </div>

                <!-- Lager View -->
                <div id="lager-view" style="display: none;">
                    <div class="nav-buttons">
                        <button class="btn btn-success" onclick="openNewProduktModal()">+ Neues Produkt</button>
                    </div>
                    <div class="lager-grid" id="lager-content"></div>
                </div>

                <!-- Statistiken View -->
                <div id="statistiken-view" style="display: none;">
                    <div class="nav-buttons">
                        <button class="btn btn-secondary" onclick="loadStatistiken('tag')">Heute</button>
                        <button class="btn btn-secondary" onclick="loadStatistiken('woche')">Diese Woche</button>
                        <button class="btn btn-secondary" onclick="loadStatistiken('monat')">Dieser Monat</button>
                    </div>
                    <div id="statistiken-content"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal für neue Bestellung -->
    <div class="modal" id="bestellung-modal">
        <div class="modal-content">
            <div class="modal-title">Neue Bestellung</div>
            <div class="modal-form">
                <div class="form-group">
                    <label>Name der Bestellung (z.B. Tisch 5, Customer Name)</label>
                    <input type="text" id="bestellung-name" placeholder="Name eingeben..." />
                </div>
                <div class="modal-buttons">
                    <button class="btn btn-primary" onclick="createBestellung()">Erstellen</button>
                    <button class="btn btn-secondary" onclick="closeModal('bestellung-modal')">Abbrechen</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal für neues Produkt -->
    <div class="modal" id="produkt-modal">
        <div class="modal-content">
            <div class="modal-title">Neues Produkt</div>
            <div class="modal-form">
                <div class="form-group">
                    <label>Produktname</label>
                    <input type="text" id="produkt-name" placeholder="z.B. Cappuccino" />
                </div>
                <div class="form-group">
                    <label>Preis (€)</label>
                    <input type="number" id="produkt-preis" placeholder="3.50" step="0.01" />
                </div>
                <div class="form-group">
                    <label>Bestand</label>
                    <input type="number" id="produkt-bestand" placeholder="50" />
                </div>
                <div class="form-group">
                    <label>Bestandswarnung ab</label>
                    <input type="number" id="produkt-warnung" placeholder="10" />
                </div>
                <div class="form-group">
                    <label>Kategorie</label>
                    <input type="text" id="produkt-kategorie" placeholder="z.B. Kaffee" />
                </div>
                <div class="modal-buttons">
                    <button class="btn btn-primary" onclick="createProdukt()">Erstellen</button>
                    <button class="btn btn-secondary" onclick="closeModal('produkt-modal')">Abbrechen</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let aktuelleBestellung = null;
        let bestellungen = [];
        let produkte = [];
        let openTabs = [];
        let aktuellterFilter = 'neue_bestellung';

        // Initialisierung
        document.addEventListener('DOMContentLoaded', () => {
            switchView('bestellungen');
            loadBestellungen();
            loadProdukte();
            loadLager();
            
            // Auto-refresh alle 2 Sekunden
            setInterval(() => {
                loadBestellungen();
                loadLager();
            }, 2000);
        });

        // ============== VIEW SWITCHING ==============
        function switchView(view) {
            document.getElementById('bestellungen-view').style.display = view === 'bestellungen' ? 'block' : 'none';
            document.getElementById('lager-view').style.display = view === 'lager' ? 'block' : 'none';
            document.getElementById('statistiken-view').style.display = view === 'statistiken' ? 'block' : 'none';
            
            document.getElementById('bestellungen-sidebar').style.display = view === 'bestellungen' ? 'block' : 'none';
            document.getElementById('lager-sidebar').style.display = view === 'lager' ? 'block' : 'none';
            
            if (view === 'statistiken') {
                loadStatistiken('woche');
            }
        }

        // ============== BESTELLUNGEN ==============
        async function loadBestellungen() {
            try {
                const response = await fetch(`api.php?action=get_bestellungen&status=${aktuellterFilter}`);
                bestellungen = await response.json();
                renderBestellungenList();
                renderTabs();
            } catch (e) {
                console.error('Fehler beim Laden:', e);
            }
        }

        function renderBestellungenList() {
            const list = document.getElementById('bestellungen-list');
            list.innerHTML = '';

            bestellungen.forEach(b => {
                const item = document.createElement('div');
                item.className = 'item' + (aktuelleBestellung?.id === b.id ? ' active' : '');
                item.innerHTML = `
                    <div class="item-name">${b.name}</div>
                    <div class="item-info">${b.artikel_count} Artikel • ${b.status.replace('_', ' ')}</div>
                `;
                item.onclick = () => selectBestellung(b);
                list.appendChild(item);
            });
        }

        function renderTabs() {
            const container = document.getElementById('tabs-container');
            container.innerHTML = '';

            bestellungen.forEach(b => {
                const tab = document.createElement('button');
                tab.className = 'tab' + (aktuelleBestellung?.id === b.id ? ' active' : '');
                tab.innerHTML = `
                    <span>${b.name}</span>
                    <span style="font-size: 12px; margin-left: 5px;">${b.artikel_count}x</span>
                    <button class="tab-close" onclick="event.stopPropagation(); deleteBestellung(${b.id})">×</button>
                `;
                tab.onclick = () => selectBestellung(b);
                container.appendChild(tab);
            });
        }

        async function selectBestellung(bestellung) {
            aktuelleBestellung = bestellung;
            renderBestellungenList();
            renderTabs();
            renderBestellungDetails();
        }

        async function renderBestellungDetails() {
            if (!aktuelleBestellung) {
                document.getElementById('bestellung-content').innerHTML = '<div class="loading">Wähle eine Bestellung aus</div>';
                return;
            }

            try {
                const response = await fetch(`api.php?action=get_bestellung&id=${aktuelleBestellung.id}`);
                const data = await response.json();
                const b = data.bestellung;
                const positionen = data.positionen;

                let gesamt = positionen.reduce((sum, p) => sum + parseFloat(p.preis), 0);
                let rabattBetrag = 0;

                if (b.rabatt_typ === 'prozent') {
                    rabattBetrag = gesamt * (b.rabatt_wert / 100);
                    gesamt = gesamt - rabattBetrag;
                } elseif (b.rabatt_typ === 'betrag') {
                    rabattBetrag = b.rabatt_wert;
                    gesamt = gesamt - rabattBetrag;
                } else if (b.rabatt_typ === 'endergebnis') {
                    rabattBetrag = gesamt - b.rabatt_wert;
                    gesamt = b.rabatt_wert;
                }

                let html = `
                    <div class="bestellung-details">
                        <div class="bestellung-header">
                            <div class="info-box">
                                <div class="info-label">Bestellung</div>
                                <div class="info-value">${b.name}</div>
                            </div>
                            <div class="info-box">
                                <div class="info-label">Status</div>
                                <select class="status-select status-${b.status}" onchange="updateStatus(${b.id}, this.value)">
                                    <option value="neue_bestellung" ${b.status === 'neue_bestellung' ? 'selected' : ''}>Neu</option>
                                    <option value="in_zubereitung" ${b.status === 'in_zubereitung' ? 'selected' : ''}>In Zubereitung</option>
                                    <option value="fertig" ${b.status === 'fertig' ? 'selected' : ''}>Fertig</option>
                                    <option value="bezahlt" ${b.status === 'bezahlt' ? 'selected' : ''}>Bezahlt</option>
                                </select>
                            </div>
                            <div class="info-box">
                                <div class="info-label">Gesamtpreis</div>
                                <div class="info-value">€ ${gesamt.toFixed(2)}</div>
                            </div>
                        </div>

                        <div class="artikel-liste">
                            <div class="section-title">Artikel</div>
                            ${positionen.map(p => `
                                <div class="artikel-item">
                                    <div class="artikel-name">${p.name}</div>
                                    <div class="artikel-menge">${p.menge}x</div>
                                    <div class="artikel-preis">€ ${p.preis.toFixed(2)}</div>
                                    <button class="artikel-remove" onclick="removeArtikel(${b.id}, ${p.id})">Entfernen</button>
                                </div>
                            `).join('')}
                        </div>

                        <div class="add-artikel-form">
                            <div class="form-group">
                                <label>Artikel</label>
                                <select id="artikel-select">
                                    <option value="">-- Wähle ein Produkt --</option>
                                    ${produkte.map(p => `<option value="${p.id}" data-name="${p.name}" data-preis="${p.preis}">${p.name} (€${p.preis.toFixed(2)})</option>`).join('')}
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Menge</label>
                                <input type="number" id="artikel-menge" value="1" min="1" />
                            </div>
                            <button class="btn btn-success" onclick="addArtikel(${b.id})">+ Hinzufügen</button>
                        </div>

                        <div class="rabatt-section">
                            <div class="rabatt-title">🎉 Rabatt</div>
                            <div class="rabatt-inputs">
                                <div class="form-group">
                                    <label>Art</label>
                                    <select id="rabatt-typ">
                                        <option value="keine" ${b.rabatt_typ === 'keine' ? 'selected' : ''}>Kein Rabatt</option>
                                        <option value="prozent" ${b.rabatt_typ === 'prozent' ? 'selected' : ''}>Prozent %</option>
                                        <option value="betrag" ${b.rabatt_typ === 'betrag' ? 'selected' : ''}>Betrag abziehen €</option>
                                        <option value="endergebnis" ${b.rabatt_typ === 'endergebnis' ? 'selected' : ''}>Endergebnis €</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Wert</label>
                                    <input type="number" id="rabatt-wert" value="${b.rabatt_wert}" step="0.01" />
                                </div>
                                <button class="btn btn-primary" onclick="applyRabatt(${b.id})">Anwenden</button>
                            </div>
                            ${rabattBetrag > 0 ? `<div style="margin-top: 10px; color: #28a745; font-weight: 600;">Rabatt: -€ ${rabattBetrag.toFixed(2)}</div>` : ''}
                        </div>
                    </div>
                `;

                document.getElementById('bestellung-content').innerHTML = html;
            } catch (e) {
                console.error('Fehler:', e);
            }
        }

        async function createBestellung() {
            const name = document.getElementById('bestellung-name').value.trim();
            if (!name) {
                alert('Bitte einen Namen eingeben');
                return;
            }

            await fetch('api.php?action=create_bestellung', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name })
            });

            document.getElementById('bestellung-name').value = '';
            closeModal('bestellung-modal');
            showUpdateIndicator();
            loadBestellungen();
        }

        async function deleteBestellung(id) {
            if (!confirm('Bestellung wirklich löschen?')) return;

            await fetch('api.php?action=delete_bestellung', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ bestellung_id: id })
            });

            if (aktuelleBestellung?.id === id) {
                aktuelleBestellung = null;
            }
            showUpdateIndicator();
            loadBestellungen();
        }

        async function addArtikel(bestellungId) {
            const select = document.getElementById('artikel-select');
            const produktId = select.value;
            const menge = parseInt(document.getElementById('artikel-menge').value);

            if (!produktId) {
                alert('Bitte ein Produkt wählen');
                return;
            }

            if (menge < 1) {
                alert('Menge muss mindestens 1 sein');
                return;
            }

            await fetch('api.php?action=add_artikel', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ bestellung_id: bestellungId, produkt_id: produktId, menge })
            });

            select.value = '';
            document.getElementById('artikel-menge').value = '1';
            showUpdateIndicator();
            renderBestellungDetails();
        }

        async function removeArtikel(bestellungId, positionId) {
            if (!confirm('Artikel wirklich entfernen?')) return;

            await fetch('api.php?action=remove_artikel', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ bestellung_id: bestellungId, position_id: positionId })
            });

            showUpdateIndicator();
            renderBestellungDetails();
        }

        async function updateStatus(bestellungId, status) {
            await fetch('api.php?action=update_status', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ bestellung_id: bestellungId, status })
            });

            showUpdateIndicator();
            loadBestellungen();
        }

        async function applyRabatt(bestellungId) {
            const typ = document.getElementById('rabatt-typ').value;
            const wert = parseFloat(document.getElementById('rabatt-wert').value) || 0;

            await fetch('api.php?action=apply_rabatt', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ bestellung_id: bestellungId, rabatt_typ: typ, rabatt_wert: wert })
            });

            showUpdateIndicator();
            renderBestellungDetails();
        }

        function filterBestellungen(status) {
            aktuellterFilter = status;
            loadBestellungen();
        }

        // ============== LAGER ==============
        async function loadProdukte() {
            try {
                const response = await fetch('api.php?action=get_produkte');
                produkte = await response.json();
            } catch (e) {
                console.error('Fehler:', e);
            }
        }

        async function loadLager() {
            try {
                await loadProdukte();
                renderLager();
            } catch (e) {
                console.error('Fehler:', e);
            }
        }

        function renderLager() {
            const container = document.getElementById('lager-content');
            container.innerHTML = '';

            const kategorien = [...new Set(produkte.map(p => p.kategorie))];

            kategorien.forEach(kat => {
                const prodsInKat = produkte.filter(p => p.kategorie === kat);

                prodsInKat.forEach(p => {
                    const isLow = p.bestand <= p.bestand_warnung;
                    const card = document.createElement('div');
                    card.className = 'lager-card' + (isLow ? ' low-stock' : '');
                    card.innerHTML = `
                        <div class="lager-card-title">${p.name}</div>
                        <div class="lager-info">
                            <span class="lager-label">Preis:</span>
                            <span class="lager-value">€ ${p.preis.toFixed(2)}</span>
                        </div>
                        <div class="lager-info">
                            <span class="lager-label">Bestand:</span>
                            <span class="lager-value">${p.bestand}</span>
                        </div>
                        <div class="form-group">
                            <label>Neuer Bestand</label>
                            <input type="number" value="${p.bestand}" onchange="updateBestand(${p.id}, this.value)" />
                        </div>
                        <div class="form-group">
                            <label>Warnung bei</label>
                            <input type="number" value="${p.bestand_warnung}" onchange="updateWarnung(${p.id}, this.value)" />
                        </div>
                        ${isLow ? `<div class="warning-badge">⚠️ Bestand niedrig!</div>` : ''}
                    `;
                    container.appendChild(card);
                });
            });
        }

        async function updateBestand(produktId, bestand) {
            await fetch('api.php?action=update_bestand', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ produkt_id: produktId, menge: parseInt(bestand) })
            });
            showUpdateIndicator();
            loadLager();
        }

        async function updateWarnung(produktId, warnung) {
            await fetch('api.php?action=update_warnung', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ produkt_id: produktId, warnung: parseInt(warnung) })
            });
            showUpdateIndicator();
            loadLager();
        }

        async function createProdukt() {
            const name = document.getElementById('produkt-name').value.trim();
            const preis = parseFloat(document.getElementById('produkt-preis').value);
            const bestand = parseInt(document.getElementById('produkt-bestand').value);
            const warnung = parseInt(document.getElementById('produkt-warnung').value);
            const kategorie = document.getElementById('produkt-kategorie').value.trim();

            if (!name || !preis || !bestand || !warnung) {
                alert('Bitte alle Felder ausfüllen');
                return;
            }

            await fetch('api.php?action=add_produkt', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name, preis, bestand, bestand_warnung: warnung, kategorie })
            });

            document.getElementById('produkt-name').value = '';
            document.getElementById('produkt-preis').value = '';
            document.getElementById('produkt-bestand').value = '';
            document.getElementById('produkt-warnung').value = '';
            document.getElementById('produkt-kategorie').value = '';
            closeModal('produkt-modal');
            showUpdateIndicator();
            loadLager();
        }

        // ============== STATISTIKEN ==============
        async function loadStatistiken(timeframe) {
            try {
                const response = await fetch(`api.php?action=get_statistiken&timeframe=${timeframe}`);
                const data = await response.json();

                let html = '';
                let gesamtUmsatz = 0;
                let gesamtVerkauft = 0;

                data.forEach(stat => {
                    gesamtUmsatz += parseFloat(stat.umsatz);
                    gesamtVerkauft += parseInt(stat.menge_verkauft);

                    html += `
                        <div class="statistik-card">
                            <div class="statistik-title">${stat.name}</div>
                            <div class="statistik-info">
                                <span>Verkauft: ${stat.menge_verkauft}x</span>
                                <span>Umsatz: € ${stat.umsatz}</span>
                            </div>
                        </div>
                    `;
                });

                html = `
                    <div class="bestellung-details">
                        <div class="bestellung-header">
                            <div class="info-box">
                                <div class="info-label">Artikel verkauft</div>
                                <div class="info-value">${gesamtVerkauft}</div>
                            </div>
                            <div class="info-box">
                                <div class="info-label">Gesamtumsatz</div>
                                <div class="info-value">€ ${gesamtUmsatz.toFixed(2)}</div>
                            </div>
                        </div>
                    </div>
                ` + html;

                document.getElementById('statistiken-content').innerHTML = html;
            } catch (e) {
                console.error('Fehler:', e);
            }
        }

        // ============== MODAL FUNKTIONEN ==============
        function openNewBestellungModal() {
            document.getElementById('bestellung-modal').classList.add('active');
            document.getElementById('bestellung-name').focus();
        }

        function openNewProduktModal() {
            document.getElementById('produkt-modal').classList.add('active');
            document.getElementById('produkt-name').focus();
        }

        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }

        // ============== HILFSFUNKTIONEN ==============
        function showUpdateIndicator() {
            const indicator = document.getElementById('update-indicator');
            indicator.classList.add('show');
            setTimeout(() => {
                indicator.classList.remove('show');
            }, 2000);
        }
    </script>
</body>
</html>
