<?php
/**
 * Standort-Verwaltung (Räume + Positionen)
 * Verwaltet standort_raeume und standort_positionen
 */

require_once __DIR__ . '/config.php';
requireBackendAccess();

$pageTitle = 'Standort-Verwaltung';

$message = '';
$error = '';

// ── POST-Verarbeitung ────────────────────────────────────────────────────────

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // ── RÄUME ────────────────────────────────────────────────────────────────

    if ($action === 'add_raum') {
        $name = trim($_POST['name'] ?? '');
        if (empty($name)) {
            $error = 'Raum-Name darf nicht leer sein';
        } else {
            try {
                $existing = $db->selectOne("SELECT id FROM standort_raeume WHERE name = ?", [$name]);
                if ($existing) {
                    $error = 'Dieser Raum existiert bereits';
                } else {
                    $newId = $db->insert("INSERT INTO standort_raeume (name) VALUES (?)", [$name]);
                    logActivity('created', 'standort_raeume', $newId, $name);
                    $message = 'Raum erfolgreich hinzugefügt';
                }
            } catch (PDOException $e) {
                $error = 'Fehler: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'edit_raum') {
        $id   = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        if (empty($name)) {
            $error = 'Raum-Name darf nicht leer sein';
        } elseif ($id <= 0) {
            $error = 'Ungültige ID';
        } else {
            try {
                $old = $db->selectOne("SELECT name FROM standort_raeume WHERE id = ?", [$id]);
                $db->execute("UPDATE standort_raeume SET name = ? WHERE id = ?", [$name, $id]);
                if ($old) {
                    logActivity('updated', 'standort_raeume', $id, $name,
                        ['name' => $old['name']], ['name' => $name]);
                }
                $message = 'Raum erfolgreich aktualisiert';
            } catch (PDOException $e) {
                $error = 'Fehler: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'delete_raum') {
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            $error = 'Ungültige ID';
        } else {
            try {
                $inUse = $db->selectOne(
                    "SELECT COUNT(*) as count FROM positionen WHERE standort_id = ?", [$id]);
                if ($inUse['count'] > 0) {
                    $error = sprintf(
                        'Dieser Raum enthält noch %d Position(en) und kann nicht gelöscht werden.',
                        $inUse['count']);
                } else {
                    $raum = $db->selectOne("SELECT name FROM standort_raeume WHERE id = ?", [$id]);
                    $db->execute("DELETE FROM standort_raeume WHERE id = ?", [$id]);
                    if ($raum) logActivity('deleted', 'standort_raeume', $id, $raum['name']);
                    $message = 'Raum erfolgreich gelöscht';
                }
            } catch (PDOException $e) {
                $error = 'Fehler: ' . $e->getMessage();
            }
        }
    }

    // ── POSITIONEN ───────────────────────────────────────────────────────────

    if ($action === 'add_position') {
        $raum_id     = intval($_POST['raum_id'] ?? 0);
        $name        = trim($_POST['name'] ?? '');
        $beschreibung = trim($_POST['beschreibung'] ?? '');
        if (empty($name) || $raum_id <= 0) {
            $error = 'Positions-Name und Raum sind Pflichtfelder';
        } else {
            try {
                $existing = $db->selectOne(
                    "SELECT id FROM positionen WHERE standort_id = ? AND name = ?",
                    [$raum_id, $name]);
                if ($existing) {
                    $error = 'Diese Position existiert in diesem Raum bereits';
                } else {
                    $newId = $db->insert(
                        "INSERT INTO positionen (standort_id, name) VALUES (?, ?)",
                        [$raum_id, $name, $beschreibung ?: null]);
                    logActivity('created', 'standort_positionen', $newId, $name);
                    $message = 'Position erfolgreich hinzugefügt';
                }
            } catch (PDOException $e) {
                $error = 'Fehler: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'edit_position') {
        $id           = intval($_POST['id'] ?? 0);
        $raum_id      = intval($_POST['raum_id'] ?? 0);
        $name         = trim($_POST['name'] ?? '');
        $beschreibung = trim($_POST['beschreibung'] ?? '');
        if (empty($name) || $raum_id <= 0 || $id <= 0) {
            $error = 'Ungültige Eingabe';
        } else {
            try {
                $old = $db->selectOne("SELECT name FROM standort_positionen WHERE id = ?", [$id]);
                $db->execute(
                    "UPDATE positionen SET standort_id = ?, name = ? WHERE id = ?",
                    [$raum_id, $name, $beschreibung ?: null, $id]);
                if ($old) {
                    logActivity('updated', 'standort_positionen', $id, $name,
                        ['name' => $old['name']], ['name' => $name]);
                }
                $message = 'Position erfolgreich aktualisiert';
            } catch (PDOException $e) {
                $error = 'Fehler: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'delete_position') {
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            $error = 'Ungültige ID';
        } else {
            try {
                $inUse = $db->selectOne(
                    "SELECT COUNT(*) as count FROM wertsachen WHERE standort_position_id = ?", [$id]);
                if ($inUse['count'] > 0) {
                    $error = sprintf(
                        'Diese Position wird noch von %d Gegenstand/Gegenständen verwendet.',
                        $inUse['count']);
                } else {
                    $pos = $db->selectOne("SELECT name FROM standort_positionen WHERE id = ?", [$id]);
                    $db->execute("DELETE FROM standort_positionen WHERE id = ?", [$id]);
                    if ($pos) logActivity('deleted', 'standort_positionen', $id, $pos['name']);
                    $message = 'Position erfolgreich gelöscht';
                }
            } catch (PDOException $e) {
                $error = 'Fehler: ' . $e->getMessage();
            }
        }
    }
}

// ── Daten laden ──────────────────────────────────────────────────────────────

try {
    $raeume = $db->select("
        SELECT r.*, COUNT(p.id) as position_count
        FROM standort_raeume r
        LEFT JOIN positionen p ON r.id = p.standort_id
        GROUP BY r.id
        ORDER BY r.name ASC
    ");
} catch (Exception $e) {
    $raeume = [];
    $error = 'Fehler beim Laden der Räume: ' . $e->getMessage();
}

try {
    $positionen = $db->select("
        SELECT p.*, r.name as raum_name,
               COUNT(w.id) as usage_count
        FROM standort_positionen p
        LEFT JOIN standort_raeume r ON p.raum_id = r.id
        LEFT JOIN wertsachen w ON w.standort_position_id = p.id
        GROUP BY p.id
        ORDER BY r.name ASC, p.name ASC
    ");
} catch (Exception $e) {
    $positionen = [];
}

$stats = [
    'raeume'     => count($raeume),
    'positionen' => count($positionen),
    'belegt'     => count(array_filter($positionen, fn($p) => $p['usage_count'] > 0)),
    'items'      => array_sum(array_column($positionen, 'usage_count')),
];

include 'layout/header_next_page.php';
?>

<main class="backend-main">

    <?php if ($message): ?>
        <div class="alert alert-success">
            <strong><i class="ti ti-circle-check" style="color:var(--vs-success);"></i> Erfolg!</strong>
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-danger">
            <strong><i class="ti ti-circle-x" style="color:var(--vs-danger);"></i> Fehler!</strong>
            <?php echo htmlspecialchars($error); ?>
        </div>
    <?php endif; ?>

    <!-- Statistik-Karten -->
    <div class="dashboard-grid" style="margin-bottom:30px;">
        <div class="widget-card">
            <div class="widget-header">
                <div>
                    <div class="widget-value"><?php echo $stats['raeume']; ?></div>
                    <div class="widget-label">🚪 Räume</div>
                </div>
                <div class="widget-icon">🚪</div>
            </div>
        </div>
        <div class="widget-card">
            <div class="widget-header">
                <div>
                    <div class="widget-value"><?php echo $stats['positionen']; ?></div>
                    <div class="widget-label">📌 Positionen</div>
                </div>
                <div class="widget-icon">📌</div>
            </div>
        </div>
        <div class="widget-card">
            <div class="widget-header">
                <div>
                    <div class="widget-value" style="color:var(--vs-success);"><?php echo $stats['belegt']; ?></div>
                    <div class="widget-label"><i class="ti ti-circle-check" style="color:var(--vs-success);"></i> Belegt</div>
                </div>
                <div class="widget-icon"><i class="ti ti-circle-check" style="color:var(--vs-success);"></i></div>
            </div>
        </div>
        <div class="widget-card">
            <div class="widget-header">
                <div>
                    <div class="widget-value" style="color:var(--vs-accent);"><?php echo $stats['items']; ?></div>
                    <div class="widget-label"><i class="ti ti-package"></i> Gegenstände</div>
                </div>
                <div class="widget-icon"><i class="ti ti-package"></i></div>
            </div>
        </div>
    </div>

    <!-- ── Räume ─────────────────────────────────────────────────────────── -->
    <div class="activity-timeline" style="margin-bottom:30px;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
            <h2>🚪 Räume</h2>
            <button onclick="showModal('addRaumModal')" class="vs-btn vs-btn-primary">
                <i class="ti ti-plus"></i> Neuer Raum
            </button>
        </div>

        <?php if (empty($raeume)): ?>
            <div style="text-align:center; padding:40px; color:#999;">
                <div style="font-size:48px; margin-bottom:15px;">🚪</div>
                <p>Keine Räume vorhanden</p>
                <p style="font-size:13px; margin-top:5px;">Erstelle deinen ersten Raum um Standorte zu verwalten.</p>
            </div>
        <?php else: ?>
            <table class="backend-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Raum-Name</th>
                        <th>Positionen</th>
                        <th style="width:140px;">Aktionen</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($raeume as $raum): ?>
                        <tr>
                            <td><strong>#<?php echo $raum['id']; ?></strong></td>
                            <td><strong><?php echo htmlspecialchars($raum['name']); ?></strong></td>
                            <td>
                                <?php if ($raum['position_count'] > 0): ?>
                                    <span class="badge badge-success"><?php echo $raum['position_count']; ?> Position(en)</span>
                                <?php else: ?>
                                    <span class="badge badge-secondary">Keine</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button onclick='editRaum(<?php echo json_encode($raum); ?>)'
                                        class="vs-btn vs-btn-sm" title="Bearbeiten" style="padding:8px 10px; font-size:16px;">
                                    <i class="ti ti-pencil"></i>
                                </button>
                                <button onclick="deleteRaum(<?php echo $raum['id']; ?>, '<?php echo htmlspecialchars($raum['name'], ENT_QUOTES); ?>', <?php echo $raum['position_count']; ?>)"
                                        class="vs-btn vs-btn-sm vs-btn-danger" title="Löschen" style="padding:8px 10px; font-size:16px;">
                                    <i class="ti ti-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <!-- ── Positionen ────────────────────────────────────────────────────── -->
    <div class="activity-timeline">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
            <h2>📌 Positionen</h2>
            <button onclick="showModal('addPositionModal')" class="vs-btn vs-btn-primary"
                    <?php echo empty($raeume) ? 'disabled title="Bitte zuerst einen Raum anlegen"' : ''; ?>>
                <i class="ti ti-plus"></i> Neue Position
            </button>
        </div>

        <?php if (empty($positionen)): ?>
            <div style="text-align:center; padding:40px; color:#999;">
                <div style="font-size:48px; margin-bottom:15px;">📌</div>
                <p>Keine Positionen vorhanden</p>
                <p style="font-size:13px; margin-top:5px;">Positionen sind präzise Standorte innerhalb eines Raums (z.B. "Vitrine links", "Regal 2").</p>
            </div>
        <?php else: ?>
            <table class="backend-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Raum</th>
                        <th>Position</th>
                        <th>Beschreibung</th>
                        <th>Verwendung</th>
                        <th style="width:140px;">Aktionen</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($positionen as $pos): ?>
                        <tr>
                            <td><strong>#<?php echo $pos['id']; ?></strong></td>
                            <td><span class="badge badge-secondary"><?php echo htmlspecialchars($pos['raum_name'] ?? '—'); ?></span></td>
                            <td><strong><?php echo htmlspecialchars($pos['name']); ?></strong></td>
                            <td style="color:#888; font-size:13px;"><?php echo htmlspecialchars($pos['beschreibung'] ?? '—'); ?></td>
                            <td>
                                <?php if ($pos['usage_count'] > 0): ?>
                                    <span class="badge badge-success"><?php echo $pos['usage_count']; ?> Gegenstand<?php echo $pos['usage_count'] > 1 ? 'e' : ''; ?></span>
                                <?php else: ?>
                                    <span class="badge badge-secondary">Nicht verwendet</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button onclick='editPosition(<?php echo json_encode($pos); ?>)'
                                        class="vs-btn vs-btn-sm" title="Bearbeiten" style="padding:8px 10px; font-size:16px;">
                                    <i class="ti ti-pencil"></i>
                                </button>
                                <button onclick="deletePosition(<?php echo $pos['id']; ?>, '<?php echo htmlspecialchars($pos['name'], ENT_QUOTES); ?>', <?php echo $pos['usage_count']; ?>)"
                                        class="vs-btn vs-btn-sm vs-btn-danger" title="Löschen" style="padding:8px 10px; font-size:16px;">
                                    <i class="ti ti-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

</main>

<!-- ── Modal: Raum hinzufügen ─────────────────────────────────────────────── -->
<div id="addRaumModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3><i class="ti ti-plus"></i> Neuer Raum</h3>
            <span class="modal-close" onclick="closeModal('addRaumModal')">&times;</span>
        </div>
        <form method="POST" class="modal-body">
            <input type="hidden" name="action" value="add_raum">
            <div class="form-group">
                <label>Raum-Name *</label>
                <input type="text" name="name" required class="form-control"
                       placeholder="z.B. Wohnzimmer, Schlafzimmer, Keller...">
            </div>
            <div class="modal-footer">
                <button type="button" onclick="closeModal('addRaumModal')" class="vs-btn vs-btn-secondary">Abbrechen</button>
                <button type="submit" class="vs-btn vs-btn-primary">Raum erstellen</button>
            </div>
        </form>
    </div>
</div>

<!-- ── Modal: Raum bearbeiten ─────────────────────────────────────────────── -->
<div id="editRaumModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3><i class="ti ti-pencil"></i> Raum bearbeiten</h3>
            <span class="modal-close" onclick="closeModal('editRaumModal')">&times;</span>
        </div>
        <form method="POST" class="modal-body">
            <input type="hidden" name="action" value="edit_raum">
            <input type="hidden" name="id" id="edit_raum_id">
            <div class="form-group">
                <label>Raum-Name *</label>
                <input type="text" name="name" id="edit_raum_name" required class="form-control">
            </div>
            <div class="modal-footer">
                <button type="button" onclick="closeModal('editRaumModal')" class="vs-btn vs-btn-secondary">Abbrechen</button>
                <button type="submit" class="vs-btn vs-btn-primary">Speichern</button>
            </div>
        </form>
    </div>
</div>

<!-- ── Modal: Position hinzufügen ────────────────────────────────────────── -->
<div id="addPositionModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3><i class="ti ti-plus"></i> Neue Position</h3>
            <span class="modal-close" onclick="closeModal('addPositionModal')">&times;</span>
        </div>
        <form method="POST" class="modal-body">
            <input type="hidden" name="action" value="add_position">
            <div class="form-group">
                <label>Raum *</label>
                <select name="raum_id" required class="form-control">
                    <option value="">— Raum wählen —</option>
                    <?php foreach ($raeume as $r): ?>
                        <option value="<?php echo $r['id']; ?>"><?php echo htmlspecialchars($r['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Positions-Name *</label>
                <input type="text" name="name" required class="form-control"
                       placeholder="z.B. Vitrine links, Regal 2, Schublade oben...">
            </div>
            <div class="form-group">
                <label>Beschreibung <span style="color:#999;">(optional)</span></label>
                <input type="text" name="beschreibung" class="form-control"
                       placeholder="z.B. Oberstes Fach, linke Seite">
            </div>
            <div class="modal-footer">
                <button type="button" onclick="closeModal('addPositionModal')" class="vs-btn vs-btn-secondary">Abbrechen</button>
                <button type="submit" class="vs-btn vs-btn-primary">Position erstellen</button>
            </div>
        </form>
    </div>
</div>

<!-- ── Modal: Position bearbeiten ────────────────────────────────────────── -->
<div id="editPositionModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3><i class="ti ti-pencil"></i> Position bearbeiten</h3>
            <span class="modal-close" onclick="closeModal('editPositionModal')">&times;</span>
        </div>
        <form method="POST" class="modal-body">
            <input type="hidden" name="action" value="edit_position">
            <input type="hidden" name="id" id="edit_pos_id">
            <div class="form-group">
                <label>Raum *</label>
                <select name="raum_id" id="edit_pos_raum_id" required class="form-control">
                    <?php foreach ($raeume as $r): ?>
                        <option value="<?php echo $r['id']; ?>"><?php echo htmlspecialchars($r['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Positions-Name *</label>
                <input type="text" name="name" id="edit_pos_name" required class="form-control">
            </div>
            <div class="form-group">
                <label>Beschreibung <span style="color:#999;">(optional)</span></label>
                <input type="text" name="beschreibung" id="edit_pos_beschreibung" class="form-control">
            </div>
            <div class="modal-footer">
                <button type="button" onclick="closeModal('editPositionModal')" class="vs-btn vs-btn-secondary">Abbrechen</button>
                <button type="submit" class="vs-btn vs-btn-primary">Speichern</button>
            </div>
        </form>
    </div>
</div>

<!-- ── Lösch-Formulare (versteckt) ───────────────────────────────────────── -->
<form id="deleteRaumForm" method="POST" style="display:none;">
    <input type="hidden" name="action" value="delete_raum">
    <input type="hidden" name="id" id="delete_raum_id">
</form>
<form id="deletePositionForm" method="POST" style="display:none;">
    <input type="hidden" name="action" value="delete_position">
    <input type="hidden" name="id" id="delete_position_id">
</form>

<!-- ── Lösch-Bestätigungs-Modal ──────────────────────────────────────────── -->
<div id="deleteConfirmModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5);
     z-index:9999; align-items:center; justify-content:center; padding:20px;">
    <div style="background:var(--vs-surface); border-radius:16px; padding:28px; max-width:360px; width:100%;
                box-shadow:0 16px 48px rgba(0,0,0,0.2); text-align:center;">
        <div style="font-size:36px; margin-bottom:12px;"><i class="ti ti-trash"></i></div>
        <h3 style="margin:0 0 8px;" id="deleteConfirmTitle">Löschen?</h3>
        <p id="deleteConfirmName" style="color:var(--vs-text-muted); margin:0 0 24px; font-size:14px;"></p>
        <div style="display:flex; gap:10px; justify-content:center;">
            <button onclick="closeDeleteConfirm()" class="vs-btn vs-btn-secondary" style="padding:10px 24px;">Abbrechen</button>
            <button id="deleteConfirmBtn"
                    style="padding:10px 24px; background:var(--vs-danger); color:var(--vs-surface); border:none;
                           border-radius:8px; cursor:pointer; font-weight:600; font-size:14px;">
                Löschen
            </button>
        </div>
    </div>
</div>

<style>
.alert { padding:15px 20px; border-radius:8px; margin-bottom:20px; border-left:4px solid; }
.alert-success { background:var(--vs-success-light); border-color:var(--vs-success); color:var(--vs-success-text); }
.alert-danger  { background:var(--vs-danger-light);  border-color:var(--vs-danger);  color:var(--vs-danger-text); }
.backend-table { width:100%; border-collapse:collapse; margin-top:15px; }
.backend-table thead tr { background:var(--bg-color); border-bottom:2px solid var(--border-color); }
.backend-table th, .backend-table td { padding:12px; text-align:left; }
.backend-table tbody tr { border-bottom:1px solid var(--border-color); transition:background 0.2s; }
.backend-table tbody tr:hover { background:var(--bg-color); }
.badge { padding:4px 10px; border-radius:12px; font-size:11px; font-weight:600; display:inline-block; }
.badge-success  { background:var(--vs-success-light); color:var(--vs-success-text); }
.badge-secondary { background:var(--vs-border); color:#666; }
.modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:10000; align-items:center; justify-content:center; }
.modal.active { display:flex; }
.modal-content { background:var(--vs-surface); border-radius:12px; width:90%; max-width:500px; max-height:90vh; overflow-y:auto; box-shadow:0 10px 40px rgba(0,0,0,0.3); }
.modal-header { padding:20px 25px; border-bottom:1px solid var(--border-color); display:flex; justify-content:space-between; align-items:center; }
.modal-header h3 { margin:0; color:var(--text-color); }
.modal-close { font-size:28px; cursor:pointer; color:var(--text-muted); line-height:1; }
.modal-close:hover { color:var(--text-color); }
.modal-body { padding:25px; }
.modal-footer { padding:15px 25px; border-top:1px solid var(--border-color); display:flex; justify-content:flex-end; gap:10px; }
.form-group { margin-bottom:20px; }
.form-group label { display:block; margin-bottom:8px; font-weight:600; color:var(--text-color); }
.form-control { width:100%; padding:10px 12px; border:1px solid var(--border-color); border-radius:6px; font-size:14px; transition:var(--transition); }
.form-control:focus { outline:none; border-color:var(--primary-color); box-shadow:0 0 0 3px rgba(102,126,234,0.1); }
</style>

<script>
function showModal(id)  { document.getElementById(id).classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); }

// Raum bearbeiten
function editRaum(raum) {
    document.getElementById('edit_raum_id').value   = raum.id;
    document.getElementById('edit_raum_name').value = raum.name;
    showModal('editRaumModal');
}

// Raum löschen
function deleteRaum(id, name, posCount) {
    if (posCount > 0) {
        alert('Dieser Raum enthält noch ' + posCount + ' Position(en) und kann nicht gelöscht werden.');
        return;
    }
    document.getElementById('deleteConfirmTitle').textContent = 'Raum löschen?';
    document.getElementById('deleteConfirmName').textContent  = '"' + name + '"';
    document.getElementById('deleteConfirmBtn').onclick = function() {
        document.getElementById('delete_raum_id').value = id;
        document.getElementById('deleteRaumForm').submit();
    };
    document.getElementById('deleteConfirmModal').style.display = 'flex';
}

// Position bearbeiten
function editPosition(pos) {
    document.getElementById('edit_pos_id').value           = pos.id;
    document.getElementById('edit_pos_raum_id').value      = pos.raum_id;
    document.getElementById('edit_pos_name').value         = pos.name;
    document.getElementById('edit_pos_beschreibung').value = pos.beschreibung || '';
    showModal('editPositionModal');
}

// Position löschen
function deletePosition(id, name, usageCount) {
    if (usageCount > 0) {
        alert('Diese Position wird noch von ' + usageCount + ' Gegenstand/Gegenständen verwendet.');
        return;
    }
    document.getElementById('deleteConfirmTitle').textContent = 'Position löschen?';
    document.getElementById('deleteConfirmName').textContent  = '"' + name + '"';
    document.getElementById('deleteConfirmBtn').onclick = function() {
        document.getElementById('delete_position_id').value = id;
        document.getElementById('deletePositionForm').submit();
    };
    document.getElementById('deleteConfirmModal').style.display = 'flex';
}

function closeDeleteConfirm() {
    document.getElementById('deleteConfirmModal').style.display = 'none';
}

// Modal schließen bei Klick außerhalb
window.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal')) e.target.classList.remove('active');
    if (e.target.id === 'deleteConfirmModal') closeDeleteConfirm();
});
</script>

<?php include 'layout/footer_next_page.php'; ?>
