<?php
/**
 * bulk_update.php
 * Ändert Kategorie oder Ort für mehrere Einträge
 */

// SESSION GANZ AM ANFANG STARTEN - VOR ALLEM ANDEREN!
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Fehler komplett unterdrücken
error_reporting(0);
ini_set('display_errors', '0');

// ALLE Output Buffer leeren
while (ob_get_level()) {
    ob_end_clean();
}

// Neuer Buffer
ob_start();

require_once 'db.php';
require_once 'helpers.php'; // FÜR logActivity()
requireLogin();

if (!canEdit()) {
    ob_end_clean();
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Keine Berechtigung']);
    exit;
}

// Buffer verwerfen und Header setzen
ob_end_clean();
header('Content-Type: application/json');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $ids = $input['ids'] ?? [];
    $action = $input['action'] ?? '';
    
    // Legacy-Support (altes Format)
    $field = $input['field'] ?? '';
    $value = $input['value'] ?? null;
    
    // Neues Format (action-basiert)
    if ($action === 'change_category') {
        $field = 'kategorie_id';
        $value = $input['category_id'] ?? null;
    } elseif ($action === 'change_location') {
        $field = 'raum_id';
        $value = $input['location_id'] ?? null;
    }
    
    if (empty($ids) || !is_array($ids)) {
        echo json_encode(['success' => false, 'error' => 'Keine IDs angegeben']);
        exit;
    }
    
    if (!in_array($field, ['kategorie_id', 'raum_id'])) {
        echo json_encode(['success' => false, 'error' => t('bulk_invalid_field')]);
        exit;
    }
    
    if ($value === null) {
        echo json_encode(['success' => false, 'error' => 'Kein Wert angegeben']);
        exit;
    }
    
    $ids = array_filter($ids, 'is_numeric');
    $ids = array_map('intval', $ids);
    
    if (empty($ids)) {
        echo json_encode(['success' => false, 'error' => t('bulk_invalid_ids')]);
        exit;
    }
    
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    
    $stmt = $pdo->prepare("UPDATE wertsachen SET $field = ?, geaendert_am = datetime('now') WHERE id IN ($placeholders)");
    $params = array_merge([$value], $ids);
    $stmt->execute($params);
    
    $affected = $stmt->rowCount();
    
    // Activity Log
    $fieldName = $field === 'kategorie_id' ? 'kategorie' : 'ort';
    foreach ($ids as $id) {
        logActivity('update', 'wertsachen', $id, "Bulk-Update $fieldName");
    }
    
    echo json_encode([
        'success' => true,
        'affected' => $affected,
        'message' => $affected . ' ' . t('bulk_entries_updated')
    ]);
    
} catch (Exception $e) {
    error_log("Bulk Update Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Datenbankfehler']);
}
