<?php
session_start();

// Prüfe ob Admin eingeloggt ist
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: login.php');
    exit;
}

require_once dirname(__DIR__) . '/config/database.php';

// Lade Autohäuser für Dropdown
try {
$db = new Database();
$conn = $db->getConnection();
    $stmt = $conn->prepare("SELECT id, name FROM autohaus WHERE is_active = 1 ORDER BY name");
$stmt->execute();
$autohauser = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $autohauser = [];
}

// Get current user data
$current_user_id = $_SESSION['admin_user_id'] ?? null;
$current_user_name = 'Admin';
$current_user_role = 'admin'; // Default role
$current_user_autohaus_id = null;
$current_user_autohaus_name = null;

if ($current_user_id) {
    $stmt = $conn->prepare("
        SELECT u.full_name, u.username, u.role, u.autohaus_id, u.can_switch_autohaus, a.name as autohaus_name
        FROM admin_users u
        LEFT JOIN autohaus a ON u.autohaus_id = a.id
        WHERE u.id = ?
    ");
    $stmt->execute([$current_user_id]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    $current_user_name = $user_data['full_name'] ?? $user_data['username'] ?? 'Benutzer';
    $current_user_role = $user_data['role'] ?? 'admin'; // Setze die Rolle aus der Datenbank
    $current_user_autohaus_id = $user_data['autohaus_id'];
    $current_user_autohaus_name = $user_data['autohaus_name'];
}

// Get user theme preference
$current_theme = 'light';
if ($current_user_id) {
    $stmt = $conn->prepare("SELECT theme FROM admin_users WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $theme_result = $stmt->fetch();
    $current_theme = $theme_result['theme'] ?? 'light';
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <title>Reifenlager - Boxenstop Admin</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/volvo-theme.css">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="stylesheet" href="assets/css/global-dark-theme.css">
    <link rel="stylesheet" href="assets/css/unified-sidebar.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css" rel="stylesheet">
    
    <style>
        /* Storage-specific styles */
        .storage-container {
            background: var(--volvo-white);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-sm);
            margin-bottom: var(--space-lg);
        }
        
        .filter-section {
            background: var(--volvo-gray-50);
            border-radius: var(--radius-md);
            padding: var(--space-lg);
            margin-bottom: var(--space-lg);
            border: 1px solid var(--volvo-gray-200);
        }
        
        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: var(--space-md);
            align-items: end;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: var(--space-md);
            margin-bottom: var(--space-lg);
        }
        
        .stat-card {
            background: var(--volvo-white);
            border-radius: var(--radius-md);
            padding: var(--space-lg);
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--volvo-gray-200);
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        
        .stat-header {
            display: flex;
            align-items: center;
            gap: var(--space-md);
            margin-bottom: var(--space-sm);
        }
        
        .stat-icon {
            width: 40px;
            height: 40px;
            border-radius: var(--radius-md);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            color: var(--volvo-white);
        }
        
        .stat-icon.primary { background: var(--volvo-blue); }
        .stat-icon.success { background: #28a745; }
        .stat-icon.warning { background: #ffc107; }
        .stat-icon.danger { background: #dc3545; }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--volvo-gray-700);
            margin: 0;
        }
        
        .stat-label {
            color: var(--volvo-gray-500);
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .wheelsets-table {
            background: var(--volvo-white);
            border-radius: var(--radius-lg);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
        }
        
        .table-header {
            background: var(--volvo-blue);
            color: var(--volvo-white);
            padding: var(--space-lg);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-header h3 {
            margin: 0;
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .table-actions {
            display: flex;
            gap: var(--space-sm);
        }
        
        .dataTables_wrapper {
            padding: var(--space-lg);
        }
        
        .dataTables_length,
        .dataTables_filter {
            margin-bottom: var(--space-md);
        }
        
        .dataTables_length select,
        .dataTables_filter input {
            border: 1px solid var(--volvo-gray-300);
            border-radius: var(--radius-sm);
            padding: var(--space-sm);
            font-size: 0.9rem;
        }
        
        .dataTables_length select:focus,
        .dataTables_filter input:focus {
            border-color: var(--volvo-accent);
            outline: none;
            box-shadow: 0 0 0 2px rgba(0, 120, 212, 0.2);
        }
        
        .dataTables_info {
            color: var(--volvo-gray-500);
            font-size: 0.9rem;
        }
        
        .dataTables_paginate .paginate_button {
            border: 1px solid var(--volvo-gray-300) !important;
            border-radius: var(--radius-sm) !important;
            margin: 0 2px !important;
            padding: var(--space-sm) var(--space-md) !important;
            transition: all 0.3s ease !important;
            color: var(--volvo-gray-600) !important;
        }
        
        .dataTables_paginate .paginate_button:hover {
            background: var(--volvo-accent) !important;
            color: var(--volvo-white) !important;
            border-color: var(--volvo-accent) !important;
        }
        
        .dataTables_paginate .paginate_button.current {
            background: var(--volvo-blue) !important;
            color: var(--volvo-white) !important;
            border-color: var(--volvo-blue) !important;
        }
        
        .status-badge {
            padding: 8px 16px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .status-badge:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }
        
        .status-eingelagert {
            background: #d4edda;
            color: #155724;
        }
        
        .status-bestellt {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-geliefert {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .empfehlung-keine-fehler {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 2px 4px rgba(16, 185, 129, 0.3);
        }
        
        .empfehlung-austausch {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3);
        }
        
        /* Professional Clipboard Button Styles */
        .clipboard-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-size: 0.7rem;
            font-weight: 500;
            cursor: pointer;
            margin-left: 10px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-flex;
            align-items: center;
            gap: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
        }
        
        .clipboard-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }
        
        .clipboard-btn:hover::before {
            left: 100%;
        }
        
        .clipboard-btn:hover {
            background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .clipboard-btn:active {
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        }
        
        .clipboard-btn.copied {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            animation: pulse 0.6s ease-in-out;
        }
        
        .clipboard-btn i {
            font-size: 0.65rem;
            transition: transform 0.2s ease;
        }
        
        .clipboard-btn:hover i {
            transform: scale(1.1);
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        /* Professional Wrapper Styles */
        .satznummer-wrapper,
        .kennzeichen-wrapper,
        .fin-wrapper,
        .halter-info {
            display: flex !important;
            align-items: center !important;
            gap: 12px !important;
            padding: 8px 0 !important;
            position: relative !important;
        }
        
        .satznummer-wrapper .satznummer-value,
        .kennzeichen-wrapper .kennzeichen-badge,
        .fin-wrapper .fin-code,
        .halter-info span {
            flex: 1 !important;
            font-weight: 500 !important;
        }
        
        /* Enhanced Value Styling */
        .satznummer-value {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.85rem;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .kennzeichen-badge {
            background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.8rem;
            letter-spacing: 1px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .fin-code {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.8rem;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            font-family: 'Courier New', monospace;
        }
        
        .halter-info span {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.85rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        /* Ensure clipboard buttons are visible */
        .clipboard-btn {
            display: inline-flex !important;
            visibility: visible !important;
            opacity: 1 !important;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }
        
        .loading-overlay.show {
            display: flex;
        }
        
        .loading-content {
            text-align: center;
            background: var(--volvo-white);
            padding: var(--space-xl);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-lg);
        }
        
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid var(--volvo-gray-200);
            border-top: 4px solid var(--volvo-accent);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto var(--space-md);
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .column-selector {
            position: fixed;
            top: 0;
            right: -400px;
            width: 400px;
            height: 100vh;
            background: var(--volvo-white);
            box-shadow: -4px 0 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            transition: right 0.3s ease;
            overflow-y: auto;
        }
        
        .column-selector.show {
            right: 0;
        }
        
        .column-selector-header {
            background: var(--volvo-blue);
            color: var(--volvo-white);
            padding: var(--space-lg);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .column-selector-content {
            padding: var(--space-lg);
        }
        
        .column-item {
            display: flex;
            align-items: center;
            padding: var(--space-md) 0;
            border-bottom: 1px solid var(--volvo-gray-200);
        }
        
        .column-item:last-child {
            border-bottom: none;
        }
        
        .column-item label {
            display: flex;
            align-items: center;
            margin: 0;
            cursor: pointer;
            font-weight: 500;
            color: var(--volvo-gray-700);
            flex: 1;
        }
        
        .column-item input[type="checkbox"] {
            margin-right: var(--space-md);
            transform: scale(1.2);
        }
        
        .column-item i {
            margin-right: var(--space-sm);
            width: 20px;
            color: var(--volvo-accent);
        }
        
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
            display: none;
        }
        
        .overlay.show {
            display: block;
        }
        
        .btn-group-sm .btn {
            padding: var(--space-xs) var(--space-sm);
            font-size: 0.8rem;
        }
        
        .table td {
            vertical-align: middle;
        }
        
        .table th {
            background: var(--volvo-gray-100);
            color: var(--volvo-gray-700);
            font-weight: 600;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border: none;
        }
        
        .table tbody tr:hover {
            background: var(--volvo-gray-50);
        }
        
        .empty-state {
            text-align: center;
            padding: var(--space-2xl);
            color: var(--volvo-gray-500);
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: var(--space-md);
            color: var(--volvo-gray-400);
        }
        
        .alert {
            border: none;
            border-radius: var(--radius-md);
            padding: var(--space-md) var(--space-lg);
            margin-bottom: var(--space-lg);
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border-left: 4px solid #ffc107;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }
        
        @media (max-width: 768px) {
            .column-selector {
                width: 100%;
                right: -100%;
            }
            
            .filter-grid {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .table-actions {
            flex-direction: column;
            }
        }

        /* Statistics Section */
        .statistics-section {
            margin-bottom: var(--space-2xl);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: var(--space-lg);
            margin-bottom: var(--space-xl);
        }

        .stat-card {
            background: linear-gradient(135deg, var(--volvo-white) 0%, #f8f9fa 100%);
            border-radius: 16px;
            padding: var(--space-xl);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            border-left: 5px solid;
            display: flex;
            align-items: center;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .stat-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, rgba(255,255,255,0.1), rgba(255,255,255,0.05));
            border-radius: 50%;
            transform: translate(30px, -30px);
        }

        .stat-card.stat-primary {
            border-left-color: var(--volvo-blue);
        }

        .stat-card.stat-success {
            border-left-color: #28a745;
        }

        .stat-card.stat-warning {
            border-left-color: #ffc107;
        }

        .stat-card.stat-info {
            border-left-color: #17a2b8;
        }

        .stat-icon {
            margin-right: var(--space-lg);
            font-size: 2.5rem;
            opacity: 0.8;
        }

        .stat-card.stat-primary .stat-icon {
            color: var(--volvo-blue);
        }

        .stat-card.stat-success .stat-icon {
            color: #28a745;
        }

        .stat-card.stat-warning .stat-icon {
            color: #ffc107;
        }

        .stat-card.stat-info .stat-icon {
            color: #17a2b8;
        }

        .stat-content {
            flex: 1;
        }

        .stat-label {
            font-size: 0.9rem;
            font-weight: 600;
            color: var(--volvo-gray-600);
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: var(--space-xs);
        }

        .stat-value {
            font-size: 2.5rem;
            font-weight: 700;
            color: var(--volvo-gray-800);
            line-height: 1;
        }

        /* Professional Table Styling */
        .wheelset-row {
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .wheelset-row:hover {
            background: linear-gradient(135deg, rgba(0, 123, 255, 0.08), rgba(0, 123, 255, 0.03));
            transform: translateX(4px) scale(1.01);
            box-shadow: 0 4px 20px rgba(0, 123, 255, 0.15);
            border-radius: 8px;
            margin: 2px 0;
        }

        .checkbox-cell {
            width: 50px;
            text-align: center;
        }

        .custom-checkbox {
            position: relative;
            display: inline-block;
        }

        .custom-checkbox input[type="checkbox"] {
            opacity: 0;
            position: absolute;
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .custom-checkbox label {
            position: relative;
            display: inline-block;
            width: 20px;
            height: 20px;
            background: var(--volvo-white);
            border: 2px solid var(--volvo-gray-300);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .custom-checkbox input[type="checkbox"]:checked + label {
            background: var(--volvo-blue);
            border-color: var(--volvo-blue);
        }

        .custom-checkbox input[type="checkbox"]:checked + label::after {
            content: '✓';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 12px;
            font-weight: bold;
        }

        .satznummer-cell {
            font-weight: 700;
            color: var(--volvo-blue);
        }

        .satznummer-value {
            background: linear-gradient(135deg, var(--volvo-blue), #0056b3);
            color: white;
            padding: 8px 16px;
            border-radius: 8px;
            font-family: 'Segoe UI', sans-serif;
            font-weight: 700;
            font-size: 1rem;
            letter-spacing: 1px;
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
            display: inline-block;
            min-width: 120px;
            text-align: center;
        }

        .kennzeichen-badge {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            color: #495057;
            padding: 6px 12px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: inline-block;
            font-family: 'Segoe UI', sans-serif;
            border: 1px solid #dee2e6;
        }

        .fin-code {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 0.8rem;
            font-weight: 600;
            letter-spacing: 0.8px;
            box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
            display: inline-block;
            min-width: 140px;
            text-align: center;
        }

        .reifenmodell-name {
            font-weight: 500;
            color: var(--volvo-gray-800);
        }

        .autohaus-info, .halter-info {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .autohaus-info i, .halter-info i {
            color: var(--volvo-accent);
            font-size: 0.9rem;
        }

        .reifenart-badge {
            background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .reifenart-badge:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }
        
        .saison-badge {
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .saison-badge:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }

        .saison-sommer {
            background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
            color: white;
            box-shadow: 0 2px 4px rgba(251, 191, 36, 0.3);
        }

        .saison-winter {
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: white;
            box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
        }

        .saison-ganzjahres {
            background: #6c757d;
            color: white;
        }

        .date-info {
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--volvo-gray-600);
        }

        .date-info i {
            color: var(--volvo-accent);
            font-size: 0.8rem;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            box-shadow: 0 3px 12px rgba(0, 0, 0, 0.15);
            transition: all 0.3s ease;
        }

        .status-badge:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
        }

        .empfehlung-keine-fehler {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .empfehlung-austausch {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }

        .empfehlung-pruefung {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            color: #212529;
        }

        .profiltiefe-info {
            display: flex;
                flex-direction: column;
            gap: 4px;
        }

        .profiltiefe-bar {
            width: 100%;
            height: 6px;
            background: var(--volvo-gray-200);
            border-radius: 3px;
            overflow: hidden;
        }

        .profiltiefe-fill {
            height: 100%;
            background: linear-gradient(90deg, #28a745, #ffc107, #dc3545);
            border-radius: 3px;
            transition: width 0.3s ease;
        }

        .profiltiefe-value {
            font-size: 0.8rem;
            color: var(--volvo-gray-600);
            font-weight: 500;
        }

        .actions-cell {
            width: 120px;
        }

        .table-actions {
            display: flex;
            gap: 4px;
                justify-content: center;
            }

        .action-btn {
            width: 36px;
            height: 36px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            font-size: 0.9rem;
            border: 2px solid transparent;
        }

        .action-btn:hover {
            transform: translateY(-3px) scale(1.1);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
        }

        .btn-outline-warning:hover {
            background: #ffc107;
            border-color: #ffc107;
            color: white;
        }

        .btn-outline-success:hover {
            background: #28a745;
            border-color: #28a745;
            color: white;
        }

        .btn-outline-info:hover {
            background: #17a2b8;
            border-color: #17a2b8;
            color: white;
        }
    </style>
</head>
<body class="admin-body" data-theme="<?php echo htmlspecialchars($current_theme); ?>">
    <div class="admin-container">
        <!-- Include Unified Sidebar -->
        <?php include 'includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="admin-main">
            <!-- Header -->
            <header class="admin-header">
                <div class="header-left">
                    <h1>Reifenlager</h1>
                    <p>Verwaltung aller eingelagerten Reifensätze</p>
                    <?php if ($current_user_autohaus_name): ?>
                        <div class="autohaus-info">
                            <i class="fas fa-building"></i>
                            <span>Autohaus: <strong><?php echo htmlspecialchars($current_user_autohaus_name); ?></strong></span>
            </div>
                    <?php endif; ?>
                        </div>
                <div class="header-right">
                    <div class="header-actions">
                        <button class="btn btn-outline-primary" onclick="toggleColumnSelector()">
                            <i class="fas fa-columns"></i>
                            Spalten
                        </button>
                        <button class="btn btn-primary" onclick="loadWheelsets()">
                            <i class="fas fa-sync-alt"></i>
                            Aktualisieren
                        </button>
                    </div>
                </div>
            </header>

            <!-- Statistics Cards -->
            <div class="statistics-section" id="statisticsCards">
                <div class="stats-grid">
                    <div class="stat-card stat-primary">
                        <div class="stat-icon">
                            <i class="fas fa-warehouse"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-label">Eingelagerte Reifensätze</div>
                            <div class="stat-value" id="totalStored">0</div>
                        </div>
                    </div>
                    
                    <div class="stat-card stat-success">
                        <div class="stat-icon">
                            <i class="fas fa-truck"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-label">Zurückgeliefert</div>
                            <div class="stat-value" id="totalReturned">0</div>
                        </div>
                    </div>
                    
                    <div class="stat-card stat-warning">
                        <div class="stat-icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-label">Empfehlung erforderlich</div>
                            <div class="stat-value" id="totalRecommendation">0</div>
                        </div>
                    </div>
                    
                    <div class="stat-card stat-info">
                        <div class="stat-icon">
                            <i class="fas fa-tire"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-label">Gesamt Reifensätze</div>
                            <div class="stat-value" id="totalWheelsets">0</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filter Section -->
            <div class="filter-section">
                <h3 style="margin-bottom: var(--space-lg); color: var(--volvo-gray-700);">
                    <i class="fas fa-filter"></i>
                    Filter & Suche
                </h3>
                <div class="filter-grid">
                                <div class="form-group">
                        <label for="autohausSelect" class="form-label">
                            <i class="fas fa-building"></i>
                            Autohaus auswählen
                        </label>
                        <select class="form-control" id="autohausSelect">
                            <option value="">-- Autohaus wählen --</option>
                                        <?php foreach ($autohauser as $autohaus): ?>
                                <option value="<?= htmlspecialchars($autohaus['id']) ?>">
                                    <?= htmlspecialchars($autohaus['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                    <div class="form-group">
                        <label for="statusFilter" class="form-label">
                            <i class="fas fa-filter"></i>
                            Status
                        </label>
                        <select class="form-control" id="statusFilter">
                            <option value="">Alle Status</option>
                            <option value="eingelagert">Eingelagert</option>
                            <option value="zurück geliefert">Zurück geliefert</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="empfehlungFilter" class="form-label">
                            <i class="fas fa-exclamation-triangle"></i>
                            Empfehlung
                        </label>
                        <select class="form-control" id="empfehlungFilter">
                            <option value="">Alle Empfehlungen</option>
                            <option value="In Ordnung">In Ordnung</option>
                            <option value="Austausch notwendig">Austausch notwendig</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary w-100" onclick="applyFilters()">
                            <i class="fas fa-search"></i>
                            Filtern
                        </button>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-outline-secondary w-100" onclick="clearFilters()">
                            <i class="fas fa-times"></i>
                            Filter zurücksetzen
                        </button>
                    </div>
                        </div>
                    </div>

            <!-- Statistics -->
            <div class="stats-grid" id="statsContainer" style="display: none;">
                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon primary">
                            <i class="fas fa-tire"></i>
                        </div>
                        <div>
                            <div class="stat-number" id="totalWheelsets">0</div>
                            <div class="stat-label">Gesamt Reifensätze</div>
                        </div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon success">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div>
                            <div class="stat-number" id="healthyWheelsets">0</div>
                            <div class="stat-label">Keine Fehler</div>
                        </div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon warning">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <div>
                            <div class="stat-number" id="warningWheelsets">0</div>
                            <div class="stat-label">Austausch nötig</div>
                        </div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon danger">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div>
                            <div class="stat-number" id="oldWheelsets">0</div>
                            <div class="stat-label">Über 1 Jahr</div>
                        </div>
                    </div>
                </div>
        </div>

            <!-- Alert Messages -->
            <div id="alertContainer"></div>

            <!-- Wheelsets Table -->
            <div class="wheelsets-table" id="tableContainer" style="display: none;">
                <div class="table-header">
                    <h3>
                        <i class="fas fa-table"></i>
                        Reifensätze Übersicht
                    </h3>
                    <div class="table-actions">
                        <button class="btn btn-sm btn-outline-light" onclick="exportToExcel()">
                            <i class="fas fa-file-excel"></i>
                            Excel
                        </button>
                        <button class="btn btn-sm btn-outline-light" onclick="exportToPDF()">
                            <i class="fas fa-file-pdf"></i>
                            PDF
                        </button>
                        <button class="btn btn-sm btn-outline-light" onclick="printTable()">
                            <i class="fas fa-print"></i>
                            Drucken
                        </button>
                    </div>
                </div>
                <div class="dataTables_wrapper">
                    <table class="table table-hover" id="wheelsetsTable">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="selectAll"></th>
                                <th><i class="fas fa-hashtag"></i> Satznummer</th>
                                <th><i class="fas fa-car"></i> Kennzeichen</th>
                                <th><i class="fas fa-barcode"></i> FIN</th>
                                <th><i class="fas fa-tire"></i> Reifenmodell</th>
                                <th><i class="fas fa-building"></i> Autohaus</th>
                                <th><i class="fas fa-snowflake"></i> Reifenart</th>
                                <th><i class="fas fa-calendar"></i> Saison</th>
                                <th><i class="fas fa-calendar-plus"></i> Eingangsdatum</th>
                                <th><i class="fas fa-user"></i> Haltername</th>
                                <th><i class="fas fa-exclamation-triangle"></i> Empfehlung</th>
                                <th><i class="fas fa-ruler"></i> Profiltiefe</th>
                                <th><i class="fas fa-cogs"></i> Aktionen</th>
                            </tr>
                        </thead>
                        <tbody id="wheelsetsTableBody">
                            <!-- Daten werden hier dynamisch geladen -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Empty State -->
            <div class="empty-state" id="emptyState">
                <i class="fas fa-warehouse"></i>
                <h3>Keine Reifensätze geladen</h3>
                <p>Wählen Sie ein Autohaus aus und klicken Sie auf "Aktualisieren" um Reifensätze zu laden.</p>
                <button class="btn btn-primary" onclick="loadWheelsets()">
                    <i class="fas fa-sync-alt"></i>
                    Reifensätze laden
                </button>
            </div>
            </main>
        </div>

    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="spinner"></div>
            <h4>Lade Reifensätze...</h4>
            <p>Bitte warten Sie, während die Daten aus dem RESY-System geladen werden.</p>
        </div>
    </div>

    <!-- Column Selector -->
    <div class="overlay" id="overlay" onclick="toggleColumnSelector()"></div>
    <div class="column-selector" id="columnSelector">
        <div class="column-selector-header">
            <h5>
                <i class="fas fa-columns"></i>
                Spalten auswählen
            </h5>
            <button class="btn btn-sm btn-outline-light" onclick="toggleColumnSelector()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="column-selector-content">
            <div style="margin-bottom: var(--space-lg);">
                <button class="btn btn-sm btn-primary me-2" onclick="selectAllColumns()">
                    <i class="fas fa-check-double"></i>
                    Alle auswählen
                </button>
                <button class="btn btn-sm btn-outline-primary" onclick="selectDefaultColumns()">
                    <i class="fas fa-undo"></i>
                    Standard
                </button>
            </div>
            
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_satznummer" checked onchange="toggleColumn('satznummer')">
                    <i class="fas fa-hashtag"></i>
                    Satznummer
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_kennzeichen" checked onchange="toggleColumn('kennzeichen')">
                    <i class="fas fa-car"></i>
                    Kennzeichen
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_fin" checked onchange="toggleColumn('fin')">
                    <i class="fas fa-barcode"></i>
                    FIN
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_reifenmodell" checked onchange="toggleColumn('reifenmodell')">
                    <i class="fas fa-tire"></i>
                    Reifenmodell
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_autohaus" checked onchange="toggleColumn('autohaus')">
                    <i class="fas fa-building"></i>
                    Autohaus
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_reifenart" checked onchange="toggleColumn('reifenart')">
                    <i class="fas fa-snowflake"></i>
                    Reifenart
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_saison" checked onchange="toggleColumn('saison')">
                    <i class="fas fa-calendar"></i>
                    Saison
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_eingangsdatum" checked onchange="toggleColumn('eingangsdatum')">
                    <i class="fas fa-calendar-plus"></i>
                    Eingangsdatum
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_haltername" checked onchange="toggleColumn('haltername')">
                    <i class="fas fa-user"></i>
                    Haltername
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_empfehlung" checked onchange="toggleColumn('empfehlung')">
                    <i class="fas fa-exclamation-triangle"></i>
                    Empfehlung
                </label>
            </div>
            <div class="column-item">
                <label>
                    <input type="checkbox" id="col_profiltiefe" checked onchange="toggleColumn('profiltiefe')">
                    <i class="fas fa-ruler"></i>
                    Profiltiefe
                </label>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>

    <script>
        let wheelsetsData = [];
        let dataTable = null;
        // Spalten-Management mit localStorage
        let visibleColumns = JSON.parse(localStorage.getItem('wheelsets_columns') || JSON.stringify({
            'satznummer': true,
            'kennzeichen': true,
            'fin': true,
            'reifenmodell': true,
            'autohaus': true,
            'reifenart': true,
            'saison': true,
            'eingangsdatum': true,
            'haltername': true,
            'empfehlung': true,
            'profiltiefe': true
        }));

        $(document).ready(function() {
            // Event Listeners
            $('#autohausSelect').change(function() {
                if ($(this).val()) {
                    loadWheelsets();
                }
            });

            $('#selectAll').change(function() {
                $('tbody input[type="checkbox"]').prop('checked', $(this).prop('checked'));
            });
            
            // Spalten-Checkboxen Event Listener
            $('.column-checkbox').change(function() {
                const column = $(this).data('column');
                visibleColumns[column] = $(this).is(':checked');
                applyColumnVisibility();
            });

            // Initialize DataTable
            initializeDataTable();
        });

        function initializeDataTable() {
            // Zerstöre die DataTable falls sie bereits existiert
            if (dataTable) {
                dataTable.destroy();
                dataTable = null;
            }

            // Prüfe ob die Tabelle bereits eine DataTable ist
            if ($.fn.DataTable.isDataTable('#wheelsetsTable')) {
                $('#wheelsetsTable').DataTable().destroy();
            }

            // Konvertiere wheelsetsData zu DataTable-Format
            const dataTableData = wheelsetsData.map(wheelset => {
                const safeWheelset = {
                    id: wheelset.satznummer || wheelset.id || wheelset.prufdoc_id || '',
                    satznummer: wheelset.satznummer || '-',
                    kennzeichen: wheelset.kennzeichen || '-',
                    fin: wheelset.fin || '-',
                    reifenmodell: wheelset.reifenmodell || '-',
                    autohaus: wheelset.autohaus || '-',
                    reifenart: wheelset.reifenart || '-',
                    saison: wheelset.saison || '-',
                    eingangsdatum: wheelset.eingangsdatum || '-',
                    haltername: wheelset.haltername || '-',
                    empfehlung: wheelset.empfehlung || 'In Ordnung',
                    profiltiefe: wheelset.profiltiefe || '-',
                    status: wheelset.status || 'eingelagert'
                };
                
                return [
                    `<div class="custom-checkbox">
                        <input type="checkbox" class="wheelset-checkbox" value="${safeWheelset.id}">
                        <label></label>
                    </div>`,
                    `<div class="satznummer-wrapper">
                        <span class="satznummer-value">${safeWheelset.satznummer}</span>
                        <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.satznummer}', this)" title="Satznummer kopieren">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>`,
                    `<div class="kennzeichen-wrapper">
                        <span class="kennzeichen-badge">${safeWheelset.kennzeichen}</span>
                        <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.kennzeichen}', this)" title="Kennzeichen kopieren">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>`,
                    `<div class="fin-wrapper">
                        <code class="fin-code">${safeWheelset.fin}</code>
                        <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.fin}', this)" title="FIN kopieren">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>`,
                    `<div class="reifenmodell-info">
                        <div class="reifenmodell-name">${safeWheelset.reifenmodell}</div>
                    </div>`,
                    `<div class="autohaus-info">
                        <i class="fas fa-building"></i>
                        <span>${safeWheelset.autohaus}</span>
                    </div>`,
                    `<span class="reifenart-badge">${safeWheelset.reifenart}</span>`,
                    `<span class="saison-badge ${getSaisonClass(safeWheelset.saison)}">${safeWheelset.saison}</span>`,
                    `<div class="date-info">
                        <i class="fas fa-calendar-alt"></i>
                        <span>${formatDate(safeWheelset.eingangsdatum)}</span>
                    </div>`,
                    `<div class="halter-info">
                        <i class="fas fa-user"></i>
                        <span>${safeWheelset.haltername}</span>
                        <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.haltername}', this)" title="Haltername kopieren">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>`,
                    `<span class="status-badge ${getEmpfehlungClass(safeWheelset.empfehlung)}">
                        <i class="fas ${getEmpfehlungIcon(safeWheelset.empfehlung)}"></i>
                        ${safeWheelset.empfehlung}
                    </span>`,
                    `<div class="profiltiefe-info">
                        <div class="profiltiefe-bar">
                            <div class="profiltiefe-fill" style="width: ${getProfiltiefePercentage(safeWheelset.profiltiefe)}%"></div>
                        </div>
                        <span class="profiltiefe-value">${safeWheelset.profiltiefe} mm</span>
                    </div>`,
                    `<div class="table-actions">
                        <button class="btn btn-outline-warning btn-sm action-btn" onclick="markForReturn('${safeWheelset.satznummer}')" title="Zur Rücklieferung vormerken">
                            <i class="fas fa-arrow-left"></i>
                        </button>
                        <button class="btn btn-outline-success btn-sm action-btn" onclick="orderNow('${safeWheelset.satznummer}')" title="Sofort bestellen">
                            <i class="fas fa-shopping-cart"></i>
                        </button>
                        <button class="btn btn-outline-info btn-sm action-btn" onclick="viewWheelset('${safeWheelset.satznummer}')" title="Details anzeigen">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>`
                ];
            });

            dataTable = $('#wheelsetsTable').DataTable({
                data: dataTableData,
                columns: [
                    { title: "", orderable: false, searchable: false },
                    { title: "Satznummer" },
                    { title: "Kennzeichen" },
                    { title: "FIN" },
                    { title: "Reifenmodell" },
                    { title: "Autohaus" },
                    { title: "Reifenart" },
                    { title: "Saison" },
                    { title: "Eingangsdatum" },
                    { title: "Haltername" },
                    { title: "Empfehlung" },
                    { title: "Profiltiefe" },
                    { title: "Aktionen", orderable: false, searchable: false }
                ],
                responsive: true,
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
                language: {
                    "sEmptyTable": "Keine Daten in der Tabelle verfügbar",
                    "sInfo": "_START_ bis _END_ von _TOTAL_ Einträgen",
                    "sInfoEmpty": "0 bis 0 von 0 Einträgen",
                    "sInfoFiltered": "(gefiltert von _MAX_ Einträgen)",
                    "sInfoPostFix": "",
                    "sInfoThousands": ".",
                    "sLengthMenu": "_MENU_ Einträge anzeigen",
                    "sLoadingRecords": "Wird geladen...",
                    "sProcessing": "Bitte warten...",
                    "sSearch": "Suchen:",
                    "sSearchPlaceholder": "Suchbegriff eingeben...",
                    "sZeroRecords": "Keine passenden Einträge gefunden",
                    "oPaginate": {
                        "sFirst": "Erste",
                        "sLast": "Letzte",
                        "sNext": "Nächste",
                        "sPrevious": "Vorherige"
                    },
                    "oAria": {
                        "sSortAscending": ": aktivieren, um Spalte aufsteigend zu sortieren",
                        "sSortDescending": ": aktivieren, um Spalte absteigend zu sortieren"
                    }
                },
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'excel',
                        text: '<i class="fas fa-file-excel me-1"></i> Excel Export',
                        className: 'btn btn-success btn-sm'
                    },
                    {
                        extend: 'pdf',
                        text: '<i class="fas fa-file-pdf me-1"></i> PDF Export',
                        className: 'btn btn-danger btn-sm'
                    },
                    {
                        extend: 'print',
                        text: '<i class="fas fa-print me-1"></i> Drucken',
                        className: 'btn btn-info btn-sm'
                    }
                ],
                columnDefs: [
                    { orderable: false, targets: [0, -1] }
                ],
                order: [[1, 'asc']]
            });
        }

        function loadWheelsets() {
            const autohausId = $('#autohausSelect').val();
            if (!autohausId) {
                showAlert('Bitte wählen Sie ein Autohaus aus.', 'warning');
                return;
            }

            showLoading(true);
            hideAlert();

            fetch('../api/get_stored_wheelsets.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    autohaus_id: autohausId
                })
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                
                if (data.success) {
                    wheelsetsData = data.wheelsets;
                    displayWheelsets(data.wheelsets);
                    updateStatistics(data.wheelsets);
                    showAlert(`Erfolgreich ${data.count} Reifensätze geladen. Quelle: ${data.source}`, 'success');
                    } else {
                    showAlert('Fehler beim Laden der Reifensätze: ' + data.error, 'danger');
                }
            })
            .catch(error => {
                showLoading(false);
                showAlert('Netzwerkfehler: ' + error.message, 'danger');
                console.error('Error:', error);
            });
        }

        function displayWheelsets(wheelsets) {
            console.log('Displaying wheelsets:', wheelsets.length, 'items');
            console.log('First wheelset:', wheelsets[0]);
            
            // Aktualisiere die globale Variable
            wheelsetsData = wheelsets;
            
            // Berechne Statistiken
            updateStatistics(wheelsets);
            
            if (wheelsets.length === 0) {
                $('#tableContainer').hide();
                $('#emptyState').show();
                    return;
                }
                
            $('#tableContainer').show();
            $('#emptyState').hide();
            
            // DataTable neu initialisieren mit den neuen Daten
            initializeDataTable();
            
            // Spalten-Sichtbarkeit anwenden
            setTimeout(() => {
                applyColumnVisibility();
            }, 100);
        }

        function updateStatistics(wheelsets) {
            console.log('Updating statistics for:', wheelsets.length, 'wheelsets');
            console.log('Sample wheelset:', wheelsets[0]);
            
            const total = wheelsets.length;
            
            // Korrekte Filterung für Status
            const stored = wheelsets.filter(w => {
                const status = w.status || w.status_id || '';
                return status.toString().toLowerCase().includes('eingelagert') || 
                       status.toString().toLowerCase().includes('20') ||
                       status === 'eingelagert' || status === 'Eingelagert';
            }).length;
            
            const returned = wheelsets.filter(w => {
                const status = w.status || w.status_id || '';
                return status.toString().toLowerCase().includes('zurück') || 
                       status.toString().toLowerCase().includes('geliefert') ||
                       status.toString().toLowerCase().includes('100') ||
                       status === 'zurück geliefert' || status === 'Zurück geliefert';
            }).length;
            
            // Korrekte Filterung für Empfehlungen
            const recommendation = wheelsets.filter(w => {
                const empfehlung = w.empfehlung || w.empfehlung_text || '';
                return empfehlung.toString().toLowerCase().includes('austausch') ||
                       empfehlung.toString().toLowerCase().includes('wechsel') ||
                       empfehlung.toString().toLowerCase().includes('defekt');
            }).length;
            
            $('#totalWheelsets').text(total);
            $('#totalStored').text(stored);
            $('#totalReturned').text(returned);
            $('#totalRecommendation').text(recommendation);
            
            console.log('Statistics updated:', { 
                total, 
                stored, 
                returned, 
                recommendation,
                sampleStatus: wheelsets[0]?.status,
                sampleEmpfehlung: wheelsets[0]?.empfehlung
            });
        }

        function createWheelsetRow(wheelset) {
            console.log('Creating row for wheelset:', wheelset);
            
            // Sichere Werte mit Fallbacks - korrekte Feldnamen aus API
            const safeWheelset = {
                id: wheelset.satznummer || wheelset.id || wheelset.prufdoc_id || '',
                satznummer: wheelset.satznummer || '-',
                kennzeichen: wheelset.kennzeichen || '-',
                fin: wheelset.fin || '-',
                reifenmodell: wheelset.reifenmodell || '-',
                autohaus: wheelset.autohaus || '-',
                reifenart: wheelset.reifenart || '-',
                saison: wheelset.saison || '-',
                eingangsdatum: wheelset.eingangsdatum || '-',
                haltername: wheelset.haltername || '-',
                empfehlung: wheelset.empfehlung || 'In Ordnung',
                profiltiefe: wheelset.profiltiefe || '-',
                status: wheelset.status || 'eingelagert'
            };
            
            const empfehlungClass = getEmpfehlungClass(safeWheelset.empfehlung);
            const statusClass = getStatusClass(safeWheelset.status);
            
            return `
                <tr class="wheelset-row">
                    <td class="checkbox-cell">
                        <div class="custom-checkbox">
                            <input type="checkbox" class="wheelset-checkbox" value="${safeWheelset.id}">
                            <label></label>
                                </div>
                            </td>
                    <td class="satznummer-cell">
                        <div class="satznummer-wrapper">
                            <span class="satznummer-value">${safeWheelset.satznummer}</span>
                            <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.satznummer}', this)" title="Satznummer kopieren">
                                <i class="fas fa-copy"></i>
                            </button>
                                </div>
                            </td>
                    <td class="kennzeichen-cell">
                        <div class="kennzeichen-wrapper">
                            <span class="kennzeichen-badge">${safeWheelset.kennzeichen}</span>
                            <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.kennzeichen}', this)" title="Kennzeichen kopieren">
                                <i class="fas fa-copy"></i>
                            </button>
                                </div>
                            </td>
                    <td class="fin-cell">
                        <div class="fin-wrapper">
                            <code class="fin-code">${safeWheelset.fin}</code>
                            <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.fin}', this)" title="FIN kopieren">
                                <i class="fas fa-copy"></i>
                            </button>
                        </div>
                    </td>
                    <td class="reifenmodell-cell">
                        <div class="reifenmodell-info">
                            <div class="reifenmodell-name">${safeWheelset.reifenmodell}</div>
                                </div>
                            </td>
                    <td class="autohaus-cell">
                        <div class="autohaus-info">
                            <i class="fas fa-building"></i>
                            <span>${safeWheelset.autohaus}</span>
                                </div>
                            </td>
                    <td class="reifenart-cell">
                        <span class="reifenart-badge">${safeWheelset.reifenart}</span>
                    </td>
                    <td class="saison-cell">
                        <span class="saison-badge ${getSaisonClass(safeWheelset.saison)}">${safeWheelset.saison}</span>
                    </td>
                    <td class="eingangsdatum-cell">
                                <div class="date-info">
                            <i class="fas fa-calendar-alt"></i>
                            <span>${formatDate(safeWheelset.eingangsdatum)}</span>
                                </div>
                            </td>
                    <td class="haltername-cell">
                        <div class="halter-info">
                            <i class="fas fa-user"></i>
                            <span>${safeWheelset.haltername}</span>
                            <button class="clipboard-btn" onclick="window.copyToClipboard('${safeWheelset.haltername}', this)" title="Haltername kopieren">
                                <i class="fas fa-copy"></i>
                            </button>
                        </div>
                    </td>
                    <td class="empfehlung-cell">
                        <span class="status-badge ${empfehlungClass}">
                            <i class="fas ${getEmpfehlungIcon(safeWheelset.empfehlung)}"></i>
                            ${safeWheelset.empfehlung}
                                    </span>
                    </td>
                    <td class="profiltiefe-cell">
                        <div class="profiltiefe-info">
                            <div class="profiltiefe-bar">
                                <div class="profiltiefe-fill" style="width: ${getProfiltiefePercentage(safeWheelset.profiltiefe)}%"></div>
                            </div>
                            <span class="profiltiefe-value">${safeWheelset.profiltiefe} mm</span>
                                </div>
                            </td>
                    <td class="actions-cell">
                        <div class="table-actions">
                            <button class="btn btn-outline-warning btn-sm action-btn" onclick="markForReturn('${safeWheelset.satznummer}')" title="Zur Rücklieferung vormerken">
                                <i class="fas fa-arrow-left"></i>
                            </button>
                            <button class="btn btn-outline-success btn-sm action-btn" onclick="orderNow('${safeWheelset.satznummer}')" title="Sofort bestellen">
                                <i class="fas fa-shopping-cart"></i>
                            </button>
                            <button class="btn btn-outline-info btn-sm action-btn" onclick="viewWheelset('${safeWheelset.satznummer}')" title="Details anzeigen">
                                <i class="fas fa-eye"></i>
                            </button>
                                </div>
                            </td>
                        </tr>
            `;
        }

        function getEmpfehlungClass(empfehlung) {
            if (!empfehlung || empfehlung === '-') return 'empfehlung-keine-fehler';
            const emp = empfehlung.toString().toLowerCase();
            if (emp.includes('in ordnung') || emp.includes('keine fehler') || emp.includes('ok')) return 'empfehlung-keine-fehler';
            if (emp.includes('austausch') || emp.includes('wechsel') || emp.includes('defekt') || emp.includes('sofortiger')) return 'empfehlung-austausch';
            if (emp.includes('prüfung') || emp.includes('empfohlen')) return 'empfehlung-pruefung';
            return 'empfehlung-keine-fehler';
        }

        function getStatusClass(status) {
            if (!status) return 'status-unknown';
            if (status.toLowerCase().includes('eingelagert')) return 'status-eingelagert';
            if (status.toLowerCase().includes('zurück')) return 'status-geliefert';
            return 'status-unknown';
        }

        function getSaisonClass(saison) {
            if (!saison) return '';
            if (saison.toLowerCase().includes('sommer')) return 'saison-sommer';
            if (saison.toLowerCase().includes('winter')) return 'saison-winter';
            if (saison.toLowerCase().includes('ganzjahres')) return 'saison-ganzjahres';
            return '';
        }

        function getEmpfehlungIcon(empfehlung) {
            if (!empfehlung) return 'fa-check-circle';
            if (empfehlung.toLowerCase().includes('keine fehler')) return 'fa-check-circle';
            if (empfehlung.toLowerCase().includes('austausch')) return 'fa-exclamation-triangle';
            return 'fa-info-circle';
        }

        function getProfiltiefePercentage(profiltiefe) {
            if (!profiltiefe || isNaN(profiltiefe)) return 0;
            const value = parseFloat(profiltiefe);
            if (value >= 7) return 100;
            if (value >= 5) return 75;
            if (value >= 3) return 50;
            if (value >= 1.6) return 25;
            return 10;
        }

        function formatDate(dateString) {
            if (!dateString || dateString === '-') return '-';
            
            try {
                // Prüfe ob es bereits deutsches Format ist (dd.mm.yyyy)
                if (dateString.match(/^\d{2}\.\d{2}\.\d{4}$/)) {
                    return dateString;
                }
                
                // Versuche verschiedene Datum-Formate zu parsen
                let date;
                if (dateString.includes('.')) {
                    // Deutsches Format: dd.mm.yyyy
                    const parts = dateString.split('.');
                    if (parts.length === 3) {
                        date = new Date(parts[2], parts[1] - 1, parts[0]);
                    }
                } else {
                    // ISO Format oder andere
                    date = new Date(dateString);
                }
                
                // Prüfe ob das Datum gültig ist
                if (isNaN(date.getTime())) {
                    return dateString; // Fallback zu Original-String
                }
                
                return date.toLocaleDateString('de-DE');
            } catch (e) {
                console.warn('Date parsing error:', e, 'for date:', dateString);
                return dateString;
            }
        }


        function showLoading(show) {
            if (show) {
                $('#loadingOverlay').addClass('show');
                $('#tableContainer').hide();
                $('#statsContainer').hide();
                $('#emptyState').hide();
            } else {
                $('#loadingOverlay').removeClass('show');
            }
        }

        function showAlert(message, type) {
            const alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'warning' ? 'exclamation-triangle' : 'exclamation-circle'} me-2"></i>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                `;
            $('#alertContainer').html(alertHtml);
        }

        function hideAlert() {
            $('#alertContainer').empty();
        }

        function toggleColumnSelector() {
            const panel = $('#columnSelector');
            const overlay = $('#overlay');
            
            if (panel.hasClass('show')) {
                panel.removeClass('show');
                overlay.removeClass('show');
            } else {
                panel.addClass('show');
                overlay.addClass('show');
            }
        }

        function toggleColumn(columnName) {
            const checkbox = $(`#col_${columnName}`);
            visibleColumns[columnName] = checkbox.prop('checked');
            applyColumnVisibility();
        }

        function selectAllColumns() {
            Object.keys(visibleColumns).forEach(column => {
                visibleColumns[column] = true;
                $(`#col_${column}`).prop('checked', true);
            });
            applyColumnVisibility();
        }

        function selectDefaultColumns() {
            const defaultColumns = {
                'satznummer': true,
                'kennzeichen': true,
                'fin': true,
                'reifenmodell': true,
                'autohaus': true,
                'reifenart': true,
                'saison': true,
                'eingangsdatum': true,
                'haltername': true,
                'empfehlung': true,
                'profiltiefe': true
            };
            
            Object.keys(visibleColumns).forEach(column => {
                visibleColumns[column] = defaultColumns[column] || false;
                $(`#col_${column}`).prop('checked', visibleColumns[column]);
            });
            applyColumnVisibility();
        }

        // Clipboard functionality - Global functions
        window.copyToClipboard = function(text, button) {
            console.log('Copying to clipboard:', text);
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    showCopySuccess(button);
                }).catch(err => {
                    console.error('Clipboard write failed:', err);
                    fallbackCopyToClipboard(text, button);
                });
            } else {
                fallbackCopyToClipboard(text, button);
            }
        };

        window.fallbackCopyToClipboard = function(text, button) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                document.execCommand('copy');
                showCopySuccess(button);
            } catch (err) {
                console.error('Fallback copy failed:', err);
                alert('Kopieren fehlgeschlagen. Bitte manuell kopieren: ' + text);
            }
            
            document.body.removeChild(textArea);
        };

        window.showCopySuccess = function(button) {
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-check"></i> Kopiert!';
            button.classList.add('copied');
            
            setTimeout(() => {
                button.innerHTML = originalText;
                button.classList.remove('copied');
            }, 2000);
        };

        // Filter-Funktionalität
        function applyFilters() {
            console.log('Filter werden angewendet...');
            
            if (!dataTable || !$.fn.DataTable.isDataTable('#wheelsetsTable')) {
                console.log('DataTable nicht verfügbar');
                return;
            }
            
            // Hole Filter-Werte
            const statusFilter = $('#statusFilter').val();
            const empfehlungFilter = $('#empfehlungFilter').val();
            
            console.log('Status Filter:', statusFilter);
            console.log('Empfehlung Filter:', empfehlungFilter);
            
            // Lösche alle bestehenden Filter
            dataTable.columns().search('');
            dataTable.search('');
            
            // Wende Filter an
            if (empfehlungFilter) {
                // Suche in der Empfehlung-Spalte (Index 10)
                dataTable.column(10).search(empfehlungFilter, false, false);
            }
            
            if (statusFilter) {
                // Suche in allen Spalten nach Status
                dataTable.search(statusFilter, false, false);
            }
            
            // Führe Suche aus
            dataTable.draw();
            
            console.log('Filter angewendet');
        }

        function clearFilters() {
            $('#statusFilter').val('');
            $('#empfehlungFilter').val('');
            
            if (dataTable && $.fn.DataTable.isDataTable('#wheelsetsTable')) {
                dataTable.search('').columns().search('').draw();
            }
        }

        function applyColumnVisibility() {
            if (!dataTable || !$.fn.DataTable.isDataTable('#wheelsetsTable')) {
                console.log('DataTable not ready for column visibility');
                    return;
                }
                
            console.log('Applying column visibility:', visibleColumns);
            
            // Hide/show columns based on visibleColumns
            const columnMapping = {
                'satznummer': 1,
                'kennzeichen': 2,
                'fin': 3,
                'reifenmodell': 4,
                'autohaus': 5,
                'reifenart': 6,
                'saison': 7,
                'eingangsdatum': 8,
                'haltername': 9,
                'empfehlung': 10,
                'profiltiefe': 11
            };
            
            Object.keys(columnMapping).forEach(column => {
                const columnIndex = columnMapping[column];
                const isVisible = visibleColumns[column];
                console.log(`Column ${column} (index ${columnIndex}): ${isVisible ? 'visible' : 'hidden'}`);
                
                try {
                    dataTable.column(columnIndex).visible(isVisible);
                } catch (e) {
                    console.error(`Error setting column ${column} visibility:`, e);
                }
            });
            
            // Speichere Einstellungen in localStorage
            localStorage.setItem('wheelsets_columns', JSON.stringify(visibleColumns));
        }

        function applyFilters() {
            if (dataTable) {
                dataTable.draw();
            }
        }

        function markForReturn(satznummer) {
            showAlert(`Reifensatz ${satznummer} zur Rücklieferung vorgemerkt.`, 'info');
        }

        function orderNow(satznummer) {
            showAlert(`Reifensatz ${satznummer} wird sofort bestellt.`, 'info');
        }

        function viewWheelset(satznummer) {
            showAlert(`Details für Reifensatz ${satznummer} werden geladen...`, 'info');
        }

        function exportToExcel() {
            if (dataTable) {
                dataTable.button('.buttons-excel').trigger();
            }
        }

        function exportToPDF() {
            if (dataTable) {
                dataTable.button('.buttons-pdf').trigger();
            }
        }

        function printTable() {
            if (dataTable) {
                dataTable.button('.buttons-print').trigger();
            }
        }

    </script>
    
    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    <script src="assets/js/unified-sidebar.js"></script>
</body>
</html>
