<?php
// storage_locations.php - Verwaltung für Lagerorte
// KORREKTUR: Design der Karten-Header für bessere Lesbarkeit repariert.

$page_title = "Lagerorte verwalten";

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

require_once 'db_connect.php';
require_once 'header.php';

$current_user_id = $_SESSION['user_id'];
$message = '';

// Lade Haushalts-Mitglieder-IDs, da Orte im Haushalt geteilt werden
$stmt_household = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_household->bind_param("i", $current_user_id);
$stmt_household->execute();
$household_id = $stmt_household->get_result()->fetch_assoc()['household_id'];
$stmt_household->close();

$household_member_ids = [$current_user_id];
if ($household_id) {
    $stmt_members = $conn->prepare("SELECT id FROM users WHERE household_id = ?");
    $stmt_members->bind_param("i", $household_id);
    $stmt_members->execute();
    $result_members = $stmt_members->get_result();
    while ($row = $result_members->fetch_assoc()) {
        if (!in_array($row['id'], $household_member_ids)) {
            $household_member_ids[] = $row['id'];
        }
    }
    $stmt_members->close();
}
$placeholders = implode(',', array_fill(0, count($household_member_ids), '?'));
$types = str_repeat('i', count($household_member_ids));

// Formularverarbeitung
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // AKTION: ORT HINZUFÜGEN
    if (isset($_POST['add_location'])) {
        $name = trim($_POST['name']);
        $parent_id = !empty($_POST['parent_id']) ? intval($_POST['parent_id']) : NULL;
        
        if (!empty($name)) {
            $stmt = $conn->prepare("INSERT INTO storage_locations (user_id, parent_id, name) VALUES (?, ?, ?)");
            $stmt->bind_param("iis", $current_user_id, $parent_id, $name);
            if ($stmt->execute()) {
                $message = '<div class="alert alert-success">Lagerort erfolgreich hinzugefügt.</div>';
            } else {
                $message = '<div class="alert alert-danger">Fehler beim Hinzufügen: ' . $stmt->error . '</div>';
            }
            $stmt->close();
        } else {
            $message = '<div class="alert alert-danger">Der Name darf nicht leer sein.</div>';
        }
    }
    // AKTION: ORT BEARBEITEN
    elseif (isset($_POST['edit_location'])) {
        $name = trim($_POST['edit_name']);
        $location_id = intval($_POST['location_id']);

        if (!empty($name) && $location_id > 0) {
            // Jedes Haushaltsmitglied darf bearbeiten, aber die user_id wird nicht geändert
            $stmt = $conn->prepare("UPDATE storage_locations SET name = ? WHERE id = ? AND user_id IN ($placeholders)");
            $all_params = array_merge([$name, $location_id], $household_member_ids);
            $all_types = 'si' . $types;
            $stmt->bind_param($all_types, ...$all_params);
            
            if ($stmt->execute() && $stmt->affected_rows > 0) {
                $message = '<div class="alert alert-success">Lagerort erfolgreich umbenannt.</div>';
            } else {
                $message = '<div class="alert alert-info">Keine Änderung vorgenommen oder keine Berechtigung.</div>';
            }
            $stmt->close();
        } else {
            $message = '<div class="alert alert-danger">Ungültige Daten zum Bearbeiten.</div>';
        }
    }
}
// AKTION: ORT LÖSCHEN
elseif (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $location_id = intval($_GET['id']);

    $stmt_check = $conn->prepare("SELECT COUNT(*) as child_count FROM storage_locations WHERE parent_id = ?");
    $stmt_check->bind_param("i", $location_id);
    $stmt_check->execute();
    $child_count = $stmt_check->get_result()->fetch_assoc()['child_count'];
    $stmt_check->close();

    if ($child_count > 0) {
        $message = '<div class="alert alert-danger">Dieser Ort kann nicht gelöscht werden, da ihm noch Unter-Orte zugeordnet sind. Bitte leere ihn zuerst.</div>';
    } else {
        $stmt_delete = $conn->prepare("DELETE FROM storage_locations WHERE id = ? AND user_id IN ($placeholders)");
        $all_params = array_merge([$location_id], $household_member_ids);
        $all_types = 'i' . $types;
        $stmt_delete->bind_param($all_types, ...$all_params);
        
        if ($stmt_delete->execute() && $stmt_delete->affected_rows > 0) {
            $message = '<div class="alert alert-success">Lagerort erfolgreich gelöscht.</div>';
        } else {
            $message = '<div class="alert alert-danger">Fehler: Ort nicht gefunden oder keine Berechtigung.</div>';
        }
        $stmt_delete->close();
    }
}


// Lade alle Orte des Haushalts
$sql = "SELECT sl.id, sl.name, sl.parent_id, sl.user_id FROM storage_locations sl WHERE sl.user_id IN ($placeholders) ORDER BY sl.parent_id ASC, sl.name ASC";
$stmt_load = $conn->prepare($sql);
$stmt_load->bind_param($types, ...$household_member_ids);
$stmt_load->execute();
$all_locations = $stmt_load->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_load->close();
$conn->close();

// Strukturiere Orte hierarchisch
$locations_level1 = [];
$locations_level2 = [];
foreach ($all_locations as $location) {
    if ($location['parent_id'] === NULL) {
        $locations_level1[] = $location;
    } else {
        if (!isset($locations_level2[$location['parent_id']])) {
            $locations_level2[$location['parent_id']] = [];
        }
        $locations_level2[$location['parent_id']][] = $location;
    }
}
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0"><i class="fas fa-archive me-2"></i>Lagerorte verwalten</h2>
    </div>
    <div class="card-body p-4">
        <?php if(!empty($message)) echo $message; ?>

        <div class="card bg-light mb-5">
            <div class="card-body">
                <h5 class="card-title mb-3">Neuen Lagerort hinzufügen</h5>
                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                    <div class="row g-3">
                        <div class="col-md-5">
                            <label for="name" class="form-label">Name des Ortes</label>
                            <input type="text" class="form-control" id="name" name="name" placeholder="z.B. Keller, Schrank, Box #3" required>
                        </div>
                        <div class="col-md-5">
                            <label for="parent_id" class="form-label">Untergeordnet zu (Ebene 2)</label>
                            <select class="form-select" id="parent_id" name="parent_id">
                                <option value="">-- Keine (neue Ebene 1) --</option>
                                <?php foreach ($locations_level1 as $loc1): ?>
                                    <option value="<?php echo $loc1['id']; ?>"><?php echo htmlspecialchars($loc1['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" name="add_location" class="btn btn-primary w-100"><i class="fas fa-plus-circle me-2"></i>Hinzufügen</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <h5 class="mb-3">Bestehende Lagerorte</h5>
        <?php if (empty($locations_level1)): ?>
            <div class="alert alert-info text-center">Noch keine Lagerorte erstellt.</div>
        <?php else: ?>
            <div class="row g-3">
                <?php foreach ($locations_level1 as $loc1): ?>
                    <div class="col-md-6">
                        <div class="card level-1-card h-100">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h6 class="mb-0"><i class="fas fa-box-open me-2"></i><?php echo htmlspecialchars($loc1['name']); ?></h6>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editLocationModal" data-id="<?php echo $loc1['id']; ?>" data-name="<?php echo htmlspecialchars($loc1['name']); ?>"><i class="fas fa-edit"></i></button>
                                    <a href="storage_locations.php?action=delete&id=<?php echo $loc1['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Sicher, dass du diesen Ort löschen willst?');"><i class="fas fa-trash"></i></a>
                                </div>
                            </div>
                            <div class="card-body">
                                <?php if (isset($locations_level2[$loc1['id']])): ?>
                                    <ul class="list-group level-2-list">
                                    <?php foreach ($locations_level2[$loc1['id']] as $loc2): ?>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            <span><i class="fas fa-long-arrow-alt-right me-2 text-muted"></i><?php echo htmlspecialchars($loc2['name']); ?></span>
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-sm btn-outline-primary py-0 px-1" data-bs-toggle="modal" data-bs-target="#editLocationModal" data-id="<?php echo $loc2['id']; ?>" data-name="<?php echo htmlspecialchars($loc2['name']); ?>"><i class="fas fa-edit"></i></button>
                                                <a href="storage_locations.php?action=delete&id=<?php echo $loc2['id']; ?>" class="btn btn-sm btn-outline-danger py-0 px-1" onclick="return confirm('Sicher, dass du diesen Unter-Ort löschen willst?');"><i class="fas fa-trash"></i></a>
                                            </div>
                                        </li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p class="text-muted small text-center">Noch keine Unter-Ebenen vorhanden.</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="editLocationModal" tabindex="-1" aria-labelledby="editLocationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editLocationModalLabel">Lagerort umbenennen</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <div class="modal-body">
                    <input type="hidden" name="location_id" id="edit_location_id">
                    <div class="mb-3">
                        <label for="edit_name" class="form-label">Neuer Name</label>
                        <input type="text" class="form-control" id="edit_name" name="edit_name" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
                    <button type="submit" name="edit_location" class="btn btn-primary">Speichern</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var editLocationModal = document.getElementById('editLocationModal');
    if (editLocationModal) {
        editLocationModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var locationId = button.getAttribute('data-id');
            var locationName = button.getAttribute('data-name');
            editLocationModal.querySelector('#edit_location_id').value = locationId;
            editLocationModal.querySelector('#edit_name').value = locationName;
        });
    }
});
</script>

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