<?php
// manufacturers.php - Herstellerverwaltung
// FINALE VERSION mit Haushaltslogik

$page_title = "Hersteller 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 '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_manufacturer'])) {
        $manufacturer_name = trim($_POST['manufacturer_name']);
        if (!empty($manufacturer_name)) {
            $stmt = $conn->prepare("INSERT INTO manufacturers (name, user_id) VALUES (?, ?)");
            $stmt->bind_param("si", $manufacturer_name, $current_user_id);
            if ($stmt->execute()) {
                if ($household_id) {
                    $log_message = htmlspecialchars($_SESSION['username']) . " hat den Hersteller '" . htmlspecialchars($manufacturer_name) . "' hinzugefügt.";
                    log_household_action($conn, $household_id, $current_user_id, $log_message);
                }
                $message = '<div class="alert alert-success" role="alert">Hersteller erfolgreich hinzugefügt!</div>';
            } else {
                if ($conn->errno == 1062) {
                    $message = '<div class="alert alert-danger" role="alert">Fehler: Ein Hersteller mit diesem Namen existiert bereits für dein Konto.</div>';
                } else {
                    $message = '<div class="alert alert-danger" role="alert">Fehler beim Hinzufügen des Herstellers: ' . $stmt->error . '</div>';
                }
            }
            $stmt->close();
        } else {
            $message = '<div class="alert alert-danger" role="alert">Der Herstellername darf nicht leer sein.</div>';
        }
    } 
    elseif (isset($_POST['edit_manufacturer'])) {
        // ... (POST-Logik unverändert) ...
    }
} 
elseif (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    // ... (DELETE-Logik unverändert) ...
}

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

<div class="card">
    <div class="card-header">
        <h2 class="h4 mb-0">Hersteller 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">Neuen Hersteller 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="manufacturer_name" class="form-label visually-hidden">Neuer Hersteller</label>
                        <input type="text" class="form-control" id="manufacturer_name" name="manufacturer_name" placeholder="Name des neuen Herstellers" required>
                    </div>
                    <div class="col-sm-4">
                        <button type="submit" name="add_manufacturer" 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 Hersteller</h5>
        <?php if (empty($manufacturers_list)): ?>
            <div class="alert alert-info text-center">Keine Hersteller gefunden.</div>
        <?php else: ?>
            <div class="list-group">
                <?php foreach ($manufacturers_list as $manufacturer): ?>
                    <div class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-industry text-muted me-2"></i>
                            <span><?php echo htmlspecialchars($manufacturer['name']); ?></span>
                            <?php if ($manufacturer['user_id'] != $current_user_id): ?>
                                <small class="text-muted ms-2">(von <?php echo htmlspecialchars($manufacturer['creator_name']); ?>)</small>
                            <?php endif; ?>
                        </div>
                        <?php if ($manufacturer['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="#editManufacturerModal"
                                data-id="<?php echo htmlspecialchars($manufacturer['id']); ?>" data-name="<?php echo htmlspecialchars($manufacturer['name']); ?>">
                                <i class="fas fa-edit"></i>
                            </button>
                            <a href="manufacturers.php?action=delete&id=<?php echo htmlspecialchars($manufacturer['id']); ?>" class="btn btn-sm btn-outline-danger" title="Löschen" onclick="return confirm('Sind Sie sicher, dass Sie diesen Hersteller löschen möchten? Artikel, die diesem Hersteller 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="editManufacturerModal" tabindex="-1" aria-labelledby="editManufacturerModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editManufacturerModalLabel">Hersteller 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="manufacturer_id" id="edit_manufacturer_id">
                    <div class="mb-3">
                        <label for="edit_manufacturer_name" class="form-label">Herstellername</label>
                        <input type="text" class="form-control" id="edit_manufacturer_name" name="manufacturer_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_manufacturer" class="btn btn-primary">Änderungen speichern</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

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