<?php
// categories.php - Kategorienverwaltung
// FINALE VERSION mit Haushaltslogik

$page_title = "Kategorien im Haushalt";

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 'household_actions.php'; // Für die Logging-Funktion
require_once 'header.php';

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

$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));

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['add_category'])) {
        $category_name = trim($_POST['category_name']);
        if (!empty($category_name)) {
            $stmt = $conn->prepare("INSERT INTO categories (name, user_id) VALUES (?, ?)");
            $stmt->bind_param("si", $category_name, $current_user_id);
            if ($stmt->execute()) {
                if ($household_id) {
                    $log_message = htmlspecialchars($_SESSION['username']) . " hat die Kategorie '" . htmlspecialchars($category_name) . "' hinzugefügt.";
                    log_household_action($conn, $household_id, $current_user_id, $log_message);
                }
                $message = '<div class="alert alert-success" role="alert">Kategorie erfolgreich hinzugefügt!</div>';
            } else { /* ... */ }
            $stmt->close();
        } else { /* ... */ }
    } 
    elseif (isset($_POST['edit_category'])) {
        // ...
    }
} 
elseif (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    // ...
}

$stmt_load = $conn->prepare("SELECT c.id, c.name, c.user_id, u.username as creator_name FROM categories c JOIN users u ON c.user_id = u.id WHERE c.user_id IN ($placeholders) ORDER BY c.name ASC");
$stmt_load->bind_param($types, ...$household_member_ids);
$stmt_load->execute();
$categories_list = $stmt_load->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_load->close();
$conn->close();
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0">Kategorien im Haushalt</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">Neue Kategorie hinzufügen</h5>
                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="row g-3 align-items-end">
                    <div class="col-sm-8">
                        <label for="category_name" class="form-label visually-hidden">Neue Kategorie</label>
                        <input type="text" class="form-control" id="category_name" name="category_name" placeholder="Name der neuen Kategorie" required>
                    </div>
                    <div class="col-sm-4">
                        <button type="submit" name="add_category" class="btn btn-primary w-100"><i class="fas fa-plus-circle me-2"></i>Hinzufügen</button>
                    </div>
                </form>
            </div>
        </div>

        <h5 class="mb-3">Bestehende Kategorien</h5>
        <?php if (empty($categories_list)): ?>
            <div class="alert alert-info text-center">Keine Kategorien im Haushalt gefunden.</div>
        <?php else: ?>
            <div class="list-group">
                <?php foreach ($categories_list as $category): ?>
                    <div class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-tag text-muted me-2"></i>
                            <span><?php echo htmlspecialchars($category['name']); ?></span>
                            <?php if ($category['user_id'] != $current_user_id): ?>
                                <small class="text-muted ms-2">(von <?php echo htmlspecialchars($category['creator_name']); ?>)</small>
                            <?php endif; ?>
                        </div>
                        <?php if ($category['user_id'] == $current_user_id): ?>
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-outline-primary" title="Bearbeiten" data-bs-toggle="modal" data-bs-target="#editCategoryModal"
                                data-id="<?php echo htmlspecialchars($category['id']); ?>" data-name="<?php echo htmlspecialchars($category['name']); ?>">
                                <i class="fas fa-edit"></i>
                            </button>
                            <a href="categories.php?action=delete&id=<?php echo htmlspecialchars($category['id']); ?>" class="btn btn-sm btn-outline-danger" title="Löschen" onclick="return confirm('Sind Sie sicher, dass Sie diese Kategorie löschen möchten? Artikel, die dieser Kategorie zugewiesen sind, verlieren ihre Zuordnung.')">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editCategoryModalLabel">Kategorie bearbeiten</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="category_id" id="edit_category_id">
                    <div class="mb-3">
                        <label for="edit_category_name" class="form-label">Kategoriename</label>
                        <input type="text" class="form-control" id="edit_category_name" name="category_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_category" class="btn btn-primary">Änderungen speichern</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var editCategoryModal = document.getElementById('editCategoryModal');
    if (editCategoryModal) {
        editCategoryModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var categoryId = button.getAttribute('data-id');
            var categoryName = button.getAttribute('data-name');
            var modalIdInput = editCategoryModal.querySelector('#edit_category_id');
            var modalNameInput = editCategoryModal.querySelector('#edit_category_name');
            if (modalIdInput) modalIdInput.value = categoryId;
            if (modalNameInput) modalNameInput.value = categoryName;
        });
    }
});
</script>

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