<!DOCTYPE html>
<html lang="ru" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Print Sales Manager</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .dark-mode { background-color: #1a202c; color: #e2e8f0; }
        .light-mode { background-color: #f7fafc; color: #2d3748; }
        .sidebar { transition: all 0.3s ease; }
        .sidebar.collapsed { width: 70px; }
        .sidebar.collapsed .sidebar-text { display: none; }
        .main-content { transition: margin-left 0.3s ease; }
        .file-upload { position: relative; overflow: hidden; display: inline-block; }
        .file-upload input[type="file"] { position: absolute; left: 0; top: 0; opacity: 0; }
        .product-photo { width: 100px; height: 100px; object-fit: cover; }
        .cost-calculator { background-color: #f3f4f6; padding: 1rem; border-radius: 0.5rem; }
        .cost-result { font-weight: bold; color: #2563eb; }
        .cost-formula { font-size: 0.875rem; color: #4b5563; }
    </style>
</head>
<body class="h-full dark-mode">
    <div class="flex h-full">
        <!-- Sidebar -->
        <div class="sidebar bg-gray-800 text-white w-64 h-full fixed overflow-y-auto no-print" id="sidebar">
            <div class="p-4 flex items-center justify-between border-b border-gray-700">
                <h1 class="text-xl font-bold sidebar-text">3D Print Manager</h1>
                <button id="toggleSidebar" class="text-gray-400 hover:text-white">
                    <i class="fas fa-bars sidebar-icon"></i>
                </button>
            </div>
            <nav class="mt-4">
                <div class="px-4 py-2">
                    <button id="toggleTheme" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-moon mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Темная тема</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('dashboard')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-tachometer-alt mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Дашборд</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('materials')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-boxes mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Материалы</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('products')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-cube mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Продукция</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('sales')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-ruble-sign mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Продажи</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('costs')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-calculator mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Калькулятор</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('analytics')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-chart-line mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Аналитика</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('settings')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-cog mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Настройки</span>
                    </button>
                </div>
            </nav>
        </div>

        <!-- Main Content -->
        <div class="main-content flex-1 ml-64 p-6 no-print" id="mainContent">
            <!-- Dashboard Section -->
            <div id="dashboard-section" class="section-content">
                <h2 class="text-2xl font-bold mb-6">Дашборд</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                    <div class="bg-blue-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Выручка за месяц</p>
                                <h3 class="text-2xl font-bold" id="monthlyRevenue">0 ₽</h3>
                            </div>
                            <i class="fas fa-ruble-sign text-3xl opacity-50"></i>
                        </div>
                    </div>
                    <div class="bg-green-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Прибыль за месяц</p>
                                <h3 class="text-2xl font-bold" id="monthlyProfit">0 ₽</h3>
                            </div>
                            <i class="fas fa-chart-line text-3xl opacity-50"></i>
                        </div>
                    </div>
                    <div class="bg-yellow-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Продано товаров</p>
                                <h3 class="text-2xl font-bold" id="soldProducts">0</h3>
                            </div>
                            <i class="fas fa-cube text-3xl opacity-50"></i>
                        </div>
                    </div>
                    <div class="bg-red-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Материалы на исходе</p>
                                <h3 class="text-2xl font-bold" id="lowMaterials">0</h3>
                            </div>
                            <i class="fas fa-exclamation-triangle text-3xl opacity-50"></i>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Продажи по месяцам</h3>
                        <canvas id="salesChart" height="250"></canvas>
                    </div>
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Расход материалов</h3>
                        <canvas id="materialsChart" height="250"></canvas>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Последние продажи</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Дата</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Товар</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Цена</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Прибыль</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="recentSalesTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Materials Section -->
            <div id="materials-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Материалы</h2>
                    <button onclick="showAddMaterialModal()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                        <i class="fas fa-plus mr-2"></i> Добавить материал
                    </button>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Фото</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Название</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Цена за кг</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Остаток</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Дата закупки</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Действия</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="materialsTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Products Section -->
            <div id="products-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Продукция</h2>
                    <button onclick="showAddProductModal()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                        <i class="fas fa-plus mr-2"></i> Добавить продукт
                    </button>
                </div>

                <div class="mb-4">
                    <div class="flex space-x-2">
                        <select id="productFilterStatus" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="all">Все статусы</option>
                            <option value="В производстве">В производстве</option>
                            <option value="В продаже">В продаже</option>
                            <option value="Продан">Продан</option>
                        </select>
                        <button onclick="filterProducts()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Фильтровать</button>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="productsGrid">
                    <!-- Filled by JavaScript -->
                </div>
            </div>

            <!-- Sales Section -->
            <div id="sales-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Продажи</h2>
                    <div class="flex space-x-2">
                        <input type="date" id="salesDateFrom" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <input type="date" id="salesDateTo" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <button onclick="filterSales()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Фильтровать</button>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Дата</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Товар</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Материал</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Цена</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Прибыль</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Действия</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="salesTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Costs Section -->
            <div id="costs-section" class="section-content hidden">
                <h2 class="text-2xl font-bold mb-6">Калькулятор затрат</h2>
                
                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Настройки затрат</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Стоимость электричества (₽/кВт·ч)</label>
                            <input type="number" id="electricityCost" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.01">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Амортизация оборудования (₽/час)</label>
                            <input type="number" id="depreciationCost" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.01">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Дополнительные расходы (₽/час)</label>
                            <input type="number" id="otherCost" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.01">
                        </div>
                        <div>
                            <button onclick="saveCostSettings()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Сохранить настройки</button>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Расчет себестоимости</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Материал</label>
                            <select id="costMaterial" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                <!-- Filled by JavaScript -->
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Вес изделия (г)</label>
                            <input type="number" id="costWeight" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Время печати (часов)</label>
                            <input type="number" id="costTime" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.1">
                        </div>
                        <div>
                            <button onclick="calculateCost()" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md">Рассчитать</button>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                    <h3 class="text-lg font-semibold mb-4">Результаты расчета</h3>
                    <div id="costResults" class="space-y-3">
                        <p class="cost-calculator">Себестоимость пластика: <span id="plasticCost" class="cost-result">0 ₽</span></p>
                        <p class="cost-calculator">Затраты на электричество: <span id="electricityCostResult" class="cost-result">0 ₽</span></p>
                        <p class="cost-calculator">Амортизация оборудования: <span id="depreciationCostResult" class="cost-result">0 ₽</span></p>
                        <p class="cost-calculator">Дополнительные расходы: <span id="otherCostResult" class="cost-result">0 ₽</span></p>
                        <p class="cost-calculator font-bold">Общая себестоимость: <span id="totalCost" class="cost-result">0 ₽</span></p>
                        <p class="cost-formula" id="costFormula"></p>
                    </div>
                </div>
            </div>

            <!-- Analytics Section -->
            <div id="analytics-section" class="section-content hidden">
                <h2 class="text-2xl font-bold mb-6">Аналитика</h2>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Топ 5 материалов по прибыли</h3>
                        <canvas id="topMaterialsChart" height="300"></canvas>
                    </div>
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Топ 5 товаров по продажам</h3>
                        <canvas id="topProductsChart" height="300"></canvas>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Остатки материалов</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Материал</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Остаток (г)</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">% от начального</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Статус</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="materialsStatusTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Settings Section -->
            <div id="settings-section" class="section-content hidden">
                <h2 class="text-2xl font-bold mb-6">Настройки</h2>
                
                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Уведомления</h3>
                    <div class="space-y-4">
                        <div class="flex items-center">
                            <input id="emailNotifications" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="emailNotifications" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">Email уведомления</label>
                        </div>
                        <div class="flex items-center">
                            <input id="telegramNotifications" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="telegramNotifications" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">Telegram уведомления</label>
                        </div>
                        <div id="telegramSettings" class="hidden mt-4">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Telegram Bot Token</label>
                                <input type="text" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Chat ID</label>
                                <input type="text" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Резервное копирование</h3>
                    <div class="space-y-4">
                        <div>
                            <button onclick="exportData()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                <i class="fas fa-file-export mr-2"></i> Экспорт данных
                            </button>
                        </div>
                        <div>
                            <div class="file-upload">
                                <button class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-file-import mr-2"></i> Импорт данных
                                </button>
                                <input type="file" id="importFile" accept=".json">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                    <h3 class="text-lg font-semibold mb-4">Настройки печати</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Логотип для ценников</label>
                            <div class="file-upload">
                                <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-upload mr-2"></i> Загрузить логотип
                                </button>
                                <input type="file" id="logoUpload" accept="image/*">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Размер шрифта</label>
                            <select class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                <option>Маленький</option>
                                <option selected>Средний</option>
                                <option>Большой</option>
                            </select>
                        </div>
                        <div class="flex items-center">
                            <input id="printQR" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="printQR" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">Печатать QR-код на ценнике</label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Material Modal -->
    <div id="addMaterialModal" class="fixed z-50 inset-0 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white dark:bg-gray-700 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg font-medium leading-6 text-gray-900 dark:text-white mb-4">Добавить материал</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Название</label>
                            <input type="text" id="materialName" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Цена за кг (руб)</label>
                            <input type="number" id="materialPrice" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Дата закупки</label>
                            <input type="date" id="materialDate" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Начальный остаток (г)</label>
                            <input type="number" id="materialAmount" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Фото материала</label>
                            <div class="file-upload">
                                <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-upload mr-2"></i> Загрузить фото
                                </button>
                                <input type="file" id="materialPhoto" accept="image/*">
                            </div>
                            <div id="materialPhotoPreview" class="mt-2 hidden">
                                <img id="materialPreviewImage" class="h-16 rounded-md">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button onclick="saveMaterial()" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-500 text-base font-medium text-white hover:bg-blue-600 sm:ml-3 sm:w-auto sm:text-sm">
                        Сохранить
                    </button>
                    <button onclick="hideAddMaterialModal()" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:bg-gray-600 dark:text-white dark:border-gray-500">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Product Modal -->
    <div id="addProductModal" class="fixed z-50 inset-0 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white dark:bg-gray-700 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg font-medium leading-6 text-gray-900 dark:text-white mb-4">Добавить продукт</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Название изделия</label>
                            <input type="text" id="productName" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Материал</label>
                            <select id="productMaterial" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                <!-- Filled by JavaScript -->
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Вес изделия (г)</label>
                            <input type="number" id="productWeight" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Розничная цена (руб)</label>
                            <input type="number" id="productPrice" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Дата производства</label>
                            <input type="date" id="productDate" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Статус</label>
                            <select id="productStatus" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                <option value="В производстве">В производстве</option>
                                <option value="В продаже">В продаже</option>
                                <option value="Продан">Продан</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Фото изделия (до 3)</label>
                            <div class="file-upload">
                                <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-upload mr-2"></i> Загрузить фото
                                </button>
                                <input type="file" id="productPhotos" accept="image/*" multiple>
                            </div>
                            <div id="productPhotosPreview" class="mt-2 grid grid-cols-3 gap-2 hidden">
                                <!-- Filled by JavaScript -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button onclick="saveProduct()" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-500 text-base font-medium text-white hover:bg-blue-600 sm:ml-3 sm:w-auto sm:text-sm">
                        Сохранить
                    </button>
                    <button onclick="hideAddProductModal()" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:bg-gray-600 dark:text-white dark:border-gray-500">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Data Storage -->
    <div id="imageStorage" class="hidden"></div>

    <script>
        // Initialize data
        let materials = [];
        let products = [];
        let sales = [];
        let images = {}; // For storing image data
        let currentTheme = 'dark';
        let sidebarCollapsed = false;
        let costSettings = {
            electricity: 5.0,
            depreciation: 50.0,
            other: 20.0
        };

        // Sample initial data
        function initializeSampleData() {
            if (localStorage.getItem('materials') === null) {
                materials = [
                    { id: 1, name: 'PLA', price: 1200, date: '2023-05-15', amount: 500, initialAmount: 1000, photo: 'https://via.placeholder.com/150?text=PLA' },
                    { id: 2, name: 'PETG', price: 1500, date: '2023-06-20', amount: 300, initialAmount: 800, photo: 'https://via.placeholder.com/150?text=PETG' },
                    { id: 3, name: 'ABS', price: 1300, date: '2023-07-10', amount: 100, initialAmount: 500, photo: 'https://via.placeholder.com/150?text=ABS' }
                ];
                localStorage.setItem('materials', JSON.stringify(materials));
            } else {
                materials = JSON.parse(localStorage.getItem('materials'));
            }

            if (localStorage.getItem('products') === null) {
                products = [
                    { 
                        id: 1, 
                        name: 'Кронштейн для полки', 
                        materialId: 1, 
                        weight: 50, 
                        price: 800, 
                        date: '2023-08-01', 
                        status: 'В продаже', 
                        photos: [
                            'https://via.placeholder.com/150?text=Кронштейн1',
                            'https://via.placeholder.com/150?text=Кронштейн2'
                        ] 
                    },
                    { 
                        id: 2, 
                        name: 'Держатель для телефона', 
                        materialId: 2, 
                        weight: 30, 
                        price: 600, 
                        date: '2023-08-05', 
                        status: 'Продан', 
                        photos: [
                            'https://via.placeholder.com/150?text=Держатель1'
                        ] 
                    },
                    { 
                        id: 3, 
                        name: 'Корпус для Arduino', 
                        materialId: 3, 
                        weight: 70, 
                        price: 900, 
                        date: '2023-08-10', 
                        status: 'В производстве', 
                        photos: [
                            'https://via.placeholder.com/150?text=Корпус1',
                            'https://via.placeholder.com/150?text=Корпус2',
                            'https://via.placeholder.com/150?text=Корпус3'
                        ] 
                    }
                ];
                localStorage.setItem('products', JSON.stringify(products));
            } else {
                products = JSON.parse(localStorage.getItem('products'));
            }

            if (localStorage.getItem('sales') === null) {
                sales = [
                    { id: 1, productId: 2, date: '2023-08-15', price: 600, profit: 450 },
                    { id: 2, productId: 1, date: '2023-08-20', price: 800, profit: 620 },
                    { id: 3, productId: 3, date: '2023-08-25', price: 900, profit: 710 }
                ];
                localStorage.setItem('sales', JSON.stringify(sales));
            } else {
                sales = JSON.parse(localStorage.getItem('sales'));
            }
            
            // Load cost settings
            if (localStorage.getItem('costSettings') !== null) {
                costSettings = JSON.parse(localStorage.getItem('costSettings'));
                document.getElementById('electricityCost').value = costSettings.electricity;
                document.getElementById('depreciationCost').value = costSettings.depreciation;
                document.getElementById('otherCost').value = costSettings.other;
            }
            
            // Load images from storage
            if (localStorage.getItem('images') !== null) {
                images = JSON.parse(localStorage.getItem('images'));
            }
        }

        // Initialize the app
        function initApp() {
            initializeSampleData();
            updateDashboard();
            renderMaterialsTable();
            renderProductsGrid();
            renderSalesTable();
            initCharts();
            setupEventListeners();
            populateCostMaterialDropdown();
        }

        // Update dashboard with current data
        function updateDashboard() {
            // Calculate monthly revenue
            const currentMonth = new Date().getMonth();
            const monthlySales = sales.filter(sale => {
                const saleMonth = new Date(sale.date).getMonth();
                return saleMonth === currentMonth;
            });
            const monthlyRevenue = monthlySales.reduce((sum, sale) => sum + sale.price, 0);
            document.getElementById('monthlyRevenue').textContent = `${monthlyRevenue} ₽`;
            
            // Calculate monthly profit
            const monthlyProfit = monthlySales.reduce((sum, sale) => sum + sale.profit, 0);
            document.getElementById('monthlyProfit').textContent = `${monthlyProfit} ₽`;
            
            // Count sold products
            const soldProductsCount = products.filter(p => p.status === 'Продан').length;
            document.getElementById('soldProducts').textContent = soldProductsCount;
            
            // Count low materials
            const lowMaterialsCount = materials.filter(m => m.amount < 200).length;
            document.getElementById('lowMaterials').textContent = lowMaterialsCount;
            
            // Update recent sales table
            const recentSalesTable = document.getElementById('recentSalesTable');
            recentSalesTable.innerHTML = '';
            
            const recentSales = sales.slice(-5).reverse();
            recentSales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                const material = materials.find(m => m.id === product.materialId);
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${formatDate(sale.date)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${product.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.price} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.profit} ₽</td>
                `;
                recentSalesTable.appendChild(row);
            });
        }

        // Render materials table
        function renderMaterialsTable() {
            const table = document.getElementById('materialsTable');
            table.innerHTML = '';
            
            materials.forEach(material => {
                const row = document.createElement('tr');
                row.className = material.amount < 200 ? 'bg-red-100 dark:bg-red-900' : '';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <img src="${material.photo}" class="h-10 w-10 rounded-full object-cover">
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${material.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${material.price} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
                        <div class="flex items-center">
                            <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-600 mr-2">
                                <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${(material.amount / material.initialAmount) * 100}%"></div>
                            </div>
                            <span>${material.amount} г</span>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${formatDate(material.date)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="editMaterial(${material.id})" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">Изменить</button>
                        <button onclick="deleteMaterial(${material.id})" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">Удалить</button>
                    </td>
                `;
                table.appendChild(row);
            });
        }

        // Render products grid
        function renderProductsGrid(filterStatus = 'all') {
            const grid = document.getElementById('productsGrid');
            grid.innerHTML = '';
            
            let filteredProducts = products;
            if (filterStatus !== 'all') {
                filteredProducts = products.filter(p => p.status === filterStatus);
            }
            
            filteredProducts.forEach(product => {
                const material = materials.find(m => m.id === product.materialId);
                const cost = (product.weight / 1000) * material.price;
                
                const card = document.createElement('div');
                card.className = 'bg-white dark:bg-gray-700 rounded-lg shadow overflow-hidden';
                card.innerHTML = `
                    <div class="relative">
                        <div class="h-32 overflow-hidden">
                            <img src="${product.photos[0] || 'https://via.placeholder.com/150?text=Product'}" class="w-full h-full object-cover">
                        </div>
                        <div class="absolute top-2 right-2 bg-${getStatusColor(product.status)}-500 text-white text-xs px-2 py-1 rounded">
                            ${product.status}
                        </div>
                    </div>
                    <div class="p-4">
                        <h3 class="text-lg font-semibold mb-2 dark:text-white">${product.name}</h3>
                        <div class="flex justify-between text-sm mb-1">
                            <span class="text-gray-600 dark:text-gray-300">Материал:</span>
                            <span class="font-medium dark:text-white">${material.name}</span>
                        </div>
                        <div class="flex justify-between text-sm mb-1">
                            <span class="text-gray-600 dark:text-gray-300">Вес:</span>
                            <span class="font-medium dark:text-white">${product.weight} г</span>
                        </div>
                        <div class="flex justify-between text-sm mb-1">
                            <span class="text-gray-600 dark:text-gray-300">Себестоимость:</span>
                            <span class="font-medium dark:text-white">${Math.round(cost)} ₽</span>
                        </div>
                        <div class="flex justify-between text-sm mb-3">
                            <span class="text-gray-600 dark:text-gray-300">Цена:</span>
                            <span class="font-medium dark:text-white">${product.price} ₽</span>
                        </div>
                        <div class="flex justify-between">
                            <button onclick="showProductPhotos(${product.id})" class="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 text-sm">
                                <i class="fas fa-images mr-1"></i> Фото
                            </button>
                            <button onclick="editProduct(${product.id})" class="text-yellow-500 hover:text-yellow-700 dark:text-yellow-400 dark:hover:text-yellow-300 text-sm">
                                <i class="fas fa-edit mr-1"></i> Изменить
                            </button>
                            <button onclick="deleteProduct(${product.id})" class="text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 text-sm">
                                <i class="fas fa-trash mr-1"></i> Удалить
                            </button>
                        </div>
                    </div>
                `;
                grid.appendChild(card);
            });
        }

        // Render sales table
        function renderSalesTable(filterFrom = null, filterTo = null) {
            const table = document.getElementById('salesTable');
            table.innerHTML = '';
            
            let filteredSales = sales;
            if (filterFrom && filterTo) {
                filteredSales = sales.filter(sale => {
                    const saleDate = new Date(sale.date);
                    return saleDate >= new Date(filterFrom) && saleDate <= new Date(filterTo);
                });
            }
            
            filteredSales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                const material = materials.find(m => m.id === product.materialId);
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${formatDate(sale.date)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${product.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${material.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.price} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.profit} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="deleteSale(${sale.id})" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">Удалить</button>
                    </td>
                `;
                table.appendChild(row);
            });
        }

        // Initialize charts
        function initCharts() {
            // Sales by month chart
            const salesCtx = document.getElementById('salesChart').getContext('2d');
            const months = ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'];
            const currentMonth = new Date().getMonth();
            const salesData = Array(12).fill(0);
            
            sales.forEach(sale => {
                const saleMonth = new Date(sale.date).getMonth();
                salesData[saleMonth] += sale.price;
            });
            
            new Chart(salesCtx, {
                type: 'bar',
                data: {
                    labels: months,
                    datasets: [{
                        label: 'Выручка',
                        data: salesData,
                        backgroundColor: 'rgba(59, 130, 246, 0.5)',
                        borderColor: 'rgba(59, 130, 246, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // Materials usage chart
            const materialsCtx = document.getElementById('materialsChart').getContext('2d');
            const materialNames = materials.map(m => m.name);
            const materialUsage = materials.map(m => m.initialAmount - m.amount);
            
            new Chart(materialsCtx, {
                type: 'doughnut',
                data: {
                    labels: materialNames,
                    datasets: [{
                        data: materialUsage,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.5)',
                            'rgba(54, 162, 235, 0.5)',
                            'rgba(255, 206, 86, 0.5)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true
                }
            });
            
            // Top materials by profit chart
            const topMaterialsCtx = document.getElementById('topMaterialsChart').getContext('2d');
            const materialProfits = {};
            
            sales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                const material = materials.find(m => m.id === product.materialId);
                
                if (!materialProfits[material.name]) {
                    materialProfits[material.name] = 0;
                }
                materialProfits[material.name] += sale.profit;
            });
            
            const sortedMaterials = Object.entries(materialProfits)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 5);
            
            new Chart(topMaterialsCtx, {
                type: 'bar',
                data: {
                    labels: sortedMaterials.map(m => m[0]),
                    datasets: [{
                        label: 'Прибыль',
                        data: sortedMaterials.map(m => m[1]),
                        backgroundColor: 'rgba(75, 192, 192, 0.5)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // Top products by sales chart
            const topProductsCtx = document.getElementById('topProductsChart').getContext('2d');
            const productSales = {};
            
            sales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                
                if (!productSales[product.name]) {
                    productSales[product.name] = 0;
                }
                productSales[product.name]++;
            });
            
            const sortedProducts = Object.entries(productSales)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 5);
            
            new Chart(topProductsCtx, {
                type: 'pie',
                data: {
                    labels: sortedProducts.map(p => p[0]),
                    datasets: [{
                        data: sortedProducts.map(p => p[1]),
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.5)',
                            'rgba(54, 162, 235, 0.5)',
                            'rgba(255, 206, 86, 0.5)',
                            'rgba(75, 192, 192, 0.5)',
                            'rgba(153, 102, 255, 0.5)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true
                }
            });
            
            // Update materials status table
            const materialsStatusTable = document.getElementById('materialsStatusTable');
            materialsStatusTable.innerHTML = '';
            
            materials.forEach(material => {
                const percentage = (material.amount / material.initialAmount) * 100;
                let status = ''; 
                let statusClass = '';
                
                if (percentage > 50) {
                    status = 'Норма';
                    statusClass = 'text-green-500';
                } else if (percentage > 20) {
                    status = 'Мало';
                    statusClass = 'text-yellow-500';
                } else {
                    status = 'На исходе';
                    statusClass = 'text-red-500';
                }
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${material.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${material.amount} г</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
                        <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-600">
                            <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${percentage}%"></div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm ${statusClass}">${status}</td>
                `;
                materialsStatusTable.appendChild(row);
            });
        }

        // Setup event listeners
        function setupEventListeners() {
            // Toggle sidebar
            document.getElementById('toggleSidebar').addEventListener('click', toggleSidebar);
            
            // Toggle theme
            document.getElementById('toggleTheme').addEventListener('click', toggleTheme);
            
            // Material photo upload
            document.getElementById('materialPhoto').addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        document.getElementById('materialPreviewImage').src = event.target.result;
                        document.getElementById('materialPhotoPreview').classList.remove('hidden');
                    };
                    reader.readAsDataURL(file);
                }
            });
            
            // Product photos upload
            document.getElementById('productPhotos').addEventListener('change', function(e) {
                const files = e.target.files;
                const previewContainer = document.getElementById('productPhotosPreview');
                previewContainer.innerHTML = '';
                
                if (files.length > 0) {
                    for (let i = 0; i < Math.min(files.length, 3); i++) {
                        const reader = new FileReader();
                        reader.onload = function(event) {
                            const img = document.createElement('img');
                            img.src = event.target.result;
                            img.className = 'h-20 w-full object-cover rounded-md';
                            previewContainer.appendChild(img);
                        };
                        reader.readAsDataURL(files[i]);
                    }
                    previewContainer.classList.remove('hidden');
                }
            });
            
            // Telegram notifications toggle
            document.getElementById('telegramNotifications').addEventListener('change', function(e) {
                const telegramSettings = document.getElementById('telegramSettings');
                if (e.target.checked) {
                    telegramSettings.classList.remove('hidden');
                } else {
                    telegramSettings.classList.add('hidden');
                }
            });
        }

        // Show section
        function showSection(sectionId) {
            document.querySelectorAll('.section-content').forEach(section => {
                section.classList.add('hidden');
            });
            document.getElementById(`${sectionId}-section`).classList.remove('hidden');
        }

        // Toggle sidebar
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('mainContent');
            
            if (sidebarCollapsed) {
                sidebar.classList.remove('collapsed');
                mainContent.classList.remove('ml-16');
                mainContent.classList.add('ml-64');
            } else {
                sidebar.classList.add('collapsed');
                mainContent.classList.remove('ml-64');
                mainContent.classList.add('ml-16');
            }
            
            sidebarCollapsed = !sidebarCollapsed;
        }

        // Toggle theme
        function toggleTheme() {
            const body = document.body;
            const toggleThemeButton = document.getElementById('toggleTheme');
            
            if (currentTheme === 'dark') {
                body.classList.remove('dark-mode');
                body.classList.add('light-mode');
                toggleThemeButton.innerHTML = `
                    <i class="fas fa-sun mr-3 sidebar-icon"></i>
                    <span class="sidebar-text">Светлая тема</span>
                `;
                currentTheme = 'light';
            } else {
                body.classList.remove('light-mode');
                body.classList.add('dark-mode');
                toggleThemeButton.innerHTML = `
                    <i class="fas fa-moon mr-3 sidebar-icon"></i>
                    <span class="sidebar-text">Темная тема</span>
                `;
                currentTheme = 'dark';
            }
        }

        // Format date
        function formatDate(dateString) {
            const options = { year: 'numeric', month: 'short', day: 'numeric' };
            return new Date(dateString).toLocaleDateString('ru-RU', options);
        }

        // Get status color
        function getStatusColor(status) {
            switch (status) {
                case 'В производстве': return 'yellow';
                case 'В продаже': return 'blue';
                case 'Продан': return 'green';
                default: return 'gray';
            }
        }

        // Material CRUD operations
        function showAddMaterialModal() {
            document.getElementById('addMaterialModal').classList.remove('hidden');
            document.getElementById('materialPhotoPreview').classList.add('hidden');
            document.getElementById('materialName').value = '';
            document.getElementById('materialPrice').value = '';
            document.getElementById('materialDate').value = '';
            document.getElementById('materialAmount').value = '';
            document.getElementById('materialPhoto').value = '';
        }

        function hideAddMaterialModal() {
            document.getElementById('addMaterialModal').classList.add('hidden');
        }

        function saveMaterial() {
            const name = document.getElementById('materialName').value;
            const price = parseFloat(document.getElementById('materialPrice').value);
            const date = document.getElementById('materialDate').value;
            const amount = parseFloat(document.getElementById('materialAmount').value);
            const photoInput = document.getElementById('materialPhoto');
            
            if (!name || !price || !date || !amount) {
                alert('Пожалуйста, заполните все обязательные поля');
                return;
            }
            
            let photo = 'https://via.placeholder.com/150?text=Material';
            if (photoInput.files.length > 0) {
                const file = photoInput.files[0];
                const reader = new FileReader();
                reader.onload = function(e) {
                    const newMaterial = {
                        id: materials.length > 0 ? Math.max(...materials.map(m => m.id)) + 1 : 1,
                        name,
                        price,
                        date,
                        amount,
                        initialAmount: amount,
                        photo: e.target.result
                    };
                    
                    materials.push(newMaterial);
                    localStorage.setItem('materials', JSON.stringify(materials));
                    
                    // Store image in local storage
                    if (!images) images = {};
                    images[`material_${newMaterial.id}`] = e.target.result;
                    localStorage.setItem('images', JSON.stringify(images));
                    
                    hideAddMaterialModal();
                    renderMaterialsTable();
                    updateDashboard();
                    initCharts();
                };
                reader.readAsDataURL(file);
            } else {
                const newMaterial = {
                    id: materials.length > 0 ? Math.max(...materials.map(m => m.id)) + 1 : 1,
                    name,
                    price,
                    date,
                    amount,
                    initialAmount: amount,
                    photo
                };
                
                materials.push(newMaterial);
                localStorage.setItem('materials', JSON.stringify(materials));
                
                hideAddMaterialModal();
                renderMaterialsTable();
                updateDashboard();
                initCharts();
            }
        }

        function editMaterial(id) {
            const material = materials.find(m => m.id === id);
            if (!material) return;
            
            document.getElementById('addMaterialModal').classList.remove('hidden');
            document.getElementById('materialName').value = material.name;
            document.getElementById('materialPrice').value = material.price;
            document.getElementById('materialDate').value = material.date;
            document.getElementById('materialAmount').value = material.amount;
            
            if (material.photo && !material.photo.startsWith('http')) {
                document.getElementById('materialPreviewImage').src = material.photo;
                document.getElementById('materialPhotoPreview').classList.remove('hidden');
            } else {
                document.getElementById('materialPhotoPreview').classList.add('hidden');
            }
            
            // Change save button to update
            const saveButton = document.querySelector('#addMaterialModal button:first-of-type');
            saveButton.textContent = 'Обновить';
            saveButton.onclick = function() {
                updateMaterial(id);
            };
        }

        function updateMaterial(id) {
            const materialIndex = materials.findIndex(m => m.id === id);
            if (materialIndex === -1) return;
            
            const name = document.getElementById('materialName').value;
            const price = parseFloat(document.getElementById('materialPrice').value);
            const date = document.getElementById('materialDate').value;
            const amount = parseFloat(document.getElementById('materialAmount').value);
            const photoInput = document.getElementById('materialPhoto');
            
            if (!name || !price || !date || !amount) {
                alert('Пожалуйста, заполните все обязательные поля');
                return;
            }
            
            let photo = materials[materialIndex].photo;
            if (photoInput.files.length > 0) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    materials[materialIndex] = {
                        ...materials[materialIndex],
                        name,
                        price,
                        date,
                        amount,
                        photo: e.target.result
                    };
                    
                    localStorage.setItem('materials', JSON.stringify(materials));
                    
                    // Update image in local storage
                    if (!images) images = {};
                    images[`material_${id}`] = e.target.result;
                    localStorage.setItem('images', JSON.stringify(images));
                    
                    hideAddMaterialModal();
                    renderMaterialsTable();
                    updateDashboard();
                    initCharts();
                };
                reader.readAsDataURL(photoInput.files[0]);
            } else {
                materials[materialIndex] = {
                    ...materials[materialIndex],
                    name,
                    price,
                    date,
                    amount,
                    photo
                };
                
                localStorage.setItem('materials', JSON.stringify(materials));
                
                hideAddMaterialModal();
                renderMaterialsTable();
                updateDashboard();
                initCharts();
            }
        }

        function deleteMaterial(id) {
            if (confirm('Вы уверены, что хотите удалить этот материал?')) {
                materials = materials.filter(m => m.id !== id);
                localStorage.setItem('materials', JSON.stringify(materials));
                
                // Also delete products that use this material
                products = products.filter(p => p.materialId !== id);
                localStorage.setItem('products', JSON.stringify(products));
                
                // Remove any images associated with this material
                if (images && images[`material_${id}`]) {
                    delete images[`material_${id}`];
                    localStorage.setItem('images', JSON.stringify(images));
                }
                
                renderMaterialsTable();
                renderProductsGrid();
                updateDashboard();
                initCharts();
            }
        }

        // Product CRUD operations
        function showAddProductModal() {
            document.getElementById('addProductModal').classList.remove('hidden');
            document.getElementById('productPhotosPreview').classList.add('hidden');
            document.getElementById('productName').value = '';
            document.getElementById('productWeight').value = '';
            document.getElementById('productPrice').value = '';
            document.getElementById('productDate').value = '';
            document.getElementById('productStatus').value = 'В продаже';
            document.getElementById('productPhotos').value = '';
            
            // Fill materials dropdown
            const materialSelect = document.getElementById('productMaterial');
            materialSelect.innerHTML = '';
            materials.forEach(material => {
                const option = document.createElement('option');
                option.value = material.id;
                option.textContent = material.name;
                materialSelect.appendChild(option);
            });
            
            // Set save button to add
            const saveButton = document.querySelector('#addProductModal button:first-of-type');
            saveButton.textContent = 'Сохранить';
            saveButton.onclick = saveProduct;
        }

        function hideAddProductModal() {
            document.getElementById('addProductModal').classList.add('hidden');
        }

        function saveProduct() {
            const name = document.getElementById('productName').value;
            const materialId = parseInt(document.getElementById('productMaterial').value);
            const weight = parseFloat(document.getElementById('productWeight').value);
            const price = parseFloat(document.getElementById('productPrice').value);
            const date = document.getElementById('productDate').value;
            const status = document.getElementById('productStatus').value;
            const photosInput = document.getElementById('productPhotos');
            
            if (!name || !materialId || !weight || !price || !date || !status) {
                alert('Пожалуйста, заполните все обязательные поля');
                return;
            }
            
            let photos = ['https://via.placeholder.com/150?text=Product'];
            if (photosInput.files.length > 0) {
                photos = [];
                for (let i = 0; i < Math.min(photosInput.files.length, 3); i++) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        photos.push(e.target.result);
                        
                        // Store image in local storage
                        if (!images) images = {};
                        images[`product_${newProduct.id}_${i}`] = e.target.result;
                        localStorage.setItem('images', JSON.stringify(images));
                    };
                    reader.readAsDataURL(photosInput.files[i]);
                }
            }
            
            const newProduct = {
                id: products.length > 0 ? Math.max(...products.map(p => p.id)) + 1 : 1,
                name,
                materialId,
                weight,
                price,
                date,
                status,
                photos
            };
            
            products.push(newProduct);
            localStorage.setItem('products', JSON.stringify(products));
            
            hideAddProductModal();
            renderProductsGrid();
            updateDashboard();
            initCharts();
        }

        function editProduct(id) {
            const product = products.find(p => p.id === id);
            if (!product) return;
            
            document.getElementById('addProductModal').classList.remove('hidden');
            document.getElementById('productName').value = product.name;
            document.getElementById('productWeight').value = product.weight;
            document.getElementById('productPrice').value = product.price;
            document.getElementById('productDate').value = product.date;
            document.getElementById('productStatus').value = product.status;
            
            // Fill materials dropdown
            const materialSelect = document.getElementById('productMaterial');
            materialSelect.innerHTML = '';
            materials.forEach(material => {
                const option = document.createElement('option');
                option.value = material.id;
                option.textContent = material.name;
                option.selected = material.id === product.materialId;
                materialSelect.appendChild(option);
            });
            
            // Show photos preview
            const previewContainer = document.getElementById('productPhotosPreview');
            previewContainer.innerHTML = '';
            
            if (product.photos && product.photos.length > 0) {
                product.photos.forEach(photo => {
                    const img = document.createElement('img');
                    img.src = photo;
                    img.className = 'h-20 w-full object-cover rounded-md';
                    previewContainer.appendChild(img);
                });
                previewContainer.classList.remove('hidden');
            } else {
                previewContainer.classList.add('hidden');
            }
            
            // Change save button to update
            const saveButton = document.querySelector('#addProductModal button:first-of-type');
            saveButton.textContent = 'Обновить';
            saveButton.onclick = function() {
                updateProduct(id);
            };
        }

        function updateProduct(id) {
            const productIndex = products.findIndex(p => p.id === id);
            if (productIndex === -1) return;
            
            const name = document.getElementById('productName').value;
            const materialId = parseInt(document.getElementById('productMaterial').value);
            const weight = parseFloat(document.getElementById('productWeight').value);
            const price = parseFloat(document.getElementById('productPrice').value);
            const date = document.getElementById('productDate').value;
            const status = document.getElementById('productStatus').value;
            const photosInput = document.getElementById('productPhotos');
            
            if (!name || !materialId || !weight || !price || !date || !status) {
                alert('Пожалуйста, заполните все обязательные поля');
                return;
            }
            
            let photos = products[productIndex].photos;
            if (photosInput.files.length > 0) {
                photos = [];
                for (let i = 0; i < Math.min(photosInput.files.length, 3); i++) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        photos.push(e.target.result);
                        
                        // Store image in local storage
                        if (!images) images = {};
                        images[`product_${id}_${i}`] = e.target.result;
                        localStorage.setItem('images', JSON.stringify(images));
                    };
                    reader.readAsDataURL(photosInput.files[i]);
                }
            }
            
            products[productIndex] = {
                ...products[productIndex],
                name,
                materialId,
                weight,
                price,
                date,
                status,
                photos
            };
            
            localStorage.setItem('products', JSON.stringify(products));
            
            hideAddProductModal();
            renderProductsGrid();
            updateDashboard();
            initCharts();
        }

        function deleteProduct(id) {
            if (confirm('Вы уверены, что хотите удалить этот продукт?')) {
                products = products.filter(p => p.id !== id);
                localStorage.setItem('products', JSON.stringify(products));
                
                // Also delete sales of this product
                sales = sales.filter(s => s.productId !== id);
                localStorage.setItem('sales', JSON.stringify(sales));
                
                // Remove any images associated with this product
                if (images) {
                    for (let i = 0; i < 3; i++) {
                        if (images[`product_${id}_${i}`]) {
                            delete images[`product_${id}_${i}`];
                        }
                    }
                    localStorage.setItem('images', JSON.stringify(images));
                }
                
                renderProductsGrid();
                renderSalesTable();
                updateDashboard();
                initCharts();
            }
        }

        // Show product photos
        function showProductPhotos(id) {
            const product = products.find(p => p.id === id);
            if (!product || !product.photos || product.photos.length === 0) return;
            
            // Create modal with larger images
            const modalHtml = `
                <div id="productPhotosModal" class="fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center">
                    <div class="max-w-4xl w-full p-4">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-white text-lg">${product.name}</h3>
                            <button onclick="closeProductPhotosModal()" class="text-white text-xl">&times;</button>
                        </div>
                        <div class="grid grid-cols-1 gap-4">
                            ${product.photos.map(photo => `
                                <img src="${photo}" class="w-full rounded-lg">
                            `).join('')}
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHtml);
        }

        function closeProductPhotosModal() {
            const modal = document.getElementById('productPhotosModal');
            if (modal) modal.remove();
        }

        // Sales operations
        function filterProducts() {
            renderProductsGrid(document.getElementById('productFilterStatus').value);
        }

        function filterSales() {
            const from = document.getElementById('salesDateFrom').value;
            const to = document.getElementById('salesDateTo').value;
            renderSalesTable(from, to);
        }

        function deleteSale(id) {
            if(confirm('Удалить продажу?')) {
                sales = sales.filter(s => s.id !== id);
                localStorage.setItem('sales', JSON.stringify(sales));
                renderSalesTable();
                updateDashboard();
            }
        }

        // Cost calculator functions
        function populateCostMaterialDropdown() {
            const select = document.getElementById('costMaterial');
            select.innerHTML = '';
            
            materials.forEach(material => {
                const option = document.createElement('option');
                option.value = material.id;
                option.textContent = material.name;
                select.appendChild(option);
            });
        }

        function saveCostSettings() {
            costSettings = {
                electricity: parseFloat(document.getElementById('electricityCost').value) || 5.0,
                depreciation: parseFloat(document.getElementById('depreciationCost').value) || 50.0,
                other: parseFloat(document.getElementById('otherCost').value) || 20.0
            };
            
            localStorage.setItem('costSettings', JSON.stringify(costSettings));
            alert('Настройки сохранены');
        }

        function calculateCost() {
            const materialId = parseInt(document.getElementById('costMaterial').value);
            const weight = parseFloat(document.getElementById('costWeight').value);
            const time = parseFloat(document.getElementById('costTime').value);
            
            if (!materialId || !weight || !time) {
                alert('Пожалуйста, заполните все поля');
                return;
            }
            
            const material = materials.find(m => m.id === materialId);
            if (!material) return;
            
            // Calculate plastic cost
            const plasticCost = (weight / 1000) * material.price;
            
            // Calculate electricity cost (assuming 0.3 kW average power usage)
            const electricityCost = time * costSettings.electricity * 0.3;
            
            // Calculate depreciation
            const depreciationCost = time * costSettings.depreciation;
            
            // Calculate other costs
            const otherCost = time * costSettings.other;
            
            // Total cost
            const totalCost = plasticCost + electricityCost + depreciationCost + otherCost;
            
            // Display results
            document.getElementById('plasticCost').textContent = `${plasticCost.toFixed(2)} ₽`;
            document.getElementById('electricityCostResult').textContent = `${electricityCost.toFixed(2)} ₽`;
            document.getElementById('depreciationCostResult').textContent = `${depreciationCost.toFixed(2)} ₽`;
            document.getElementById('otherCostResult').textContent = `${otherCost.toFixed(2)} ₽`;
            document.getElementById('totalCost').textContent = `${totalCost.toFixed(2)} ₽`;
            
            // Show formula
            document.getElementById('costFormula').textContent = 
                `Формула: (${weight}г / 1000) * ${material.price}₽ + ${time}ч * ${0.3 * costSettings.electricity}₽ + ${time}ч * ${costSettings.depreciation}₽ + ${time}ч * ${costSettings.other}₽`;
        }

        // Data export/import
        function exportData() {
            const data = {
                materials: materials,
                products: products,
                sales: sales,
                costSettings: costSettings
            };
            
            const dataStr = JSON.stringify(data);
            const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
            
            const exportFile = document.createElement('a');
            exportFile.setAttribute('href', dataUri);
            exportFile.setAttribute('download', '3d_print_data.json');
            exportFile.click();
        }

        function importData() {
            const file = document.getElementById('importFile').files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const data = JSON.parse(e.target.result);
                    if (data.materials) materials = data.materials;
                    if (data.products) products = data.products;
                    if (data.sales) sales = data.sales;
                    if (data.costSettings) costSettings = data.costSettings;
                    
                    localStorage.setItem('materials', JSON.stringify(materials));
                    localStorage.setItem('products', JSON.stringify(products));
                    localStorage.setItem('sales', JSON.stringify(sales));
                    localStorage.setItem('costSettings', JSON.stringify(costSettings));
                    
                    renderMaterialsTable();
                    renderProductsGrid();
                    renderSalesTable();
                    updateDashboard();
                    initCharts();
                    populateCostMaterialDropdown();
                    
                    alert('Данные успешно импортированы');
                } catch (error) {
                    alert('Ошибка при импорте данных: ' + error.message);
                }
            };
            reader.readAsText(file);
        }

        // Start app
        window.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>

вот целый код просто перепеши его как надо