<?php
// articles.php – DB-Version mit Inline-Editing

declare(strict_types=1);
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);

require __DIR__ . '/auth.php';
requireLogin();
$user = currentUser();

$storeFile = $_GET['store'] ?? null;

if (!$storeFile || !preg_match('~^[a-z0-9._-]+\.json$~i', $storeFile)) {
    abort404();
}

// Store aus DB holen
$stmt = $pdo->prepare('SELECT id, name FROM stores WHERE file = :file');
$stmt->execute([':file' => $storeFile]);
$store = $stmt->fetch();

if (!$store) {
    abort404();
}

$storeId   = (int)$store['id'];
$storeName = $store['name'];

// Artikel holen (inkl. Bildpfad UND Userfarbe)
$stmt = $pdo->prepare('
    SELECT 
        i.id,
        i.name,
        i.price,
        i.amount,
        i.unit,
        i.sort_order,
        i.image_path,
        i.created_by,
        u.first_name,
        u.last_name,
        u.text_color
    FROM items i
    LEFT JOIN users u ON u.id = i.created_by
    WHERE i.store_id = :sid
    ORDER BY i.sort_order, i.name
');
$stmt->execute([':sid' => $storeId]);
$articles = $stmt->fetchAll();

// Einheiten (ausgeschrieben, alphabetisch sortiert)
$unitOptions = [
    "Becher",
    "Beutel",
    "Blister",
    "Box",
    "Bund",
    "Dose(n)",
    "Flasche(n)",
    "Glas/Gläser",
    "Gramm",
    "Karton(s)",
    "Kilogramm",
    "Kiste(n)",
    "Laib(e)",
    "Liter",
    "Milliliter",
    "Paar",
    "Packung(en)",
    "Portion(en)",
    "Rolle(n)",
    "Sack/Säcke",
    "Schale(n)",
    "Scheibe(n)",
    "Stange(n)",
    "Stück(e)",
    "Tube(n)",
    "Tüte(n)"
];

?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>EKL – <?= htmlspecialchars($storeName) ?></title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="icon" href="icons/logo.png" type="image/png">
</head>
<body>
<div id="app">
    <div class="user-info">
        Eingeloggt als
        <?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>
        | <a href="logout.php">Logout</a>
    </div>

    <h1><?= htmlspecialchars($storeName) ?> – Einkaufsliste</h1>
    <p>
        <a class="link-pill btn-with-icon" href="store_pdf.php?store=<?= urlencode($storeFile) ?>" target="_blank">
            <span class="icon" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"></path>
                    <path d="M14 2v5h5"></path>
                    <path d="M8 13h8"></path>
                    <path d="M8 17h6"></path>
                </svg>
            </span>
            PDF erstellen
        </a>
    </p>


    <form id="addArticleForm" method="post" action="php/add_article.php" enctype="multipart/form-data">
        <input type="hidden" name="storeFile" value="<?= htmlspecialchars($storeFile) ?>">

        <input type="text" name="itemName" placeholder="Artikelname" required>
        <!-- Preis entfernt -->
        <input type="text" name="amount" placeholder="Menge (z.B. 2)">

        <select name="unit">
            <?php foreach ($unitOptions as $opt): ?>
                <option value="<?= htmlspecialchars($opt) ?>"><?= htmlspecialchars($opt) ?></option>
            <?php endforeach; ?>
        </select>

        <!-- Foto aufnehmen / auswählen -->
        <input type="file"
               name="image"
               id="image"
               accept="image/*"
               capture="environment">

        <!-- Button-Zeile -->
        <div class="add-actions">
            <button type="submit" class="btn-with-icon">
                <span class="icon" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M12 5v14"></path>
                        <path d="M5 12h14"></path>
                    </svg>
                </span>
                Artikel hinzuf&uuml;gen
            </button>
            <button type="button" id="voiceAddBtn" class="btn-with-icon">
                <span class="icon" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="9" y="3" width="6" height="11" rx="3"></rect>
                        <path d="M5 11a7 7 0 0 0 14 0"></path>
                        <path d="M12 18v3"></path>
                        <path d="M8 21h8"></path>
                    </svg>
                </span>
                Per Sprache hinzufuegen
            </button>
        </div>

        <span id="voiceAddStatus" class="note"></span>

        <!-- <p><a href="start.php" style="color: green;">Zur&uuml;ck zu den Gesch&auml;ften</a></p> 
                //Ausgeklammert da Jenny da immer draufklickt.
        -->
    </form>

    <table id="shoppingTable">
        <thead>
        <tr>
            <th>Artikel</th>
            <th>Menge</th>
            <th>Einheit</th>
            <th>Bild</th>
            <th class="action-header">
                <span class="action-text">Aktion</span>
                <span class="action-icon" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="3"></circle>
                        <path d="M19.4 15a1.7 1.7 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.7 1.7 0 0 0-1.82-.33 1.7 1.7 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.7 1.7 0 0 0-1-1.51 1.7 1.7 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.09a1.7 1.7 0 0 0 1.51-1 1.7 1.7 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-1.5V3a2 2 0 0 1 4 0v.09a1.7 1.7 0 0 0 1 1.51 1.7 1.7 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9c.69.08 1.26.6 1.5 1.23.07.19.1.39.1.6v.34a2 2 0 0 1-1.5 1z"></path>
                    </svg>
                </span>
            </th>
        </tr>
        </thead>
        <tbody>
        <?php
        foreach ($articles as $index => $article):
            $id        = (int)$article['id'];
            $name      = (string)($article['name'] ?? '');
            $amount    = (float)($article['amount'] ?? 0);
            $unit      = (string)($article['unit'] ?? '');
            $imagePath = (string)($article['image_path'] ?? '');
            $colorHex  = $article['text_color'] ?? '#000000';

            $creatorName = trim(
                (($article['first_name'] ?? '') . ' ' . ($article['last_name'] ?? ''))
            );
            ?>
            <tr draggable="true"
                data-id="<?= $id ?>"
                style="color: <?= htmlspecialchars($colorHex) ?>;"
                <?php if ($creatorName !== ''): ?>
                    title="Angelegt von <?= htmlspecialchars($creatorName) ?>"
                <?php endif; ?>
            >
                <td class="cell-name" data-field="name"><?= htmlspecialchars($name) ?></td>
                <td class="cell-amount" data-field="amount">
                    <?= rtrim(rtrim(number_format($amount, 2, ',', '.'), '0'), ',') ?>
                </td>
                <td class="cell-unit" data-field="unit"><?= htmlspecialchars($unit) ?></td>

                <td class="cell-image" data-item-id="<?= $id ?>">
                    <?php if ($imagePath !== ''): ?>
                        <img class="img-thumb" src="uploads/items/<?= htmlspecialchars($imagePath) ?>" alt="">
                        <a href="uploads/items/<?= htmlspecialchars($imagePath) ?>" target="_blank">Bild</a>
                    <?php else: ?>
                        <button type="button" class="img-add-btn" title="Bild hinzuf&uuml;gen">+</button>
                        <input type="file" class="img-add-input" accept="image/*" capture="environment" hidden>
                    <?php endif; ?>
                </td>

                <td>
                    <form method="post" action="php/delete_item.php" style="display:inline;">
                        <input type="hidden" name="storeFile" value="<?= htmlspecialchars($storeFile) ?>">
                        <input type="hidden" name="item_id" value="<?= $id ?>">
                        <button type="submit" class="delete-store btn-with-icon" title="Loeschen" aria-label="Loeschen">
                            <span class="icon" aria-hidden="true">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M3 6h18"></path>
                                    <path d="M8 6V4h8v2"></path>
                                    <path d="M19 6l-1 14H6L5 6"></path>
                                    <path d="M10 11v6"></path>
                                    <path d="M14 11v6"></path>
                                </svg>
                            </span>
                        </button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
        <!-- Fußzeile mit Gesamt entfernt -->
    </table>

    <p>
        <a class="link-pill btn-with-icon" href="start.php">
            <span class="icon" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M15 18l-6-6 6-6"></path>
                </svg>
            </span>
            Zur&uuml;ck zu den Gesch&auml;ften
        </a>
    </p>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', () => {
    const tbody = document.querySelector('#shoppingTable tbody');
    const storeFile = <?= json_encode($storeFile) ?>;
    const storeId = <?= (int)$storeId ?>;
    const UNIT_OPTIONS = <?= json_encode($unitOptions, JSON_UNESCAPED_UNICODE) ?>;

    // Drag & Drop Reihenfolge
    let dragSrcEl = null;

    tbody.addEventListener('dragstart', (e) => {
        const row = e.target.closest('tr');
        if (!row) return;
        dragSrcEl = row;
        row.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
    });

    tbody.addEventListener('dragover', (e) => {
        e.preventDefault();
        const row = e.target.closest('tr');
        if (!row || row === dragSrcEl) return;
        const bounding = row.getBoundingClientRect();
        const offset = e.clientY - bounding.top - bounding.height / 2;
        const parent = row.parentNode;
        if (offset > 0) {
            parent.insertBefore(dragSrcEl, row.nextSibling);
        } else {
            parent.insertBefore(dragSrcEl, row);
        }
    });

    tbody.addEventListener('dragend', () => {
        const rows = Array.from(tbody.querySelectorAll('tr'));
        rows.forEach(r => r.classList.remove('dragging'));
        saveNewOrder(rows);
    });

    async function saveNewOrder(rows) {
        const newOrder = rows.map(r => parseInt(r.dataset.id, 10));
        const originalOrder = [...newOrder]; // legacy
        try {
            const res = await fetch('php/update_article_order.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ newOrder, originalOrder, storeId })
            });
            if (!res.ok) throw new Error('HTTP ' + res.status);
        } catch (err) {
            console.error(err);
            alert('Reihenfolge konnte nicht gespeichert werden.');
            location.reload();
        }
    }

    // Inline-Editing
    const editableSelectors = ['.cell-name', '.cell-amount', '.cell-unit'];

    tbody.addEventListener('dblclick', (e) => {
        const cell = e.target.closest(editableSelectors.join(','));
        if (!cell) return;
        if (cell.classList.contains('cell-unit')) {
            startUnitEdit(cell);
        } else {
            startTextOrNumberEdit(cell);
        }
    });

    function startTextOrNumberEdit(cell) {
        if (cell.isContentEditable) return;
        cell.dataset.prev = cell.innerText.trim();
        cell.contentEditable = 'true';
        cell.classList.add('is-editing');
        placeCaretAtEnd(cell);
    }

    tbody.addEventListener('keydown', (e) => {
        const cell = e.target.closest('td[contenteditable="true"]');
        if (!cell) return;
        if (e.key === 'Enter') {
            e.preventDefault();
            commitEdit(cell);
        } else if (e.key === 'Escape') {
            cancelEdit(cell);
        }
    });

    tbody.addEventListener('blur', (e) => {
        const cell = e.target.closest('td[contenteditable="true"]');
        if (!cell) return;
        if (!cell.classList.contains('is-editing')) return;
        commitEdit(cell);
    }, true);

    function cancelEdit(cell) {
        if (!cell.dataset.prev) return;
        cell.textContent = cell.dataset.prev;
        cell.contentEditable = 'false';
        cell.classList.remove('is-editing');
        delete cell.dataset.prev;
    }

    async function commitEdit(cell) {
        const row = cell.closest('tr');
        const itemId = parseInt(row.dataset.id, 10);
        const field = cell.dataset.field;
        let value = cell.innerText.trim();

        // Nur Menge als Zahl pruefen
        if (field === 'amount') {
            value = value.replace(/\./g, '').replace(',', '.');
            if (value === '') value = '0';
            if (isNaN(Number(value))) {
                alert('Bitte eine Zahl eingeben.');
                cancelEdit(cell);
                return;
            }
        }

        try {
            const payload = { itemId, field, value };
            const res = await fetch('php/update_article.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await res.json();

            if (!data.success) {
                throw new Error(data.message || 'Unbekannter Fehler');
            }

            // Menge formatiert zuruecksetzen, sonst normaler Text
            if (field === 'amount') {
                cell.textContent = data.formatted.amount ?? data.value;
            } else {
                cell.textContent = data.value;
            }
        } catch (err) {
            console.error(err);
            alert('Fehler beim Speichern: ' + err.message);
            cancelEdit(cell);
        } finally {
            cell.contentEditable = 'false';
            cell.classList.remove('is-editing');
            delete cell.dataset.prev;
        }
    }

    function startUnitEdit(cell) {
        if (cell.querySelector('select')) return;
        const prevText = cell.innerText.trim();
        cell.dataset.prev = prevText;

        const select = document.createElement('select');
        select.className = 'inline-unit-select';
        select.setAttribute('aria-label', 'Einheit waehlen');

        UNIT_OPTIONS.forEach(opt => {
            const o = document.createElement('option');
            o.value = opt;
            o.textContent = opt;
            if (opt === prevText) o.selected = true;
            select.appendChild(o);
        });

        cell.textContent = '';
        cell.appendChild(select);
        select.focus();

        select.addEventListener('change', () => commitUnitEdit(cell, select));
        select.addEventListener('blur', () => commitUnitEdit(cell, select));
    }

    async function commitUnitEdit(cell, selectEl) {
        const row = cell.closest('tr');
        const itemId = parseInt(row.dataset.id, 10);
        const field = 'unit';
        const value = selectEl.value;

        try {
            const payload = { itemId, field, value };
            const res = await fetch('php/update_article.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await res.json();
            if (!data.success) {
                throw new Error(data.message || 'Fehler beim Speichern');
            }
            cell.textContent = data.value;
        } catch (err) {
            console.error(err);
            alert('Fehler beim Speichern: ' + err.message);
            cell.textContent = cell.dataset.prev || '';
        } finally {
            delete cell.dataset.prev;
        }
    }

    function placeCaretAtEnd(el) {
        const range = document.createRange();
        const sel = window.getSelection();
        range.selectNodeContents(el);
        range.collapse(false);
        sel.removeAllRanges();
        sel.addRange(range);
    }

    // Bild nachtraeglich hinzufuegen (nur wenn noch kein Bild da ist)
    tbody.addEventListener('click', (e) => {
        const btn = e.target.closest('.img-add-btn');
        if (!btn) return;

        const cell = btn.closest('td.cell-image');
        if (!cell) return;

        const input = cell.querySelector('.img-add-input');
        if (!input) return;

        input.click();
    });

    tbody.addEventListener('change', async (e) => {
        const input = e.target.closest('.img-add-input');
        if (!input) return;

        const file = input.files && input.files[0] ? input.files[0] : null;
        if (!file) return;

        const cell = input.closest('td.cell-image');
        const row = input.closest('tr');
        if (!cell || !row) return;

        const itemId = parseInt(row.dataset.id, 10);
        if (!itemId) return;

        const fd = new FormData();
        fd.append('storeFile', storeFile);
        fd.append('item_id', String(itemId));
        fd.append('image', file);

        // UI kurz sperren
        const oldHtml = cell.innerHTML;
        cell.innerHTML = 'Upload.';

        try {
            const res = await fetch('php/update_item_image.php', {
                method: 'POST',
                body: fd
            });

            const data = await res.json();
            if (!data.ok) {
                throw new Error(data.error || 'Upload fehlgeschlagen');
            }

            const filename = data.filename;
            const url = 'uploads/items/' + encodeURIComponent(filename);

            // Desktop: Vorschau + Link. Mobile: Vorschau wird per CSS ausgeblendet.
            cell.innerHTML =
                '<img class="img-thumb" src="' + url + '" alt="">' +
                '<a href="' + url + '" target="_blank">Bild</a>';
        } catch (err) {
            console.error(err);
            alert('Bild konnte nicht gespeichert werden: ' + err.message);
            cell.innerHTML = oldHtml;
        } finally {
            // File-Input zuruecksetzen, damit gleicher Dateiname nochmal geht
            input.value = '';
        }
    });

    // Voice Add (Web Speech API)
    const voiceBtn = document.getElementById('voiceAddBtn');
    const voiceStatus = document.getElementById('voiceAddStatus');

    if (voiceBtn && ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
        const Recognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        const rec = new Recognition();
        rec.lang = 'de-DE';
        rec.interimResults = false;

        voiceBtn.addEventListener('click', () => {
            voiceStatus.textContent = 'Mikro aktiv, bitte sprechen.';
            rec.start();
        });

        rec.onresult = async (e) => {
            const spoken = e.results[0][0].transcript.trim();
            voiceStatus.textContent = 'Erkannt: "' + spoken + '". Wird hinzugefuegt.';

            try {
                const res = await fetch('php/voice_add.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        storeFile: storeFile,
                        text: spoken
                    })
                });

                const data = await res.json();
                voiceStatus.textContent = data.message || 'Fertig.';

                if (data.ok) {
                    location.reload();
                }
            } catch (err) {
                console.error(err);
                voiceStatus.textContent = 'Fehler bei der Spracheingabe.';
            }
        };

        rec.onerror = (e) => {
            console.error(e);
            voiceStatus.textContent = 'Spracherkennung Fehler: ' + e.error;
        };
    } else if (voiceBtn) {
        voiceBtn.disabled = true;
        voiceBtn.title = 'Spracherkennung wird von diesem Browser nicht unterstuetzt.';
        voiceStatus.textContent = 'Spracherkennung nicht verfuegbar.';
    }
});
</script>
</body>
</html>




