<?php
/**
 * Save Sidebar Preference API
 */

session_start();
require_once '../../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Nicht autorisiert']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['sidebar_collapsed'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Ungültige Daten']);
    exit;
}

$user_id = $_SESSION['admin_user_id'];
$sidebar_collapsed = $input['sidebar_collapsed'] ? 'true' : 'false';

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Save sidebar preference to admin_settings table
    $stmt = $conn->prepare("INSERT INTO admin_settings (user_id, setting_key, setting_value) VALUES (?, 'sidebar_collapsed', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute([$user_id, $sidebar_collapsed, $sidebar_collapsed]);
    
    echo json_encode([
        'success' => true, 
        'message' => 'Sidebar-Einstellung gespeichert',
        'sidebar_collapsed' => $sidebar_collapsed === 'true'
    ]);
    
} catch (Exception $e) {
    error_log("Error saving sidebar preference: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Fehler beim Speichern']);
}
?>
